diff options
author | chansuke <chansuke@georepublic.de> | 2018-09-18 23:24:15 +0900 |
---|---|---|
committer | Josh Matthews <josh@joshmatthews.net> | 2018-09-19 17:40:47 -0400 |
commit | c37a345dc9f4dda6ea29c42f96f6c7201c42cbac (patch) | |
tree | 1f05b49bac02318455a59d5b143c186fd872bdb9 /components/script/dom | |
parent | 2ca7a134736bb4759ff209c1bc0b6dc3cc1984c9 (diff) | |
download | servo-c37a345dc9f4dda6ea29c42f96f6c7201c42cbac.tar.gz servo-c37a345dc9f4dda6ea29c42f96f6c7201c42cbac.zip |
Format script component
Diffstat (limited to 'components/script/dom')
328 files changed, 19087 insertions, 12524 deletions
diff --git a/components/script/dom/abstractworker.rs b/components/script/dom/abstractworker.rs index 9a72316810b..2038ff62476 100644 --- a/components/script/dom/abstractworker.rs +++ b/components/script/dom/abstractworker.rs @@ -12,7 +12,7 @@ pub enum WorkerScriptMsg { /// Common variants associated with the script messages Common(CommonScriptMsg), /// Message sent through Worker.postMessage - DOMMessage(StructuredCloneData) + DOMMessage(StructuredCloneData), } pub struct SimpleWorkerErrorHandler<T: DomObject> { @@ -21,8 +21,6 @@ pub struct SimpleWorkerErrorHandler<T: DomObject> { impl<T: DomObject> SimpleWorkerErrorHandler<T> { pub fn new(addr: Trusted<T>) -> SimpleWorkerErrorHandler<T> { - SimpleWorkerErrorHandler { - addr: addr - } + SimpleWorkerErrorHandler { addr: addr } } } diff --git a/components/script/dom/abstractworkerglobalscope.rs b/components/script/dom/abstractworkerglobalscope.rs index e3e6fbcf813..051469520ec 100644 --- a/components/script/dom/abstractworkerglobalscope.rs +++ b/components/script/dom/abstractworkerglobalscope.rs @@ -25,7 +25,10 @@ pub struct SendableWorkerScriptChan { impl ScriptChan for SendableWorkerScriptChan { fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> { - let msg = DedicatedWorkerScriptMsg::CommonWorker(self.worker.clone(), WorkerScriptMsg::Common(msg)); + let msg = DedicatedWorkerScriptMsg::CommonWorker( + self.worker.clone(), + WorkerScriptMsg::Common(msg), + ); self.sender.send(msg).map_err(|_| ()) } @@ -48,10 +51,11 @@ pub struct WorkerThreadWorkerChan { impl ScriptChan for WorkerThreadWorkerChan { fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> { - let msg = DedicatedWorkerScriptMsg::CommonWorker(self.worker.clone(), WorkerScriptMsg::Common(msg)); - self.sender - .send(msg) - .map_err(|_| ()) + let msg = DedicatedWorkerScriptMsg::CommonWorker( + self.worker.clone(), + WorkerScriptMsg::Common(msg), + ); + self.sender.send(msg).map_err(|_| ()) } fn clone(&self) -> Box<ScriptChan + Send> { @@ -67,7 +71,7 @@ impl ScriptPort for Receiver<DedicatedWorkerScriptMsg> { let common_msg = match self.recv() { Some(DedicatedWorkerScriptMsg::CommonWorker(_worker, common_msg)) => common_msg, None => return Err(()), - Some(DedicatedWorkerScriptMsg::WakeUp) => panic!("unexpected worker event message!") + Some(DedicatedWorkerScriptMsg::WakeUp) => panic!("unexpected worker event message!"), }; match common_msg { WorkerScriptMsg::Common(script_msg) => Ok(script_msg), @@ -90,14 +94,17 @@ pub trait WorkerEventLoopMethods { } // https://html.spec.whatwg.org/multipage/#worker-event-loop -pub fn run_worker_event_loop<T, TimerMsg, WorkerMsg, Event>(worker_scope: &T, - worker: Option<&TrustedWorkerAddress>) -where +pub fn run_worker_event_loop<T, TimerMsg, WorkerMsg, Event>( + worker_scope: &T, + worker: Option<&TrustedWorkerAddress>, +) where TimerMsg: Send, WorkerMsg: QueuedTaskConversion + Send, - T: WorkerEventLoopMethods<TimerMsg = TimerMsg, WorkerMsg = WorkerMsg, Event = Event> - + DerivedFrom<WorkerGlobalScope> + DerivedFrom<GlobalScope> - + DomObject { + T: WorkerEventLoopMethods<TimerMsg = TimerMsg, WorkerMsg = WorkerMsg, Event = Event> + + DerivedFrom<WorkerGlobalScope> + + DerivedFrom<GlobalScope> + + DomObject, +{ let scope = worker_scope.upcast::<WorkerGlobalScope>(); let timer_event_port = worker_scope.timer_event_port(); let devtools_port = match scope.from_devtools_sender() { @@ -140,8 +147,10 @@ where // Step 6 let _ar = match worker { Some(worker) => worker_scope.handle_worker_post_event(worker), - None => None + None => None, }; - worker_scope.upcast::<GlobalScope>().perform_a_microtask_checkpoint(); + worker_scope + .upcast::<GlobalScope>() + .perform_a_microtask_checkpoint(); } } diff --git a/components/script/dom/activation.rs b/components/script/dom/activation.rs index 029e77ed449..9498f17bf17 100644 --- a/components/script/dom/activation.rs +++ b/components/script/dom/activation.rs @@ -56,12 +56,14 @@ pub enum ActivationSource { } // https://html.spec.whatwg.org/multipage/#run-synthetic-click-activation-steps -pub fn synthetic_click_activation(element: &Element, - ctrl_key: bool, - shift_key: bool, - alt_key: bool, - meta_key: bool, - source: ActivationSource) { +pub fn synthetic_click_activation( + element: &Element, + ctrl_key: bool, + shift_key: bool, + alt_key: bool, + meta_key: bool, + source: ActivationSource, +) { // Step 1 if element.click_in_progress() { return; @@ -78,23 +80,25 @@ pub fn synthetic_click_activation(element: &Element, // https://html.spec.whatwg.org/multipage/#fire-a-synthetic-mouse-event let win = window_from_node(element); let target = element.upcast::<EventTarget>(); - let mouse = MouseEvent::new(&win, - DOMString::from("click"), - EventBubbles::DoesNotBubble, - EventCancelable::NotCancelable, - Some(&win), - 1, - 0, - 0, - 0, - 0, - ctrl_key, - shift_key, - alt_key, - meta_key, - 0, - None, - None); + let mouse = MouseEvent::new( + &win, + DOMString::from("click"), + EventBubbles::DoesNotBubble, + EventCancelable::NotCancelable, + Some(&win), + 1, + 0, + 0, + 0, + 0, + ctrl_key, + shift_key, + alt_key, + meta_key, + 0, + None, + None, + ); let event = mouse.upcast::<Event>(); if source == ActivationSource::FromClick { event.set_trusted(false); diff --git a/components/script/dom/attr.rs b/components/script/dom/attr.rs index 333b2ae413e..e14dadec1a0 100644 --- a/components/script/dom/attr.rs +++ b/components/script/dom/attr.rs @@ -36,13 +36,14 @@ pub struct Attr { } impl Attr { - fn new_inherited(local_name: LocalName, - value: AttrValue, - name: LocalName, - namespace: Namespace, - prefix: Option<Prefix>, - owner: Option<&Element>) - -> Attr { + fn new_inherited( + local_name: LocalName, + value: AttrValue, + name: LocalName, + namespace: Namespace, + prefix: Option<Prefix>, + owner: Option<&Element>, + ) -> Attr { Attr { reflector_: Reflector::new(), identifier: AttrIdentifier { @@ -56,25 +57,21 @@ impl Attr { } } - pub fn new(window: &Window, - local_name: LocalName, - value: AttrValue, - name: LocalName, - namespace: Namespace, - prefix: Option<Prefix>, - owner: Option<&Element>) - -> DomRoot<Attr> { + pub fn new( + window: &Window, + local_name: LocalName, + value: AttrValue, + name: LocalName, + namespace: Namespace, + prefix: Option<Prefix>, + owner: Option<&Element>, + ) -> DomRoot<Attr> { reflect_dom_object( Box::new(Attr::new_inherited( - local_name, - value, - name, - namespace, - prefix, - owner + local_name, value, name, namespace, prefix, owner, )), window, - AttrBinding::Wrap + AttrBinding::Wrap, ) } @@ -110,9 +107,7 @@ impl AttrMethods for Attr { // https://dom.spec.whatwg.org/#dom-attr-value fn SetValue(&self, value: DOMString) { if let Some(owner) = self.owner() { - let value = owner.parse_attribute(&self.identifier.namespace, - self.local_name(), - value); + let value = owner.parse_attribute(&self.identifier.namespace, self.local_name(), value); self.set_value(value, &owner); } else { *self.value.borrow_mut() = AttrValue::String(value.into()); @@ -175,7 +170,6 @@ impl AttrMethods for Attr { } } - impl Attr { pub fn set_value(&self, mut value: AttrValue, owner: &Element) { let name = self.local_name().clone(); @@ -191,7 +185,12 @@ impl Attr { MutationObserver::queue_a_mutation_record(owner.upcast::<Node>(), mutation); if owner.get_custom_element_definition().is_some() { - let reaction = CallbackReaction::AttributeChanged(name, Some(old_value), Some(new_value), namespace); + let reaction = CallbackReaction::AttributeChanged( + name, + Some(old_value), + Some(new_value), + namespace, + ); ScriptThread::enqueue_callback_reaction(owner, reaction, None); } @@ -229,7 +228,7 @@ impl Attr { (Some(old), None) => { // Already gone from the list of attributes of old owner. assert!(old.get_attribute(&ns, &self.identifier.local_name).r() != Some(self)) - } + }, (Some(old), Some(new)) => assert_eq!(&*old, new), _ => {}, } diff --git a/components/script/dom/audiobuffersourcenode.rs b/components/script/dom/audiobuffersourcenode.rs index e2056535386..b534acead44 100644 --- a/components/script/dom/audiobuffersourcenode.rs +++ b/components/script/dom/audiobuffersourcenode.rs @@ -98,7 +98,11 @@ impl AudioBufferSourceNode { options: &AudioBufferSourceOptions, ) -> Fallible<DomRoot<AudioBufferSourceNode>> { let node = AudioBufferSourceNode::new_inherited(window, context, options)?; - Ok(reflect_dom_object(Box::new(node), window, AudioBufferSourceNodeBinding::Wrap)) + Ok(reflect_dom_object( + Box::new(node), + window, + AudioBufferSourceNodeBinding::Wrap, + )) } pub fn Constructor( diff --git a/components/script/dom/audiocontext.rs b/components/script/dom/audiocontext.rs index 519a73972a5..eef971fcba5 100644 --- a/components/script/dom/audiocontext.rs +++ b/components/script/dom/audiocontext.rs @@ -36,9 +36,8 @@ impl AudioContext { // https://webaudio.github.io/web-audio-api/#AudioContext-constructors fn new_inherited(options: &AudioContextOptions) -> AudioContext { // Steps 1-3. - let context = BaseAudioContext::new_inherited( - BaseAudioContextOptions::AudioContext(options.into()), - ); + let context = + BaseAudioContext::new_inherited(BaseAudioContextOptions::AudioContext(options.into())); // Step 4.1. let latency_hint = options.latencyHint; diff --git a/components/script/dom/audiodestinationnode.rs b/components/script/dom/audiodestinationnode.rs index eb3f0873156..4c394919671 100644 --- a/components/script/dom/audiodestinationnode.rs +++ b/components/script/dom/audiodestinationnode.rs @@ -22,8 +22,8 @@ impl AudioDestinationNode { context: &BaseAudioContext, options: &AudioNodeOptions, ) -> AudioDestinationNode { - let node_options = options.unwrap_or(2, ChannelCountMode::Max, - ChannelInterpretation::Speakers); + let node_options = + options.unwrap_or(2, ChannelCountMode::Max, ChannelInterpretation::Speakers); AudioDestinationNode { node: AudioNode::new_inherited_for_id( context.destination_node(), diff --git a/components/script/dom/audiolistener.rs b/components/script/dom/audiolistener.rs index bf6c9b20d44..0287816f921 100644 --- a/components/script/dom/audiolistener.rs +++ b/components/script/dom/audiolistener.rs @@ -28,10 +28,7 @@ pub struct AudioListener { } impl AudioListener { - fn new_inherited( - window: &Window, - context: &BaseAudioContext, - ) -> AudioListener { + fn new_inherited(window: &Window, context: &BaseAudioContext) -> AudioListener { let node = context.listener(); let position_x = AudioParam::new( @@ -90,7 +87,7 @@ impl AudioListener { node, ParamType::Forward(ParamDir::Z), AutomationRate::A_rate, - -1., // default value + -1., // default value f32::MIN, // min value f32::MAX, // max value ); @@ -139,10 +136,7 @@ impl AudioListener { } #[allow(unrooted_must_root)] - pub fn new( - window: &Window, - context: &BaseAudioContext, - ) -> DomRoot<AudioListener> { + pub fn new(window: &Window, context: &BaseAudioContext) -> DomRoot<AudioListener> { let node = AudioListener::new_inherited(window, context); reflect_dom_object(Box::new(node), window, AudioListenerBinding::Wrap) } diff --git a/components/script/dom/audionode.rs b/components/script/dom/audionode.rs index db0d5668b17..e227f7282ff 100644 --- a/components/script/dom/audionode.rs +++ b/components/script/dom/audionode.rs @@ -36,7 +36,6 @@ pub struct AudioNode { channel_interpretation: Cell<ChannelInterpretation>, } - impl AudioNode { pub fn new_inherited( node_type: AudioNodeInit, @@ -54,7 +53,13 @@ impl AudioNode { interpretation: options.interpretation.into(), }; let node_id = context.audio_context_impl().create_node(node_type, ch); - Ok(AudioNode::new_inherited_for_id(node_id, context, options, number_of_inputs, number_of_outputs)) + Ok(AudioNode::new_inherited_for_id( + node_id, + context, + options, + number_of_inputs, + number_of_outputs, + )) } pub fn new_inherited_for_id( @@ -177,8 +182,7 @@ impl AudioNodeMethods for AudioNode { fn Disconnect_____(&self, param: &AudioParam) -> ErrorResult { self.context .audio_context_impl() - .disconnect_to(self.node_id(), - param.node_id().param(param.param_type())); + .disconnect_to(self.node_id(), param.node_id().param(param.param_type())); Ok(()) } @@ -186,8 +190,10 @@ impl AudioNodeMethods for AudioNode { fn Disconnect______(&self, param: &AudioParam, out: u32) -> ErrorResult { self.context .audio_context_impl() - .disconnect_output_between_to(self.node_id().output(out), - param.node_id().param(param.param_type())); + .disconnect_output_between_to( + self.node_id().output(out), + param.node_id().param(param.param_type()), + ); Ok(()) } @@ -223,14 +229,14 @@ impl AudioNodeMethods for AudioNode { }, EventTargetTypeId::AudioNode(AudioNodeTypeId::PannerNode) => { if value > 2 { - return Err(Error::NotSupported) + return Err(Error::NotSupported); } - } + }, EventTargetTypeId::AudioNode(AudioNodeTypeId::ChannelMergerNode) => { if value != 1 { - return Err(Error::InvalidState) + return Err(Error::InvalidState); } - } + }, // XXX We do not support any of the other AudioNodes with // constraints yet. Add more cases here as we add support // for new AudioNodes. @@ -266,14 +272,14 @@ impl AudioNodeMethods for AudioNode { }, EventTargetTypeId::AudioNode(AudioNodeTypeId::PannerNode) => { if value == ChannelCountMode::Max { - return Err(Error::NotSupported) + return Err(Error::NotSupported); } - } + }, EventTargetTypeId::AudioNode(AudioNodeTypeId::ChannelMergerNode) => { if value != ChannelCountMode::Explicit { - return Err(Error::InvalidState) + return Err(Error::InvalidState); } - } + }, // XXX We do not support any of the other AudioNodes with // constraints yet. Add more cases here as we add support // for new AudioNodes. @@ -321,14 +327,17 @@ impl From<ChannelInterpretation> for ServoMediaChannelInterpretation { } } - impl AudioNodeOptions { - pub fn unwrap_or(&self, count: u32, mode: ChannelCountMode, - interpretation: ChannelInterpretation) -> UnwrappedAudioNodeOptions { + pub fn unwrap_or( + &self, + count: u32, + mode: ChannelCountMode, + interpretation: ChannelInterpretation, + ) -> UnwrappedAudioNodeOptions { UnwrappedAudioNodeOptions { count: self.channelCount.unwrap_or(count), mode: self.channelCountMode.unwrap_or(mode), - interpretation: self.channelInterpretation.unwrap_or(interpretation) + interpretation: self.channelInterpretation.unwrap_or(interpretation), } } } diff --git a/components/script/dom/audioparam.rs b/components/script/dom/audioparam.rs index db73619180f..40826790cbf 100644 --- a/components/script/dom/audioparam.rs +++ b/components/script/dom/audioparam.rs @@ -76,7 +76,9 @@ impl AudioParam { } fn message_node(&self, message: AudioNodeMessage) { - self.context.audio_context_impl().message_node(self.node, message); + self.context + .audio_context_impl() + .message_node(self.node, message); } pub fn context(&self) -> &BaseAudioContext { @@ -101,25 +103,25 @@ impl AudioParamMethods for AudioParam { // https://webaudio.github.io/web-audio-api/#dom-audioparam-automationrate fn SetAutomationRate(&self, automation_rate: AutomationRate) { self.automation_rate.set(automation_rate); - self.message_node( - AudioNodeMessage::SetParamRate(self.param, automation_rate.into()) - ); + self.message_node(AudioNodeMessage::SetParamRate( + self.param, + automation_rate.into(), + )); } // https://webaudio.github.io/web-audio-api/#dom-audioparam-value fn Value(&self) -> Finite<f32> { let (tx, rx) = mpsc::channel(); - self.message_node( - AudioNodeMessage::GetParamValue(self.param, tx) - ); + self.message_node(AudioNodeMessage::GetParamValue(self.param, tx)); Finite::wrap(rx.recv().unwrap()) } // https://webaudio.github.io/web-audio-api/#dom-audioparam-value fn SetValue(&self, value: Finite<f32>) { - self.message_node( - AudioNodeMessage::SetParam(self.param, UserAutomationEvent::SetValue(*value)), - ); + self.message_node(AudioNodeMessage::SetParam( + self.param, + UserAutomationEvent::SetValue(*value), + )); } // https://webaudio.github.io/web-audio-api/#dom-audioparam-defaultvalue @@ -139,12 +141,10 @@ impl AudioParamMethods for AudioParam { // https://webaudio.github.io/web-audio-api/#dom-audioparam-setvalueattime fn SetValueAtTime(&self, value: Finite<f32>, start_time: Finite<f64>) -> DomRoot<AudioParam> { - self.message_node( - AudioNodeMessage::SetParam( - self.param, - UserAutomationEvent::SetValueAtTime(*value, *start_time), - ) - ); + self.message_node(AudioNodeMessage::SetParam( + self.param, + UserAutomationEvent::SetValueAtTime(*value, *start_time), + )); DomRoot::from_ref(self) } @@ -154,12 +154,10 @@ impl AudioParamMethods for AudioParam { value: Finite<f32>, end_time: Finite<f64>, ) -> DomRoot<AudioParam> { - self.message_node( - AudioNodeMessage::SetParam( - self.param, - UserAutomationEvent::RampToValueAtTime(RampKind::Linear, *value, *end_time), - ), - ); + self.message_node(AudioNodeMessage::SetParam( + self.param, + UserAutomationEvent::RampToValueAtTime(RampKind::Linear, *value, *end_time), + )); DomRoot::from_ref(self) } @@ -169,12 +167,10 @@ impl AudioParamMethods for AudioParam { value: Finite<f32>, end_time: Finite<f64>, ) -> DomRoot<AudioParam> { - self.message_node( - AudioNodeMessage::SetParam( - self.param, - UserAutomationEvent::RampToValueAtTime(RampKind::Exponential, *value, *end_time), - ), - ); + self.message_node(AudioNodeMessage::SetParam( + self.param, + UserAutomationEvent::RampToValueAtTime(RampKind::Exponential, *value, *end_time), + )); DomRoot::from_ref(self) } @@ -185,34 +181,28 @@ impl AudioParamMethods for AudioParam { start_time: Finite<f64>, time_constant: Finite<f32>, ) -> DomRoot<AudioParam> { - self.message_node( - AudioNodeMessage::SetParam( - self.param, - UserAutomationEvent::SetTargetAtTime(*target, *start_time, (*time_constant).into()), - ), - ); + self.message_node(AudioNodeMessage::SetParam( + self.param, + UserAutomationEvent::SetTargetAtTime(*target, *start_time, (*time_constant).into()), + )); DomRoot::from_ref(self) } // https://webaudio.github.io/web-audio-api/#dom-audioparam-cancelscheduledvalues fn CancelScheduledValues(&self, cancel_time: Finite<f64>) -> DomRoot<AudioParam> { - self.message_node( - AudioNodeMessage::SetParam( - self.param, - UserAutomationEvent::CancelScheduledValues(*cancel_time), - ), - ); + self.message_node(AudioNodeMessage::SetParam( + self.param, + UserAutomationEvent::CancelScheduledValues(*cancel_time), + )); DomRoot::from_ref(self) } // https://webaudio.github.io/web-audio-api/#dom-audioparam-cancelandholdattime fn CancelAndHoldAtTime(&self, cancel_time: Finite<f64>) -> DomRoot<AudioParam> { - self.message_node( - AudioNodeMessage::SetParam( - self.param, - UserAutomationEvent::CancelAndHoldAtTime(*cancel_time), - ), - ); + self.message_node(AudioNodeMessage::SetParam( + self.param, + UserAutomationEvent::CancelAndHoldAtTime(*cancel_time), + )); DomRoot::from_ref(self) } } diff --git a/components/script/dom/audioscheduledsourcenode.rs b/components/script/dom/audioscheduledsourcenode.rs index 972d709ba69..cd913897cad 100644 --- a/components/script/dom/audioscheduledsourcenode.rs +++ b/components/script/dom/audioscheduledsourcenode.rs @@ -84,9 +84,10 @@ impl AudioScheduledSourceNodeMethods for AudioScheduledSourceNode { ); }); - self.node().message( - AudioNodeMessage::AudioScheduledSourceNode( - AudioScheduledSourceNodeMessage::RegisterOnEndedCallback(callback))); + self.node() + .message(AudioNodeMessage::AudioScheduledSourceNode( + AudioScheduledSourceNodeMessage::RegisterOnEndedCallback(callback), + )); self.started.set(true); self.node diff --git a/components/script/dom/baseaudiocontext.rs b/components/script/dom/baseaudiocontext.rs index 514a51f113b..f539f81bc4e 100644 --- a/components/script/dom/baseaudiocontext.rs +++ b/components/script/dom/baseaudiocontext.rs @@ -98,14 +98,16 @@ impl BaseAudioContext { pub fn new_inherited(options: BaseAudioContextOptions) -> BaseAudioContext { let (sample_rate, channel_count) = match options { BaseAudioContextOptions::AudioContext(ref opt) => (opt.sample_rate, 2), - BaseAudioContextOptions::OfflineAudioContext(ref opt) => (opt.sample_rate, opt.channels), + BaseAudioContextOptions::OfflineAudioContext(ref opt) => { + (opt.sample_rate, opt.channels) + }, }; let context = BaseAudioContext { eventtarget: EventTarget::new_inherited(), audio_context_impl: ServoMedia::get() - .unwrap() - .create_audio_context(options.into()), + .unwrap() + .create_audio_context(options.into()), destination: Default::default(), listener: Default::default(), in_flight_resume_promises_queue: Default::default(), @@ -312,9 +314,7 @@ impl BaseAudioContextMethods for BaseAudioContext { fn Listener(&self) -> DomRoot<AudioListener> { let global = self.global(); let window = global.as_window(); - self.listener.or_init(|| { - AudioListener::new(&window, self) - }) + self.listener.or_init(|| AudioListener::new(&window, self)) } /// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-onstatechange @@ -425,12 +425,10 @@ impl BaseAudioContextMethods for BaseAudioContext { .lock() .unwrap() .resize(channel_count as usize, Vec::new()); - }) - .progress(move |buffer, channel| { + }).progress(move |buffer, channel| { let mut decoded_audio = decoded_audio_.lock().unwrap(); decoded_audio[(channel - 1) as usize].extend_from_slice((*buffer).as_ref()); - }) - .eos(move || { + }).eos(move || { let _ = task_source.queue_with_canceller( task!(audio_decode_eos: move || { let this = this.root(); @@ -456,8 +454,7 @@ impl BaseAudioContextMethods for BaseAudioContext { }), &canceller, ); - }) - .error(move || { + }).error(move || { let _ = task_source_.queue_with_canceller( task!(audio_decode_eos: move || { let this = this_.root(); @@ -473,8 +470,7 @@ impl BaseAudioContextMethods for BaseAudioContext { }), &canceller_, ); - }) - .build(); + }).build(); self.audio_context_impl .decode_audio_data(audio_data, callbacks); } else { @@ -491,10 +487,12 @@ impl BaseAudioContextMethods for BaseAudioContext { impl From<BaseAudioContextOptions> for AudioContextOptions { fn from(options: BaseAudioContextOptions) -> Self { match options { - BaseAudioContextOptions::AudioContext(options) => - AudioContextOptions::RealTimeAudioContext(options), - BaseAudioContextOptions::OfflineAudioContext(options) => - AudioContextOptions::OfflineAudioContext(options), + BaseAudioContextOptions::AudioContext(options) => { + AudioContextOptions::RealTimeAudioContext(options) + }, + BaseAudioContextOptions::OfflineAudioContext(options) => { + AudioContextOptions::OfflineAudioContext(options) + }, } } } diff --git a/components/script/dom/beforeunloadevent.rs b/components/script/dom/beforeunloadevent.rs index bd7fc05daac..43f37a117e4 100644 --- a/components/script/dom/beforeunloadevent.rs +++ b/components/script/dom/beforeunloadevent.rs @@ -33,20 +33,23 @@ impl BeforeUnloadEvent { } pub fn new_uninitialized(window: &Window) -> DomRoot<BeforeUnloadEvent> { - reflect_dom_object(Box::new(BeforeUnloadEvent::new_inherited()), - window, - BeforeUnloadEventBinding::Wrap) + reflect_dom_object( + Box::new(BeforeUnloadEvent::new_inherited()), + window, + BeforeUnloadEventBinding::Wrap, + ) } - pub fn new(window: &Window, - type_: Atom, - bubbles: EventBubbles, - cancelable: EventCancelable) -> DomRoot<BeforeUnloadEvent> { + pub fn new( + window: &Window, + type_: Atom, + bubbles: EventBubbles, + cancelable: EventCancelable, + ) -> DomRoot<BeforeUnloadEvent> { let ev = BeforeUnloadEvent::new_uninitialized(window); { let event = ev.upcast::<Event>(); - event.init_event(type_, bool::from(bubbles), - bool::from(cancelable)); + event.init_event(type_, bool::from(bubbles), bool::from(cancelable)); } ev } diff --git a/components/script/dom/bindings/callback.rs b/components/script/dom/bindings/callback.rs index 6b4d7cd981a..ddc11ce25da 100644 --- a/components/script/dom/bindings/callback.rs +++ b/components/script/dom/bindings/callback.rs @@ -53,7 +53,7 @@ pub struct CallbackObject { /// /// ["callback context"]: https://heycam.github.io/webidl/#dfn-callback-context /// [sometimes]: https://github.com/whatwg/html/issues/2248 - incumbent: Option<Dom<GlobalScope>> + incumbent: Option<Dom<GlobalScope>>, } impl Default for CallbackObject { @@ -81,8 +81,11 @@ impl CallbackObject { unsafe fn init(&mut self, cx: *mut JSContext, callback: *mut JSObject) { self.callback.set(callback); self.permanent_js_root.set(ObjectValue(callback)); - assert!(AddRawValueRoot(cx, self.permanent_js_root.get_unsafe(), - b"CallbackObject::root\n".as_c_char_ptr())); + assert!(AddRawValueRoot( + cx, + self.permanent_js_root.get_unsafe(), + b"CallbackObject::root\n".as_c_char_ptr() + )); } } @@ -94,7 +97,6 @@ impl Drop for CallbackObject { RemoveRawValueRoot(cx, self.permanent_js_root.get_unsafe()); } } - } impl PartialEq for CallbackObject { @@ -103,7 +105,6 @@ impl PartialEq for CallbackObject { } } - /// A trait to be implemented by concrete IDL callback function and /// callback interface types. pub trait CallbackContainer { @@ -124,7 +125,6 @@ pub trait CallbackContainer { } } - /// A common base class for representing IDL callback function types. #[derive(JSTraceable, PartialEq)] #[must_root] @@ -153,9 +153,6 @@ impl CallbackFunction { } } - - - /// A common base class for representing IDL callback interface types. #[derive(JSTraceable, PartialEq)] #[must_root] @@ -194,19 +191,22 @@ impl CallbackInterface { } if !callable.is_object() || !IsCallable(callable.to_object()) { - return Err(Error::Type(format!("The value of the {} property is not callable", - name))); + return Err(Error::Type(format!( + "The value of the {} property is not callable", + name + ))); } } Ok(callable.get()) } } - /// Wraps the reflector for `p` into the compartment of `cx`. -pub fn wrap_call_this_object<T: DomObject>(cx: *mut JSContext, - p: &T, - mut rval: MutableHandleObject) { +pub fn wrap_call_this_object<T: DomObject>( + cx: *mut JSContext, + p: &T, + mut rval: MutableHandleObject, +) { rval.set(p.reflector().get_jsobject().get()); assert!(!rval.get().is_null()); @@ -217,7 +217,6 @@ pub fn wrap_call_this_object<T: DomObject>(cx: *mut JSContext, } } - /// A class that performs whatever setup we need to safely make a call while /// this class is on the stack. After `new` returns, the call is safe to make. pub struct CallSetup { @@ -241,9 +240,7 @@ pub struct CallSetup { impl CallSetup { /// Performs the setup needed to make a call. #[allow(unrooted_must_root)] - pub fn new<T: CallbackContainer>(callback: &T, - handling: ExceptionHandling) - -> CallSetup { + pub fn new<T: CallbackContainer>(callback: &T, handling: ExceptionHandling) -> CallSetup { let global = unsafe { GlobalScope::from_object(callback.callback()) }; let cx = global.get_cx(); @@ -270,8 +267,10 @@ impl Drop for CallSetup { unsafe { JS_LeaveCompartment(self.cx, self.old_compartment); if self.handling == ExceptionHandling::Report { - let _ac = JSAutoCompartment::new(self.cx, - self.exception_global.reflector().get_jsobject().get()); + let _ac = JSAutoCompartment::new( + self.cx, + self.exception_global.reflector().get_jsobject().get(), + ); report_pending_exception(self.cx, true); } drop(self.incumbent_script.take()); diff --git a/components/script/dom/bindings/cell.rs b/components/script/dom/bindings/cell.rs index c40885866b5..02c538f0506 100644 --- a/components/script/dom/bindings/cell.rs +++ b/components/script/dom/bindings/cell.rs @@ -55,7 +55,6 @@ impl<T> DomRefCell<T> { } } - /// Immutably borrows the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple @@ -67,7 +66,8 @@ impl<T> DomRefCell<T> { /// /// Panics if the value is currently mutably borrowed. pub fn borrow(&self) -> Ref<T> { - self.try_borrow().expect("DomRefCell<T> already mutably borrowed") + self.try_borrow() + .expect("DomRefCell<T> already mutably borrowed") } /// Mutably borrows the wrapped value. @@ -81,7 +81,8 @@ impl<T> DomRefCell<T> { /// /// Panics if the value is currently borrowed. pub fn borrow_mut(&self) -> RefMut<T> { - self.try_borrow_mut().expect("DomRefCell<T> already borrowed") + self.try_borrow_mut() + .expect("DomRefCell<T> already borrowed") } /// Attempts to immutably borrow the wrapped value. diff --git a/components/script/dom/bindings/constant.rs b/components/script/dom/bindings/constant.rs index b30247f887b..0329d106132 100644 --- a/components/script/dom/bindings/constant.rs +++ b/components/script/dom/bindings/constant.rs @@ -51,16 +51,15 @@ impl ConstantSpec { /// Defines constants on `obj`. /// Fails on JSAPI failure. -pub unsafe fn define_constants( - cx: *mut JSContext, - obj: HandleObject, - constants: &[ConstantSpec]) { +pub unsafe fn define_constants(cx: *mut JSContext, obj: HandleObject, constants: &[ConstantSpec]) { for spec in constants { rooted!(in(cx) let value = spec.get_value()); - assert!(JS_DefineProperty(cx, - obj, - spec.name.as_ptr() as *const libc::c_char, - value.handle(), - (JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT) as u32)); + assert!(JS_DefineProperty( + cx, + obj, + spec.name.as_ptr() as *const libc::c_char, + value.handle(), + (JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT) as u32 + )); } } diff --git a/components/script/dom/bindings/conversions.rs b/components/script/dom/bindings/conversions.rs index 0576298d49d..4f848ea97d7 100644 --- a/components/script/dom/bindings/conversions.rs +++ b/components/script/dom/bindings/conversions.rs @@ -69,8 +69,10 @@ pub trait IDLInterface { } /// A trait to mark an IDL interface as deriving from another one. -#[cfg_attr(feature = "unstable", - rustc_on_unimplemented = "The IDL interface `{Self}` is not derived from `{T}`.")] +#[cfg_attr( + feature = "unstable", + rustc_on_unimplemented = "The IDL interface `{Self}` is not derived from `{T}`." +)] pub trait DerivedFrom<T: Castable>: Castable {} impl<T: Float + ToJSValConvertible> ToJSValConvertible for Finite<T> { @@ -81,20 +83,21 @@ impl<T: Float + ToJSValConvertible> ToJSValConvertible for Finite<T> { } } -impl<T: Float + FromJSValConvertible<Config=()>> FromJSValConvertible for Finite<T> { +impl<T: Float + FromJSValConvertible<Config = ()>> FromJSValConvertible for Finite<T> { type Config = (); - unsafe fn from_jsval(cx: *mut JSContext, - value: HandleValue, - option: ()) - -> Result<ConversionResult<Finite<T>>, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + value: HandleValue, + option: (), + ) -> Result<ConversionResult<Finite<T>>, ()> { let result = match FromJSValConvertible::from_jsval(cx, value, option)? { ConversionResult::Success(v) => v, ConversionResult::Failure(error) => { // FIXME(emilio): Why throwing instead of propagating the error? throw_type_error(cx, &error); return Err(()); - } + }, }; match Finite::new(result) { Some(v) => Ok(ConversionResult::Success(v)), @@ -106,13 +109,14 @@ impl<T: Float + FromJSValConvertible<Config=()>> FromJSValConvertible for Finite } } -impl <T: DomObject + IDLInterface> FromJSValConvertible for DomRoot<T> { +impl<T: DomObject + IDLInterface> FromJSValConvertible for DomRoot<T> { type Config = (); - unsafe fn from_jsval(_cx: *mut JSContext, - value: HandleValue, - _config: Self::Config) - -> Result<ConversionResult<DomRoot<T>>, ()> { + unsafe fn from_jsval( + _cx: *mut JSContext, + value: HandleValue, + _config: Self::Config, + ) -> Result<ConversionResult<DomRoot<T>>, ()> { Ok(match root_from_handlevalue(value) { Ok(result) => ConversionResult::Success(result), Err(()) => ConversionResult::Failure("value is not an object".into()), @@ -129,19 +133,21 @@ impl<T: ToJSValConvertible + JSTraceable> ToJSValConvertible for RootedTraceable } impl<T> FromJSValConvertible for RootedTraceableBox<Heap<T>> - where - T: FromJSValConvertible + js::rust::GCMethods + Copy, - Heap<T>: JSTraceable + Default +where + T: FromJSValConvertible + js::rust::GCMethods + Copy, + Heap<T>: JSTraceable + Default, { type Config = T::Config; - unsafe fn from_jsval(cx: *mut JSContext, - value: HandleValue, - config: Self::Config) - -> Result<ConversionResult<Self>, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + value: HandleValue, + config: Self::Config, + ) -> Result<ConversionResult<Self>, ()> { T::from_jsval(cx, value, config).map(|result| match result { - ConversionResult::Success(inner) => - ConversionResult::Success(RootedTraceableBox::from_box(Heap::boxed(inner))), + ConversionResult::Success(inner) => { + ConversionResult::Success(RootedTraceableBox::from_box(Heap::boxed(inner))) + }, ConversionResult::Failure(msg) => ConversionResult::Failure(msg), }) } @@ -190,12 +196,12 @@ impl ToJSValConvertible for DOMString { // https://heycam.github.io/webidl/#es-DOMString impl FromJSValConvertible for DOMString { type Config = StringificationBehavior; - unsafe fn from_jsval(cx: *mut JSContext, - value: HandleValue, - null_behavior: StringificationBehavior) - -> Result<ConversionResult<DOMString>, ()> { - if null_behavior == StringificationBehavior::Empty && - value.get().is_null() { + unsafe fn from_jsval( + cx: *mut JSContext, + value: HandleValue, + null_behavior: StringificationBehavior, + ) -> Result<ConversionResult<DOMString>, ()> { + if null_behavior == StringificationBehavior::Empty && value.get().is_null() { Ok(ConversionResult::Success(DOMString::new())) } else { let jsstr = ToString(cx, value); @@ -231,16 +237,19 @@ pub unsafe fn jsstring_to_str(cx: *mut JSContext, s: *mut JSString) -> DOMString "Found an unpaired surrogate in a DOM string. \ If you see this in real web content, \ please comment on https://github.com/servo/servo/issues/6564" - } + }; } if opts::get().replace_surrogates { error!(message!()); s.push('\u{FFFD}'); } else { - panic!(concat!(message!(), " Use `-Z replace-surrogates` \ - on the command line to make this non-fatal.")); + panic!(concat!( + message!(), + " Use `-Z replace-surrogates` \ + on the command line to make this non-fatal." + )); } - } + }, } } s @@ -250,8 +259,11 @@ pub unsafe fn jsstring_to_str(cx: *mut JSContext, s: *mut JSString) -> DOMString // http://heycam.github.io/webidl/#es-USVString impl FromJSValConvertible for USVString { type Config = (); - unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, _: ()) - -> Result<ConversionResult<USVString>, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + value: HandleValue, + _: (), + ) -> Result<ConversionResult<USVString>, ()> { let jsstr = ToString(cx, value); if jsstr.is_null() { debug!("ToString failed"); @@ -260,23 +272,28 @@ impl FromJSValConvertible for USVString { let latin1 = JS_StringHasLatin1Chars(jsstr); if latin1 { // FIXME(ajeffrey): Convert directly from DOMString to USVString - return Ok(ConversionResult::Success( - USVString(String::from(jsstring_to_str(cx, jsstr))))); + return Ok(ConversionResult::Success(USVString(String::from( + jsstring_to_str(cx, jsstr), + )))); } let mut length = 0; let chars = JS_GetTwoByteStringCharsAndLength(cx, ptr::null(), jsstr, &mut length); assert!(!chars.is_null()); let char_vec = slice::from_raw_parts(chars as *const u16, length as usize); - Ok(ConversionResult::Success(USVString(String::from_utf16_lossy(char_vec)))) + Ok(ConversionResult::Success(USVString( + String::from_utf16_lossy(char_vec), + ))) } } // http://heycam.github.io/webidl/#es-ByteString impl ToJSValConvertible for ByteString { unsafe fn to_jsval(&self, cx: *mut JSContext, mut rval: MutableHandleValue) { - let jsstr = JS_NewStringCopyN(cx, - self.as_ptr() as *const libc::c_char, - self.len() as libc::size_t); + let jsstr = JS_NewStringCopyN( + cx, + self.as_ptr() as *const libc::c_char, + self.len() as libc::size_t, + ); if jsstr.is_null() { panic!("JS_NewStringCopyN failed"); } @@ -287,10 +304,11 @@ impl ToJSValConvertible for ByteString { // http://heycam.github.io/webidl/#es-ByteString impl FromJSValConvertible for ByteString { type Config = (); - unsafe fn from_jsval(cx: *mut JSContext, - value: HandleValue, - _option: ()) - -> Result<ConversionResult<ByteString>, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + value: HandleValue, + _option: (), + ) -> Result<ConversionResult<ByteString>, ()> { let string = ToString(cx, value); if string.is_null() { debug!("ToString failed"); @@ -304,7 +322,9 @@ impl FromJSValConvertible for ByteString { assert!(!chars.is_null()); let char_slice = slice::from_raw_parts(chars as *mut u8, length as usize); - return Ok(ConversionResult::Success(ByteString::new(char_slice.to_vec()))); + return Ok(ConversionResult::Success(ByteString::new( + char_slice.to_vec(), + ))); } let mut length = 0; @@ -315,13 +335,13 @@ impl FromJSValConvertible for ByteString { throw_type_error(cx, "Invalid ByteString"); Err(()) } else { - Ok(ConversionResult::Success( - ByteString::new(char_vec.iter().map(|&c| c as u8).collect()))) + Ok(ConversionResult::Success(ByteString::new( + char_vec.iter().map(|&c| c as u8).collect(), + ))) } } } - impl ToJSValConvertible for Reflector { unsafe fn to_jsval(&self, cx: *mut JSContext, mut rval: MutableHandleValue) { let obj = self.get_jsobject().get(); @@ -389,10 +409,12 @@ pub unsafe fn get_dom_class(obj: *mut JSObject) -> Result<&'static DOMClass, ()> /// not an object for a DOM object of the given type (as defined by the /// proto_id and proto_depth). #[inline] -pub unsafe fn private_from_proto_check<F>(mut obj: *mut JSObject, - proto_check: F) - -> Result<*const libc::c_void, ()> - where F: Fn(&'static DOMClass) -> bool +pub unsafe fn private_from_proto_check<F>( + mut obj: *mut JSObject, + proto_check: F, +) -> Result<*const libc::c_void, ()> +where + F: Fn(&'static DOMClass) -> bool, { let dom_class = get_dom_class(obj).or_else(|_| { if IsWrapper(obj) { @@ -423,11 +445,10 @@ pub unsafe fn private_from_proto_check<F>(mut obj: *mut JSObject, /// Get a `*const T` for a DOM object accessible from a `JSObject`. pub fn native_from_object<T>(obj: *mut JSObject) -> Result<*const T, ()> - where T: DomObject + IDLInterface +where + T: DomObject + IDLInterface, { - unsafe { - private_from_proto_check(obj, T::derives).map(|ptr| ptr as *const T) - } + unsafe { private_from_proto_check(obj, T::derives).map(|ptr| ptr as *const T) } } /// Get a `DomRoot<T>` for the given DOM object, unwrapping any wrapper @@ -437,7 +458,8 @@ pub fn native_from_object<T>(obj: *mut JSObject) -> Result<*const T, ()> /// not a reflector for a DOM object of the given type (as defined by the /// proto_id and proto_depth). pub fn root_from_object<T>(obj: *mut JSObject) -> Result<DomRoot<T>, ()> - where T: DomObject + IDLInterface +where + T: DomObject + IDLInterface, { native_from_object(obj).map(|ptr| unsafe { DomRoot::from_ref(&*ptr) }) } @@ -445,7 +467,8 @@ pub fn root_from_object<T>(obj: *mut JSObject) -> Result<DomRoot<T>, ()> /// Get a `*const T` for a DOM object accessible from a `HandleValue`. /// Caller is responsible for throwing a JS exception if needed in case of error. pub fn native_from_handlevalue<T>(v: HandleValue) -> Result<*const T, ()> - where T: DomObject + IDLInterface +where + T: DomObject + IDLInterface, { if !v.get().is_object() { return Err(()); @@ -456,7 +479,8 @@ pub fn native_from_handlevalue<T>(v: HandleValue) -> Result<*const T, ()> /// Get a `DomRoot<T>` for a DOM object accessible from a `HandleValue`. /// Caller is responsible for throwing a JS exception if needed in case of error. pub fn root_from_handlevalue<T>(v: HandleValue) -> Result<DomRoot<T>, ()> - where T: DomObject + IDLInterface +where + T: DomObject + IDLInterface, { if !v.get().is_object() { return Err(()); @@ -466,7 +490,8 @@ pub fn root_from_handlevalue<T>(v: HandleValue) -> Result<DomRoot<T>, ()> /// Get a `DomRoot<T>` for a DOM object accessible from a `HandleObject`. pub fn root_from_handleobject<T>(obj: HandleObject) -> Result<DomRoot<T>, ()> - where T: DomObject + IDLInterface +where + T: DomObject + IDLInterface, { root_from_object(obj.get()) } @@ -487,12 +512,12 @@ pub unsafe fn is_array_like(cx: *mut JSContext, value: HandleValue) -> bool { } /// Get a property from a JS object. -pub unsafe fn get_property_jsval(cx: *mut JSContext, - object: HandleObject, - name: &str, - mut rval: MutableHandleValue) - -> Fallible<()> -{ +pub unsafe fn get_property_jsval( + cx: *mut JSContext, + object: HandleObject, + name: &str, + mut rval: MutableHandleValue, +) -> Fallible<()> { rval.set(UndefinedValue()); let cname = match ffi::CString::new(name) { Ok(cname) => cname, @@ -506,12 +531,14 @@ pub unsafe fn get_property_jsval(cx: *mut JSContext, } /// Get a property from a JS object, and convert it to a Rust value. -pub unsafe fn get_property<T>(cx: *mut JSContext, - object: HandleObject, - name: &str, - option: T::Config) - -> Fallible<Option<T>> where - T: FromJSValConvertible +pub unsafe fn get_property<T>( + cx: *mut JSContext, + object: HandleObject, + name: &str, + option: T::Config, +) -> Fallible<Option<T>> +where + T: FromJSValConvertible, { debug!("Getting property {}.", name); rooted!(in(cx) let mut result = UndefinedValue()); diff --git a/components/script/dom/bindings/error.rs b/components/script/dom/bindings/error.rs index 7c68de0df18..ce045b2c9d3 100644 --- a/components/script/dom/bindings/error.rs +++ b/components/script/dom/bindings/error.rs @@ -126,7 +126,7 @@ pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: &GlobalScope, resu Error::JSFailed => { assert!(JS_IsExceptionPending(cx)); return; - } + }, }; assert!(!JS_IsExceptionPending(cx)); @@ -149,8 +149,7 @@ pub struct ErrorInfo { } impl ErrorInfo { - unsafe fn from_native_error(cx: *mut JSContext, object: HandleObject) - -> Option<ErrorInfo> { + unsafe fn from_native_error(cx: *mut JSContext, object: HandleObject) -> Option<ErrorInfo> { let report = JS_ErrorFromException(cx, object); if report.is_null() { return None; @@ -205,7 +204,9 @@ impl ErrorInfo { /// The `dispatch_event` argument is temporary and non-standard; passing false /// prevents dispatching the `error` event. pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) { - if !JS_IsExceptionPending(cx) { return; } + if !JS_IsExceptionPending(cx) { + return; + } rooted!(in(cx) let mut value = UndefinedValue()); if !JS_GetPendingException(cx, value.handle_mut()) { @@ -219,23 +220,19 @@ pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) rooted!(in(cx) let object = value.to_object()); ErrorInfo::from_native_error(cx, object.handle()) .or_else(|| ErrorInfo::from_dom_exception(object.handle())) - .unwrap_or_else(|| { - ErrorInfo { - message: format!("uncaught exception: unknown (can't convert to string)"), - filename: String::new(), - lineno: 0, - column: 0, - } + .unwrap_or_else(|| ErrorInfo { + message: format!("uncaught exception: unknown (can't convert to string)"), + filename: String::new(), + lineno: 0, + column: 0, }) } else { match USVString::from_jsval(cx, value.handle(), ()) { - Ok(ConversionResult::Success(USVString(string))) => { - ErrorInfo { - message: format!("uncaught exception: {}", string), - filename: String::new(), - lineno: 0, - column: 0, - } + Ok(ConversionResult::Success(USVString(string))) => ErrorInfo { + message: format!("uncaught exception: {}", string), + filename: String::new(), + lineno: 0, + column: 0, }, _ => { panic!("Uncaught exception: failed to stringify primitive"); @@ -243,15 +240,13 @@ pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) } }; - error!("Error at {}:{}:{} {}", - error_info.filename, - error_info.lineno, - error_info.column, - error_info.message); + error!( + "Error at {}:{}:{} {}", + error_info.filename, error_info.lineno, error_info.column, error_info.message + ); if dispatch_event { - GlobalScope::from_context(cx) - .report_an_error(error_info, value.handle()); + GlobalScope::from_context(cx).report_an_error(error_info, value.handle()); } } @@ -259,14 +254,21 @@ pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) /// given DOM type. pub unsafe fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) { debug_assert!(!JS_IsExceptionPending(cx)); - let error = format!("\"this\" object does not implement interface {}.", - proto_id_to_name(proto_id)); + let error = format!( + "\"this\" object does not implement interface {}.", + proto_id_to_name(proto_id) + ); throw_type_error(cx, &error); } impl Error { /// Convert this error value to a JS value, consuming it in the process. - pub unsafe fn to_jsval(self, cx: *mut JSContext, global: &GlobalScope, rval: MutableHandleValue) { + pub unsafe fn to_jsval( + self, + cx: *mut JSContext, + global: &GlobalScope, + rval: MutableHandleValue, + ) { assert!(!JS_IsExceptionPending(cx)); throw_dom_exception(cx, global, self); assert!(JS_IsExceptionPending(cx)); diff --git a/components/script/dom/bindings/htmlconstructor.rs b/components/script/dom/bindings/htmlconstructor.rs index 1b89d3f7669..7cbac28398f 100644 --- a/components/script/dom/bindings/htmlconstructor.rs +++ b/components/script/dom/bindings/htmlconstructor.rs @@ -89,7 +89,9 @@ use std::ptr; // https://html.spec.whatwg.org/multipage/#htmlconstructor pub unsafe fn html_constructor<T>(window: &Window, call_args: &CallArgs) -> Fallible<DomRoot<T>> - where T: DerivedFrom<Element> { +where + T: DerivedFrom<Element>, +{ let document = window.Document(); // Step 1 @@ -101,7 +103,11 @@ pub unsafe fn html_constructor<T>(window: &Window, call_args: &CallArgs) -> Fall rooted!(in(window.get_cx()) let new_target = call_args.new_target().to_object()); let definition = match registry.lookup_definition_by_constructor(new_target.handle()) { Some(definition) => definition, - None => return Err(Error::Type("No custom element definition found for new.target".to_owned())), + None => { + return Err(Error::Type( + "No custom element definition found for new.target".to_owned(), + )) + }, }; rooted!(in(window.get_cx()) let callee = UnwrapObject(call_args.callee(), 1)); @@ -119,18 +125,25 @@ pub unsafe fn html_constructor<T>(window: &Window, call_args: &CallArgs) -> Fall // Since this element is autonomous, its active function object must be the HTMLElement // Retrieve the constructor object for HTMLElement - HTMLElementBinding::GetConstructorObject(window.get_cx(), global_object.handle(), constructor.handle_mut()); - + HTMLElementBinding::GetConstructorObject( + window.get_cx(), + global_object.handle(), + constructor.handle_mut(), + ); } else { // Step 5 - get_constructor_object_from_local_name(definition.local_name.clone(), - window.get_cx(), - global_object.handle(), - constructor.handle_mut()); + get_constructor_object_from_local_name( + definition.local_name.clone(), + window.get_cx(), + global_object.handle(), + constructor.handle_mut(), + ); } // Callee must be the same as the element interface's constructor object. if constructor.get() != callee.get() { - return Err(Error::Type("Custom element does not extend the proper interface".to_owned())); + return Err(Error::Type( + "Custom element does not extend the proper interface".to_owned(), + )); } } @@ -176,11 +189,12 @@ pub unsafe fn html_constructor<T>(window: &Window, call_args: &CallArgs) -> Fall /// Returns the constructor object for the element associated with the given local name. /// This list should only include elements marked with the [HTMLConstructor] extended attribute. -pub fn get_constructor_object_from_local_name(name: LocalName, - cx: *mut JSContext, - global: HandleObject, - rval: MutableHandleObject) - -> bool { +pub fn get_constructor_object_from_local_name( + name: LocalName, + cx: *mut JSContext, + global: HandleObject, + rval: MutableHandleObject, +) -> bool { macro_rules! get_constructor( ($binding:ident) => ({ unsafe { $binding::GetConstructorObject(cx, global, rval); } @@ -189,131 +203,131 @@ pub fn get_constructor_object_from_local_name(name: LocalName, ); match name { - local_name!("a") => get_constructor!(HTMLAnchorElementBinding), - local_name!("abbr") => get_constructor!(HTMLElementBinding), - local_name!("acronym") => get_constructor!(HTMLElementBinding), - local_name!("address") => get_constructor!(HTMLElementBinding), - local_name!("area") => get_constructor!(HTMLAreaElementBinding), - local_name!("article") => get_constructor!(HTMLElementBinding), - local_name!("aside") => get_constructor!(HTMLElementBinding), - local_name!("audio") => get_constructor!(HTMLAudioElementBinding), - local_name!("b") => get_constructor!(HTMLElementBinding), - local_name!("base") => get_constructor!(HTMLBaseElementBinding), - local_name!("bdi") => get_constructor!(HTMLElementBinding), - local_name!("bdo") => get_constructor!(HTMLElementBinding), - local_name!("big") => get_constructor!(HTMLElementBinding), + local_name!("a") => get_constructor!(HTMLAnchorElementBinding), + local_name!("abbr") => get_constructor!(HTMLElementBinding), + local_name!("acronym") => get_constructor!(HTMLElementBinding), + local_name!("address") => get_constructor!(HTMLElementBinding), + local_name!("area") => get_constructor!(HTMLAreaElementBinding), + local_name!("article") => get_constructor!(HTMLElementBinding), + local_name!("aside") => get_constructor!(HTMLElementBinding), + local_name!("audio") => get_constructor!(HTMLAudioElementBinding), + local_name!("b") => get_constructor!(HTMLElementBinding), + local_name!("base") => get_constructor!(HTMLBaseElementBinding), + local_name!("bdi") => get_constructor!(HTMLElementBinding), + local_name!("bdo") => get_constructor!(HTMLElementBinding), + local_name!("big") => get_constructor!(HTMLElementBinding), local_name!("blockquote") => get_constructor!(HTMLQuoteElementBinding), - local_name!("body") => get_constructor!(HTMLBodyElementBinding), - local_name!("br") => get_constructor!(HTMLBRElementBinding), - local_name!("button") => get_constructor!(HTMLButtonElementBinding), - local_name!("canvas") => get_constructor!(HTMLCanvasElementBinding), - local_name!("caption") => get_constructor!(HTMLTableCaptionElementBinding), - local_name!("center") => get_constructor!(HTMLElementBinding), - local_name!("cite") => get_constructor!(HTMLElementBinding), - local_name!("code") => get_constructor!(HTMLElementBinding), - local_name!("col") => get_constructor!(HTMLTableColElementBinding), - local_name!("colgroup") => get_constructor!(HTMLTableColElementBinding), - local_name!("data") => get_constructor!(HTMLDataElementBinding), - local_name!("datalist") => get_constructor!(HTMLDataListElementBinding), - local_name!("dd") => get_constructor!(HTMLElementBinding), - local_name!("del") => get_constructor!(HTMLModElementBinding), - local_name!("details") => get_constructor!(HTMLDetailsElementBinding), - local_name!("dfn") => get_constructor!(HTMLElementBinding), - local_name!("dialog") => get_constructor!(HTMLDialogElementBinding), - local_name!("dir") => get_constructor!(HTMLDirectoryElementBinding), - local_name!("div") => get_constructor!(HTMLDivElementBinding), - local_name!("dl") => get_constructor!(HTMLDListElementBinding), - local_name!("dt") => get_constructor!(HTMLElementBinding), - local_name!("em") => get_constructor!(HTMLElementBinding), - local_name!("embed") => get_constructor!(HTMLEmbedElementBinding), - local_name!("fieldset") => get_constructor!(HTMLFieldSetElementBinding), + local_name!("body") => get_constructor!(HTMLBodyElementBinding), + local_name!("br") => get_constructor!(HTMLBRElementBinding), + local_name!("button") => get_constructor!(HTMLButtonElementBinding), + local_name!("canvas") => get_constructor!(HTMLCanvasElementBinding), + local_name!("caption") => get_constructor!(HTMLTableCaptionElementBinding), + local_name!("center") => get_constructor!(HTMLElementBinding), + local_name!("cite") => get_constructor!(HTMLElementBinding), + local_name!("code") => get_constructor!(HTMLElementBinding), + local_name!("col") => get_constructor!(HTMLTableColElementBinding), + local_name!("colgroup") => get_constructor!(HTMLTableColElementBinding), + local_name!("data") => get_constructor!(HTMLDataElementBinding), + local_name!("datalist") => get_constructor!(HTMLDataListElementBinding), + local_name!("dd") => get_constructor!(HTMLElementBinding), + local_name!("del") => get_constructor!(HTMLModElementBinding), + local_name!("details") => get_constructor!(HTMLDetailsElementBinding), + local_name!("dfn") => get_constructor!(HTMLElementBinding), + local_name!("dialog") => get_constructor!(HTMLDialogElementBinding), + local_name!("dir") => get_constructor!(HTMLDirectoryElementBinding), + local_name!("div") => get_constructor!(HTMLDivElementBinding), + local_name!("dl") => get_constructor!(HTMLDListElementBinding), + local_name!("dt") => get_constructor!(HTMLElementBinding), + local_name!("em") => get_constructor!(HTMLElementBinding), + local_name!("embed") => get_constructor!(HTMLEmbedElementBinding), + local_name!("fieldset") => get_constructor!(HTMLFieldSetElementBinding), local_name!("figcaption") => get_constructor!(HTMLElementBinding), - local_name!("figure") => get_constructor!(HTMLElementBinding), - local_name!("font") => get_constructor!(HTMLFontElementBinding), - local_name!("footer") => get_constructor!(HTMLElementBinding), - local_name!("form") => get_constructor!(HTMLFormElementBinding), - local_name!("frame") => get_constructor!(HTMLFrameElementBinding), - local_name!("frameset") => get_constructor!(HTMLFrameSetElementBinding), - local_name!("h1") => get_constructor!(HTMLHeadingElementBinding), - local_name!("h2") => get_constructor!(HTMLHeadingElementBinding), - local_name!("h3") => get_constructor!(HTMLHeadingElementBinding), - local_name!("h4") => get_constructor!(HTMLHeadingElementBinding), - local_name!("h5") => get_constructor!(HTMLHeadingElementBinding), - local_name!("h6") => get_constructor!(HTMLHeadingElementBinding), - local_name!("head") => get_constructor!(HTMLHeadElementBinding), - local_name!("header") => get_constructor!(HTMLElementBinding), - local_name!("hgroup") => get_constructor!(HTMLElementBinding), - local_name!("hr") => get_constructor!(HTMLHRElementBinding), - local_name!("html") => get_constructor!(HTMLHtmlElementBinding), - local_name!("i") => get_constructor!(HTMLElementBinding), - local_name!("iframe") => get_constructor!(HTMLIFrameElementBinding), - local_name!("img") => get_constructor!(HTMLImageElementBinding), - local_name!("input") => get_constructor!(HTMLInputElementBinding), - local_name!("ins") => get_constructor!(HTMLModElementBinding), - local_name!("kbd") => get_constructor!(HTMLElementBinding), - local_name!("label") => get_constructor!(HTMLLabelElementBinding), - local_name!("legend") => get_constructor!(HTMLLegendElementBinding), - local_name!("li") => get_constructor!(HTMLLIElementBinding), - local_name!("link") => get_constructor!(HTMLLinkElementBinding), - local_name!("listing") => get_constructor!(HTMLPreElementBinding), - local_name!("main") => get_constructor!(HTMLElementBinding), - local_name!("map") => get_constructor!(HTMLMapElementBinding), - local_name!("mark") => get_constructor!(HTMLElementBinding), - local_name!("marquee") => get_constructor!(HTMLElementBinding), - local_name!("meta") => get_constructor!(HTMLMetaElementBinding), - local_name!("meter") => get_constructor!(HTMLMeterElementBinding), - local_name!("nav") => get_constructor!(HTMLElementBinding), - local_name!("nobr") => get_constructor!(HTMLElementBinding), - local_name!("noframes") => get_constructor!(HTMLElementBinding), - local_name!("noscript") => get_constructor!(HTMLElementBinding), - local_name!("object") => get_constructor!(HTMLObjectElementBinding), - local_name!("ol") => get_constructor!(HTMLOListElementBinding), - local_name!("optgroup") => get_constructor!(HTMLOptGroupElementBinding), - local_name!("option") => get_constructor!(HTMLOptionElementBinding), - local_name!("output") => get_constructor!(HTMLOutputElementBinding), - local_name!("p") => get_constructor!(HTMLParagraphElementBinding), - local_name!("param") => get_constructor!(HTMLParamElementBinding), - local_name!("plaintext") => get_constructor!(HTMLPreElementBinding), - local_name!("pre") => get_constructor!(HTMLPreElementBinding), - local_name!("progress") => get_constructor!(HTMLProgressElementBinding), - local_name!("q") => get_constructor!(HTMLQuoteElementBinding), - local_name!("rp") => get_constructor!(HTMLElementBinding), - local_name!("rt") => get_constructor!(HTMLElementBinding), - local_name!("ruby") => get_constructor!(HTMLElementBinding), - local_name!("s") => get_constructor!(HTMLElementBinding), - local_name!("samp") => get_constructor!(HTMLElementBinding), - local_name!("script") => get_constructor!(HTMLScriptElementBinding), - local_name!("section") => get_constructor!(HTMLElementBinding), - local_name!("select") => get_constructor!(HTMLSelectElementBinding), - local_name!("small") => get_constructor!(HTMLElementBinding), - local_name!("source") => get_constructor!(HTMLSourceElementBinding), - local_name!("span") => get_constructor!(HTMLSpanElementBinding), - local_name!("strike") => get_constructor!(HTMLElementBinding), - local_name!("strong") => get_constructor!(HTMLElementBinding), - local_name!("style") => get_constructor!(HTMLStyleElementBinding), - local_name!("sub") => get_constructor!(HTMLElementBinding), - local_name!("summary") => get_constructor!(HTMLElementBinding), - local_name!("sup") => get_constructor!(HTMLElementBinding), - local_name!("table") => get_constructor!(HTMLTableElementBinding), - local_name!("tbody") => get_constructor!(HTMLTableSectionElementBinding), - local_name!("td") => get_constructor!(HTMLTableDataCellElementBinding), - local_name!("template") => get_constructor!(HTMLTemplateElementBinding), - local_name!("textarea") => get_constructor!(HTMLTextAreaElementBinding), - local_name!("tfoot") => get_constructor!(HTMLTableSectionElementBinding), - local_name!("th") => get_constructor!(HTMLTableHeaderCellElementBinding), - local_name!("thead") => get_constructor!(HTMLTableSectionElementBinding), - local_name!("time") => get_constructor!(HTMLTimeElementBinding), - local_name!("title") => get_constructor!(HTMLTitleElementBinding), - local_name!("tr") => get_constructor!(HTMLTableRowElementBinding), - local_name!("tt") => get_constructor!(HTMLElementBinding), - local_name!("track") => get_constructor!(HTMLTrackElementBinding), - local_name!("u") => get_constructor!(HTMLElementBinding), - local_name!("ul") => get_constructor!(HTMLUListElementBinding), - local_name!("var") => get_constructor!(HTMLElementBinding), - local_name!("video") => get_constructor!(HTMLVideoElementBinding), - local_name!("wbr") => get_constructor!(HTMLElementBinding), - local_name!("xmp") => get_constructor!(HTMLPreElementBinding), - _ => false, + local_name!("figure") => get_constructor!(HTMLElementBinding), + local_name!("font") => get_constructor!(HTMLFontElementBinding), + local_name!("footer") => get_constructor!(HTMLElementBinding), + local_name!("form") => get_constructor!(HTMLFormElementBinding), + local_name!("frame") => get_constructor!(HTMLFrameElementBinding), + local_name!("frameset") => get_constructor!(HTMLFrameSetElementBinding), + local_name!("h1") => get_constructor!(HTMLHeadingElementBinding), + local_name!("h2") => get_constructor!(HTMLHeadingElementBinding), + local_name!("h3") => get_constructor!(HTMLHeadingElementBinding), + local_name!("h4") => get_constructor!(HTMLHeadingElementBinding), + local_name!("h5") => get_constructor!(HTMLHeadingElementBinding), + local_name!("h6") => get_constructor!(HTMLHeadingElementBinding), + local_name!("head") => get_constructor!(HTMLHeadElementBinding), + local_name!("header") => get_constructor!(HTMLElementBinding), + local_name!("hgroup") => get_constructor!(HTMLElementBinding), + local_name!("hr") => get_constructor!(HTMLHRElementBinding), + local_name!("html") => get_constructor!(HTMLHtmlElementBinding), + local_name!("i") => get_constructor!(HTMLElementBinding), + local_name!("iframe") => get_constructor!(HTMLIFrameElementBinding), + local_name!("img") => get_constructor!(HTMLImageElementBinding), + local_name!("input") => get_constructor!(HTMLInputElementBinding), + local_name!("ins") => get_constructor!(HTMLModElementBinding), + local_name!("kbd") => get_constructor!(HTMLElementBinding), + local_name!("label") => get_constructor!(HTMLLabelElementBinding), + local_name!("legend") => get_constructor!(HTMLLegendElementBinding), + local_name!("li") => get_constructor!(HTMLLIElementBinding), + local_name!("link") => get_constructor!(HTMLLinkElementBinding), + local_name!("listing") => get_constructor!(HTMLPreElementBinding), + local_name!("main") => get_constructor!(HTMLElementBinding), + local_name!("map") => get_constructor!(HTMLMapElementBinding), + local_name!("mark") => get_constructor!(HTMLElementBinding), + local_name!("marquee") => get_constructor!(HTMLElementBinding), + local_name!("meta") => get_constructor!(HTMLMetaElementBinding), + local_name!("meter") => get_constructor!(HTMLMeterElementBinding), + local_name!("nav") => get_constructor!(HTMLElementBinding), + local_name!("nobr") => get_constructor!(HTMLElementBinding), + local_name!("noframes") => get_constructor!(HTMLElementBinding), + local_name!("noscript") => get_constructor!(HTMLElementBinding), + local_name!("object") => get_constructor!(HTMLObjectElementBinding), + local_name!("ol") => get_constructor!(HTMLOListElementBinding), + local_name!("optgroup") => get_constructor!(HTMLOptGroupElementBinding), + local_name!("option") => get_constructor!(HTMLOptionElementBinding), + local_name!("output") => get_constructor!(HTMLOutputElementBinding), + local_name!("p") => get_constructor!(HTMLParagraphElementBinding), + local_name!("param") => get_constructor!(HTMLParamElementBinding), + local_name!("plaintext") => get_constructor!(HTMLPreElementBinding), + local_name!("pre") => get_constructor!(HTMLPreElementBinding), + local_name!("progress") => get_constructor!(HTMLProgressElementBinding), + local_name!("q") => get_constructor!(HTMLQuoteElementBinding), + local_name!("rp") => get_constructor!(HTMLElementBinding), + local_name!("rt") => get_constructor!(HTMLElementBinding), + local_name!("ruby") => get_constructor!(HTMLElementBinding), + local_name!("s") => get_constructor!(HTMLElementBinding), + local_name!("samp") => get_constructor!(HTMLElementBinding), + local_name!("script") => get_constructor!(HTMLScriptElementBinding), + local_name!("section") => get_constructor!(HTMLElementBinding), + local_name!("select") => get_constructor!(HTMLSelectElementBinding), + local_name!("small") => get_constructor!(HTMLElementBinding), + local_name!("source") => get_constructor!(HTMLSourceElementBinding), + local_name!("span") => get_constructor!(HTMLSpanElementBinding), + local_name!("strike") => get_constructor!(HTMLElementBinding), + local_name!("strong") => get_constructor!(HTMLElementBinding), + local_name!("style") => get_constructor!(HTMLStyleElementBinding), + local_name!("sub") => get_constructor!(HTMLElementBinding), + local_name!("summary") => get_constructor!(HTMLElementBinding), + local_name!("sup") => get_constructor!(HTMLElementBinding), + local_name!("table") => get_constructor!(HTMLTableElementBinding), + local_name!("tbody") => get_constructor!(HTMLTableSectionElementBinding), + local_name!("td") => get_constructor!(HTMLTableDataCellElementBinding), + local_name!("template") => get_constructor!(HTMLTemplateElementBinding), + local_name!("textarea") => get_constructor!(HTMLTextAreaElementBinding), + local_name!("tfoot") => get_constructor!(HTMLTableSectionElementBinding), + local_name!("th") => get_constructor!(HTMLTableHeaderCellElementBinding), + local_name!("thead") => get_constructor!(HTMLTableSectionElementBinding), + local_name!("time") => get_constructor!(HTMLTimeElementBinding), + local_name!("title") => get_constructor!(HTMLTitleElementBinding), + local_name!("tr") => get_constructor!(HTMLTableRowElementBinding), + local_name!("tt") => get_constructor!(HTMLElementBinding), + local_name!("track") => get_constructor!(HTMLTrackElementBinding), + local_name!("u") => get_constructor!(HTMLElementBinding), + local_name!("ul") => get_constructor!(HTMLUListElementBinding), + local_name!("var") => get_constructor!(HTMLElementBinding), + local_name!("video") => get_constructor!(HTMLVideoElementBinding), + local_name!("wbr") => get_constructor!(HTMLElementBinding), + local_name!("xmp") => get_constructor!(HTMLPreElementBinding), + _ => false, } } diff --git a/components/script/dom/bindings/inheritance.rs b/components/script/dom/bindings/inheritance.rs index c017a806b6e..eaf394e594d 100644 --- a/components/script/dom/bindings/inheritance.rs +++ b/components/script/dom/bindings/inheritance.rs @@ -16,7 +16,8 @@ use std::mem; pub trait Castable: IDLInterface + DomObject + Sized { /// Check whether a DOM object implements one of its deriving interfaces. fn is<T>(&self) -> bool - where T: DerivedFrom<Self> + where + T: DerivedFrom<Self>, { let class = unsafe { get_dom_class(self.reflector().get_jsobject().get()).unwrap() }; T::derives(class) @@ -24,15 +25,17 @@ pub trait Castable: IDLInterface + DomObject + Sized { /// Cast a DOM object upwards to one of the interfaces it derives from. fn upcast<T>(&self) -> &T - where T: Castable, - Self: DerivedFrom<T> + where + T: Castable, + Self: DerivedFrom<T>, { unsafe { mem::transmute(self) } } /// Cast a DOM object downwards to one of the interfaces it might implement. fn downcast<T>(&self) -> Option<&T> - where T: DerivedFrom<Self> + where + T: DerivedFrom<Self>, { if self.is::<T>() { Some(unsafe { mem::transmute(self) }) diff --git a/components/script/dom/bindings/interface.rs b/components/script/dom/bindings/interface.rs index 60fb712b831..210e9ae5576 100644 --- a/components/script/dom/bindings/interface.rs +++ b/components/script/dom/bindings/interface.rs @@ -52,11 +52,12 @@ unsafe impl Sync for NonCallbackInterfaceObjectClass {} impl NonCallbackInterfaceObjectClass { /// Create a new `NonCallbackInterfaceObjectClass` structure. - pub const fn new(constructor_behavior: &'static InterfaceConstructorBehavior, - string_rep: &'static [u8], - proto_id: PrototypeList::ID, - proto_depth: u16) - -> NonCallbackInterfaceObjectClass { + pub const fn new( + constructor_behavior: &'static InterfaceConstructorBehavior, + string_rep: &'static [u8], + proto_id: PrototypeList::ID, + proto_depth: u16, + ) -> NonCallbackInterfaceObjectClass { NonCallbackInterfaceObjectClass { class: Class { name: b"Function\0" as *const _ as *const libc::c_char, @@ -74,9 +75,7 @@ impl NonCallbackInterfaceObjectClass { /// cast own reference to `JSClass` reference pub fn as_jsclass(&self) -> &JSClass { - unsafe { - &*(self as *const _ as *const JSClass) - } + unsafe { &*(self as *const _ as *const JSClass) } } } @@ -124,27 +123,29 @@ impl InterfaceConstructorBehavior { } /// A trace hook. -pub type TraceHook = - unsafe extern "C" fn(trc: *mut JSTracer, obj: *mut JSObject); +pub type TraceHook = unsafe extern "C" fn(trc: *mut JSTracer, obj: *mut JSObject); /// Create a global object with the given class. pub unsafe fn create_global_object( - cx: *mut JSContext, - class: &'static JSClass, - private: *const libc::c_void, - trace: TraceHook, - mut rval: MutableHandleObject) { + cx: *mut JSContext, + class: &'static JSClass, + private: *const libc::c_void, + trace: TraceHook, + mut rval: MutableHandleObject, +) { assert!(rval.is_null()); let mut options = CompartmentOptions::default(); options.creationOptions_.traceGlobal_ = Some(trace); options.creationOptions_.sharedMemoryAndAtomics_ = true; - rval.set(JS_NewGlobalObject(cx, - class, - ptr::null_mut(), - OnNewGlobalHookOption::DontFireOnNewGlobalHook, - &options)); + rval.set(JS_NewGlobalObject( + cx, + class, + ptr::null_mut(), + OnNewGlobalHookOption::DontFireOnNewGlobalHook, + &options, + )); assert!(!rval.is_null()); // Initialize the reserved slots before doing anything that can GC, to @@ -162,11 +163,12 @@ pub unsafe fn create_global_object( /// Create and define the interface object of a callback interface. pub unsafe fn create_callback_interface_object( - cx: *mut JSContext, - global: HandleObject, - constants: &[Guard<&[ConstantSpec]>], - name: &[u8], - mut rval: MutableHandleObject) { + cx: *mut JSContext, + global: HandleObject, + constants: &[Guard<&[ConstantSpec]>], + name: &[u8], + mut rval: MutableHandleObject, +) { assert!(!constants.is_empty()); rval.set(JS_NewObject(cx, ptr::null())); assert!(!rval.is_null()); @@ -177,15 +179,24 @@ pub unsafe fn create_callback_interface_object( /// Create the interface prototype object of a non-callback interface. pub unsafe fn create_interface_prototype_object( - cx: *mut JSContext, - proto: HandleObject, - class: &'static JSClass, - regular_methods: &[Guard<&'static [JSFunctionSpec]>], - regular_properties: &[Guard<&'static [JSPropertySpec]>], - constants: &[Guard<&[ConstantSpec]>], - unscopable_names: &[&[u8]], - rval: MutableHandleObject) { - create_object(cx, proto, class, regular_methods, regular_properties, constants, rval); + cx: *mut JSContext, + proto: HandleObject, + class: &'static JSClass, + regular_methods: &[Guard<&'static [JSFunctionSpec]>], + regular_properties: &[Guard<&'static [JSPropertySpec]>], + constants: &[Guard<&[ConstantSpec]>], + unscopable_names: &[&[u8]], + rval: MutableHandleObject, +) { + create_object( + cx, + proto, + class, + regular_methods, + regular_properties, + constants, + rval, + ); if !unscopable_names.is_empty() { rooted!(in(cx) let mut unscopable_obj = ptr::null_mut::<JSObject>()); @@ -196,32 +207,43 @@ pub unsafe fn create_interface_prototype_object( rooted!(in(cx) let unscopable_id = RUST_SYMBOL_TO_JSID(unscopable_symbol)); assert!(JS_DefinePropertyById4( - cx, rval.handle(), unscopable_id.handle(), unscopable_obj.handle(), - JSPROP_READONLY as u32)) + cx, + rval.handle(), + unscopable_id.handle(), + unscopable_obj.handle(), + JSPROP_READONLY as u32 + )) } } /// Create and define the interface object of a non-callback interface. pub unsafe fn create_noncallback_interface_object( - cx: *mut JSContext, - global: HandleObject, - proto: HandleObject, - class: &'static NonCallbackInterfaceObjectClass, - static_methods: &[Guard<&'static [JSFunctionSpec]>], - static_properties: &[Guard<&'static [JSPropertySpec]>], - constants: &[Guard<&[ConstantSpec]>], - interface_prototype_object: HandleObject, - name: &[u8], - length: u32, - rval: MutableHandleObject) { - create_object(cx, - proto, - class.as_jsclass(), - static_methods, - static_properties, - constants, - rval); - assert!(JS_LinkConstructorAndPrototype(cx, rval.handle(), interface_prototype_object)); + cx: *mut JSContext, + global: HandleObject, + proto: HandleObject, + class: &'static NonCallbackInterfaceObjectClass, + static_methods: &[Guard<&'static [JSFunctionSpec]>], + static_properties: &[Guard<&'static [JSPropertySpec]>], + constants: &[Guard<&[ConstantSpec]>], + interface_prototype_object: HandleObject, + name: &[u8], + length: u32, + rval: MutableHandleObject, +) { + create_object( + cx, + proto, + class.as_jsclass(), + static_methods, + static_properties, + constants, + rval, + ); + assert!(JS_LinkConstructorAndPrototype( + cx, + rval.handle(), + interface_prototype_object + )); define_name(cx, rval.handle(), name); define_length(cx, rval.handle(), i32::try_from(length).expect("overflow")); define_on_global_object(cx, global, name, rval.handle()); @@ -229,29 +251,34 @@ pub unsafe fn create_noncallback_interface_object( /// Create and define the named constructors of a non-callback interface. pub unsafe fn create_named_constructors( - cx: *mut JSContext, - global: HandleObject, - named_constructors: &[(ConstructorClassHook, &[u8], u32)], - interface_prototype_object: HandleObject) { + cx: *mut JSContext, + global: HandleObject, + named_constructors: &[(ConstructorClassHook, &[u8], u32)], + interface_prototype_object: HandleObject, +) { rooted!(in(cx) let mut constructor = ptr::null_mut::<JSObject>()); for &(native, name, arity) in named_constructors { assert_eq!(*name.last().unwrap(), b'\0'); - let fun = JS_NewFunction(cx, - Some(native), - arity, - JSFUN_CONSTRUCTOR, - name.as_ptr() as *const libc::c_char); + let fun = JS_NewFunction( + cx, + Some(native), + arity, + JSFUN_CONSTRUCTOR, + name.as_ptr() as *const libc::c_char, + ); assert!(!fun.is_null()); constructor.set(JS_GetFunctionObject(fun)); assert!(!constructor.is_null()); - assert!(JS_DefineProperty2(cx, - constructor.handle(), - b"prototype\0".as_ptr() as *const libc::c_char, - interface_prototype_object, - (JSPROP_PERMANENT | JSPROP_READONLY) as u32)); + assert!(JS_DefineProperty2( + cx, + constructor.handle(), + b"prototype\0".as_ptr() as *const libc::c_char, + interface_prototype_object, + (JSPROP_PERMANENT | JSPROP_READONLY) as u32 + )); define_on_global_object(cx, global, name, constructor.handle()); } @@ -259,13 +286,14 @@ pub unsafe fn create_named_constructors( /// Create a new object with a unique type. pub unsafe fn create_object( - cx: *mut JSContext, - proto: HandleObject, - class: &'static JSClass, - methods: &[Guard<&'static [JSFunctionSpec]>], - properties: &[Guard<&'static [JSPropertySpec]>], - constants: &[Guard<&[ConstantSpec]>], - mut rval: MutableHandleObject) { + cx: *mut JSContext, + proto: HandleObject, + class: &'static JSClass, + methods: &[Guard<&'static [JSFunctionSpec]>], + properties: &[Guard<&'static [JSPropertySpec]>], + constants: &[Guard<&[ConstantSpec]>], + mut rval: MutableHandleObject, +) { rval.set(JS_NewObjectWithUniqueType(cx, class, proto)); assert!(!rval.is_null()); define_guarded_methods(cx, rval.handle(), methods); @@ -275,9 +303,10 @@ pub unsafe fn create_object( /// Conditionally define constants on an object. pub unsafe fn define_guarded_constants( - cx: *mut JSContext, - obj: HandleObject, - constants: &[Guard<&[ConstantSpec]>]) { + cx: *mut JSContext, + obj: HandleObject, + constants: &[Guard<&[ConstantSpec]>], +) { for guard in constants { if let Some(specs) = guard.expose(cx, obj) { define_constants(cx, obj, specs); @@ -287,9 +316,10 @@ pub unsafe fn define_guarded_constants( /// Conditionally define methods on an object. pub unsafe fn define_guarded_methods( - cx: *mut JSContext, - obj: HandleObject, - methods: &[Guard<&'static [JSFunctionSpec]>]) { + cx: *mut JSContext, + obj: HandleObject, + methods: &[Guard<&'static [JSFunctionSpec]>], +) { for guard in methods { if let Some(specs) = guard.expose(cx, obj) { define_methods(cx, obj, specs).unwrap(); @@ -299,9 +329,10 @@ pub unsafe fn define_guarded_methods( /// Conditionally define properties on an object. pub unsafe fn define_guarded_properties( - cx: *mut JSContext, - obj: HandleObject, - properties: &[Guard<&'static [JSPropertySpec]>]) { + cx: *mut JSContext, + obj: HandleObject, + properties: &[Guard<&'static [JSPropertySpec]>], +) { for guard in properties { if let Some(specs) = guard.expose(cx, obj) { define_properties(cx, obj, specs).unwrap(); @@ -320,16 +351,19 @@ pub unsafe fn is_exposed_in(object: HandleObject, globals: Globals) -> bool { /// Define a property with a given name on the global object. Should be called /// through the resolve hook. pub unsafe fn define_on_global_object( - cx: *mut JSContext, - global: HandleObject, - name: &[u8], - obj: HandleObject) { + cx: *mut JSContext, + global: HandleObject, + name: &[u8], + obj: HandleObject, +) { assert_eq!(*name.last().unwrap(), b'\0'); - assert!(JS_DefineProperty2(cx, - global, - name.as_ptr() as *const libc::c_char, - obj, - JSPROP_RESOLVING)); + assert!(JS_DefineProperty2( + cx, + global, + name.as_ptr() as *const libc::c_char, + obj, + JSPROP_RESOLVING + )); } const OBJECT_OPS: ObjectOps = ObjectOps { @@ -344,10 +378,11 @@ const OBJECT_OPS: ObjectOps = ObjectOps { funToString: Some(fun_to_string_hook), }; -unsafe extern "C" fn fun_to_string_hook(cx: *mut JSContext, - obj: RawHandleObject, - _is_to_source: bool) - -> *mut JSString { +unsafe extern "C" fn fun_to_string_hook( + cx: *mut JSContext, + obj: RawHandleObject, + _is_to_source: bool, +) -> *mut JSString { let js_class = get_object_class(obj.get()); assert!(!js_class.is_null()); let repr = (*(js_class as *const NonCallbackInterfaceObjectClass)).representation; @@ -358,17 +393,19 @@ unsafe extern "C" fn fun_to_string_hook(cx: *mut JSContext, } /// Hook for instanceof on interface objects. -unsafe extern "C" fn has_instance_hook(cx: *mut JSContext, - obj: RawHandleObject, - value: RawMutableHandleValue, - rval: *mut bool) -> bool { +unsafe extern "C" fn has_instance_hook( + cx: *mut JSContext, + obj: RawHandleObject, + value: RawMutableHandleValue, + rval: *mut bool, +) -> bool { let obj_raw = HandleObject::from_raw(obj); let val_raw = HandleValue::from_raw(value.handle()); match has_instance(cx, obj_raw, val_raw) { Ok(result) => { *rval = result; true - } + }, Err(()) => false, } } @@ -376,10 +413,10 @@ unsafe extern "C" fn has_instance_hook(cx: *mut JSContext, /// Return whether a value is an instance of a given prototype. /// <http://heycam.github.io/webidl/#es-interface-hasinstance> unsafe fn has_instance( - cx: *mut JSContext, - interface_object: HandleObject, - value: HandleValue) - -> Result<bool, ()> { + cx: *mut JSContext, + interface_object: HandleObject, + value: HandleValue, +) -> Result<bool, ()> { if !value.is_object() { // Step 1. return Ok(false); @@ -391,8 +428,10 @@ unsafe fn has_instance( let js_class = get_object_class(interface_object.get()); let object_class = &*(js_class as *const NonCallbackInterfaceObjectClass); - if let Ok(dom_class) = get_dom_class(UncheckedUnwrapObject(value.get(), - /* stopAtWindowProxy = */ 0)) { + if let Ok(dom_class) = get_dom_class(UncheckedUnwrapObject( + value.get(), + /* stopAtWindowProxy = */ 0, + )) { if dom_class.interface_chain[object_class.proto_depth as usize] == object_class.proto_id { // Step 4. return Ok(true); @@ -422,9 +461,10 @@ unsafe fn has_instance( } unsafe fn create_unscopable_object( - cx: *mut JSContext, - names: &[&[u8]], - mut rval: MutableHandleObject) { + cx: *mut JSContext, + names: &[&[u8]], + mut rval: MutableHandleObject, +) { assert!(!names.is_empty()); assert!(rval.is_null()); rval.set(JS_NewPlainObject(cx)); @@ -445,35 +485,39 @@ unsafe fn define_name(cx: *mut JSContext, obj: HandleObject, name: &[u8]) { assert_eq!(*name.last().unwrap(), b'\0'); rooted!(in(cx) let name = JS_AtomizeAndPinString(cx, name.as_ptr() as *const libc::c_char)); assert!(!name.is_null()); - assert!(JS_DefineProperty3(cx, - obj, - b"name\0".as_ptr() as *const libc::c_char, - name.handle().into(), - JSPROP_READONLY as u32)); + assert!(JS_DefineProperty3( + cx, + obj, + b"name\0".as_ptr() as *const libc::c_char, + name.handle().into(), + JSPROP_READONLY as u32 + )); } unsafe fn define_length(cx: *mut JSContext, obj: HandleObject, length: i32) { - assert!(JS_DefineProperty4(cx, - obj, - b"length\0".as_ptr() as *const libc::c_char, - length, - JSPROP_READONLY as u32)); + assert!(JS_DefineProperty4( + cx, + obj, + b"length\0".as_ptr() as *const libc::c_char, + length, + JSPROP_READONLY as u32 + )); } unsafe extern "C" fn invalid_constructor( - cx: *mut JSContext, - _argc: libc::c_uint, - _vp: *mut JSVal) - -> bool { + cx: *mut JSContext, + _argc: libc::c_uint, + _vp: *mut JSVal, +) -> bool { throw_type_error(cx, "Illegal constructor."); false } unsafe extern "C" fn non_new_constructor( - cx: *mut JSContext, - _argc: libc::c_uint, - _vp: *mut JSVal) - -> bool { + cx: *mut JSContext, + _argc: libc::c_uint, + _vp: *mut JSVal, +) -> bool { throw_type_error(cx, "This constructor needs to be called with `new`."); false } diff --git a/components/script/dom/bindings/iterable.rs b/components/script/dom/bindings/iterable.rs index 87ee05541fa..488714d3d0b 100644 --- a/components/script/dom/bindings/iterable.rs +++ b/components/script/dom/bindings/iterable.rs @@ -59,10 +59,11 @@ pub struct IterableIterator<T: DomObject + JSTraceable + Iterable> { impl<T: DomObject + JSTraceable + Iterable> IterableIterator<T> { /// Create a new iterator instance for the provided iterable DOM interface. - pub fn new(iterable: &T, - type_: IteratorType, - wrap: unsafe fn(*mut JSContext, &GlobalScope, Box<IterableIterator<T>>) - -> DomRoot<Self>) -> DomRoot<Self> { + pub fn new( + iterable: &T, + type_: IteratorType, + wrap: unsafe fn(*mut JSContext, &GlobalScope, Box<IterableIterator<T>>) -> DomRoot<Self>, + ) -> DomRoot<Self> { let iterator = Box::new(IterableIterator { reflector: Reflector::new(), type_: type_, @@ -84,37 +85,45 @@ impl<T: DomObject + JSTraceable + Iterable> IterableIterator<T> { match self.type_ { IteratorType::Keys => { unsafe { - self.iterable.get_key_at_index(index).to_jsval(cx, value.handle_mut()); + self.iterable + .get_key_at_index(index) + .to_jsval(cx, value.handle_mut()); } dict_return(cx, rval.handle_mut(), false, value.handle()) - } + }, IteratorType::Values => { unsafe { - self.iterable.get_value_at_index(index).to_jsval(cx, value.handle_mut()); + self.iterable + .get_value_at_index(index) + .to_jsval(cx, value.handle_mut()); } dict_return(cx, rval.handle_mut(), false, value.handle()) - } + }, IteratorType::Entries => { rooted!(in(cx) let mut key = UndefinedValue()); unsafe { - self.iterable.get_key_at_index(index).to_jsval(cx, key.handle_mut()); - self.iterable.get_value_at_index(index).to_jsval(cx, value.handle_mut()); + self.iterable + .get_key_at_index(index) + .to_jsval(cx, key.handle_mut()); + self.iterable + .get_value_at_index(index) + .to_jsval(cx, value.handle_mut()); } key_and_value_return(cx, rval.handle_mut(), key.handle(), value.handle()) - } + }, } }; self.index.set(index + 1); - result.map(|_| { - NonNull::new(rval.get()).expect("got a null pointer") - }) + result.map(|_| NonNull::new(rval.get()).expect("got a null pointer")) } } -fn dict_return(cx: *mut JSContext, - mut result: MutableHandleObject, - done: bool, - value: HandleValue) -> Fallible<()> { +fn dict_return( + cx: *mut JSContext, + mut result: MutableHandleObject, + done: bool, + value: HandleValue, +) -> Fallible<()> { let mut dict = IterableKeyOrValueResult::empty(); dict.done = done; dict.value.set(value.get()); @@ -126,16 +135,20 @@ fn dict_return(cx: *mut JSContext, Ok(()) } -fn key_and_value_return(cx: *mut JSContext, - mut result: MutableHandleObject, - key: HandleValue, - value: HandleValue) -> Fallible<()> { +fn key_and_value_return( + cx: *mut JSContext, + mut result: MutableHandleObject, + key: HandleValue, + value: HandleValue, +) -> Fallible<()> { let mut dict = IterableKeyAndValueResult::empty(); dict.done = false; - dict.value = Some(vec![key, value] - .into_iter() - .map(|handle| RootedTraceableBox::from_box(Heap::boxed(handle.get()))) - .collect()); + dict.value = Some( + vec![key, value] + .into_iter() + .map(|handle| RootedTraceableBox::from_box(Heap::boxed(handle.get()))) + .collect(), + ); rooted!(in(cx) let mut dict_value = UndefinedValue()); unsafe { dict.to_jsval(cx, dict_value.handle_mut()); diff --git a/components/script/dom/bindings/mozmap.rs b/components/script/dom/bindings/mozmap.rs index 2dfacbb2996..68ea9fa382d 100644 --- a/components/script/dom/bindings/mozmap.rs +++ b/components/script/dom/bindings/mozmap.rs @@ -49,24 +49,37 @@ impl<T> Deref for MozMap<T> { } impl<T, C> FromJSValConvertible for MozMap<T> - where T: FromJSValConvertible<Config=C>, - C: Clone, +where + T: FromJSValConvertible<Config = C>, + C: Clone, { type Config = C; - unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, config: C) - -> Result<ConversionResult<Self>, ()> { + unsafe fn from_jsval( + cx: *mut JSContext, + value: HandleValue, + config: C, + ) -> Result<ConversionResult<Self>, ()> { if !value.is_object() { - return Ok(ConversionResult::Failure("MozMap value was not an object".into())); + return Ok(ConversionResult::Failure( + "MozMap value was not an object".into(), + )); } rooted!(in(cx) let object = value.to_object()); let ids = IdVector::new(cx); - if !GetPropertyKeys(cx, object.handle(), JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, ids.get()) { + if !GetPropertyKeys( + cx, + object.handle(), + JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, + ids.get(), + ) { // TODO: can GetPropertyKeys fail? // (it does so if the object has duplicate keys) // https://github.com/servo/servo/issues/21462 report_pending_exception(cx, false); - return Ok(ConversionResult::Failure("Getting MozMap value property keys failed".into())); + return Ok(ConversionResult::Failure( + "Getting MozMap value property keys failed".into(), + )); } let mut map = HashMap::new(); @@ -90,9 +103,7 @@ impl<T, C> FromJSValConvertible for MozMap<T> } } - Ok(ConversionResult::Success(MozMap { - map: map, - })) + Ok(ConversionResult::Success(MozMap { map: map })) } } @@ -107,12 +118,14 @@ impl<T: ToJSValConvertible> ToJSValConvertible for MozMap<T> { let key = key.encode_utf16().collect::<Vec<_>>(); value.to_jsval(cx, js_value.handle_mut()); - assert!(JS_DefineUCProperty2(cx, - js_object.handle(), - key.as_ptr(), - key.len(), - js_value.handle(), - JSPROP_ENUMERATE as u32)); + assert!(JS_DefineUCProperty2( + cx, + js_object.handle(), + key.as_ptr(), + key.len(), + js_value.handle(), + JSPROP_ENUMERATE as u32 + )); } rval.set(ObjectValue(js_object.handle().get())); diff --git a/components/script/dom/bindings/namespace.rs b/components/script/dom/bindings/namespace.rs index 69b82f0d0ba..64b67b33e1e 100644 --- a/components/script/dom/bindings/namespace.rs +++ b/components/script/dom/bindings/namespace.rs @@ -30,13 +30,14 @@ impl NamespaceObjectClass { /// Create a new namespace object. pub unsafe fn create_namespace_object( - cx: *mut JSContext, - global: HandleObject, - proto: HandleObject, - class: &'static NamespaceObjectClass, - methods: &[Guard<&'static [JSFunctionSpec]>], - name: &[u8], - rval: MutableHandleObject) { + cx: *mut JSContext, + global: HandleObject, + proto: HandleObject, + class: &'static NamespaceObjectClass, + methods: &[Guard<&'static [JSFunctionSpec]>], + name: &[u8], + rval: MutableHandleObject, +) { create_object(cx, proto, &class.0, methods, &[], &[], rval); define_on_global_object(cx, global, name, rval.handle()); } diff --git a/components/script/dom/bindings/num.rs b/components/script/dom/bindings/num.rs index 79480574f4d..da880f559ee 100644 --- a/components/script/dom/bindings/num.rs +++ b/components/script/dom/bindings/num.rs @@ -26,8 +26,10 @@ impl<T: Float> Finite<T> { /// Create a new `Finite<T: Float>`. #[inline] pub fn wrap(value: T) -> Finite<T> { - assert!(value.is_finite(), - "Finite<T> doesn't encapsulate unrestricted value."); + assert!( + value.is_finite(), + "Finite<T> doesn't encapsulate unrestricted value." + ); Finite(value) } } diff --git a/components/script/dom/bindings/proxyhandler.rs b/components/script/dom/bindings/proxyhandler.rs index 2a512b02df3..86b7d81667c 100644 --- a/components/script/dom/bindings/proxyhandler.rs +++ b/components/script/dom/bindings/proxyhandler.rs @@ -30,12 +30,12 @@ use js::rust::wrappers::JS_AlreadyHasOwnPropertyById; use js::rust::wrappers::JS_NewObjectWithGivenProto; use std::ptr; - /// Determine if this id shadows any existing properties for this proxy. -pub unsafe extern "C" fn shadow_check_callback(cx: *mut JSContext, - object: RawHandleObject, - id: RawHandleId) - -> DOMProxyShadowsResult { +pub unsafe extern "C" fn shadow_check_callback( + cx: *mut JSContext, + object: RawHandleObject, + id: RawHandleId, +) -> DOMProxyShadowsResult { // TODO: support OverrideBuiltins when #12978 is fixed. rooted!(in(cx) let mut expando = ptr::null_mut::<JSObject>()); @@ -59,19 +59,19 @@ pub unsafe extern "C" fn shadow_check_callback(cx: *mut JSContext, /// Initialize the infrastructure for DOM proxy objects. pub unsafe fn init() { - SetDOMProxyInformation(GetProxyHandlerFamily(), - Some(shadow_check_callback)); + SetDOMProxyInformation(GetProxyHandlerFamily(), Some(shadow_check_callback)); } /// Invoke the [[GetOwnProperty]] trap (`getOwnPropertyDescriptor`) on `proxy`, /// with argument `id` and return the result, if it is not `undefined`. /// Otherwise, walk along the prototype chain to find a property with that /// name. -pub unsafe extern "C" fn get_property_descriptor(cx: *mut JSContext, - proxy: RawHandleObject, - id: RawHandleId, - desc: RawMutableHandle<PropertyDescriptor>) - -> bool { +pub unsafe extern "C" fn get_property_descriptor( + cx: *mut JSContext, + proxy: RawHandleObject, + id: RawHandleId, + desc: RawMutableHandle<PropertyDescriptor>, +) -> bool { let handler = GetProxyHandler(proxy.get()); if !InvokeGetOwnPropertyDescriptor(handler, cx, proxy, id, desc) { return false; @@ -91,23 +91,25 @@ pub unsafe extern "C" fn get_property_descriptor(cx: *mut JSContext, } /// Defines an expando on the given `proxy`. -pub unsafe extern "C" fn define_property(cx: *mut JSContext, - proxy: RawHandleObject, - id: RawHandleId, - desc: RawHandle<PropertyDescriptor>, - result: *mut ObjectOpResult) - -> bool { +pub unsafe extern "C" fn define_property( + cx: *mut JSContext, + proxy: RawHandleObject, + id: RawHandleId, + desc: RawHandle<PropertyDescriptor>, + result: *mut ObjectOpResult, +) -> bool { rooted!(in(cx) let mut expando = ptr::null_mut::<JSObject>()); ensure_expando_object(cx, proxy, expando.handle_mut()); JS_DefinePropertyById(cx, expando.handle().into(), id, desc, result) } /// Deletes an expando off the given `proxy`. -pub unsafe extern "C" fn delete(cx: *mut JSContext, - proxy: RawHandleObject, - id: RawHandleId, - bp: *mut ObjectOpResult) - -> bool { +pub unsafe extern "C" fn delete( + cx: *mut JSContext, + proxy: RawHandleObject, + id: RawHandleId, + bp: *mut ObjectOpResult, +) -> bool { rooted!(in(cx) let mut expando = ptr::null_mut::<JSObject>()); get_expando_object(proxy, expando.handle_mut()); if expando.is_null() { @@ -119,19 +121,21 @@ pub unsafe extern "C" fn delete(cx: *mut JSContext, } /// Controls whether the Extensible bit can be changed -pub unsafe extern "C" fn prevent_extensions(_cx: *mut JSContext, - _proxy: RawHandleObject, - result: *mut ObjectOpResult) - -> bool { +pub unsafe extern "C" fn prevent_extensions( + _cx: *mut JSContext, + _proxy: RawHandleObject, + result: *mut ObjectOpResult, +) -> bool { (*result).code_ = JSErrNum::JSMSG_CANT_PREVENT_EXTENSIONS as ::libc::uintptr_t; true } /// Reports whether the object is Extensible -pub unsafe extern "C" fn is_extensible(_cx: *mut JSContext, - _proxy: RawHandleObject, - succeeded: *mut bool) - -> bool { +pub unsafe extern "C" fn is_extensible( + _cx: *mut JSContext, + _proxy: RawHandleObject, + succeeded: *mut bool, +) -> bool { *succeeded = true; true } @@ -145,11 +149,12 @@ pub unsafe extern "C" fn is_extensible(_cx: *mut JSContext, /// This implementation always handles the case of the ordinary /// `[[GetPrototypeOf]]` behavior. An alternative implementation will be /// necessary for the Location object. -pub unsafe extern "C" fn get_prototype_if_ordinary(_: *mut JSContext, - proxy: RawHandleObject, - is_ordinary: *mut bool, - proto: RawMutableHandleObject) - -> bool { +pub unsafe extern "C" fn get_prototype_if_ordinary( + _: *mut JSContext, + proxy: RawHandleObject, + is_ordinary: *mut bool, + proto: RawMutableHandleObject, +) -> bool { *is_ordinary = true; proto.set(GetStaticPrototype(proxy.get())); true @@ -169,11 +174,19 @@ pub unsafe fn get_expando_object(obj: RawHandleObject, mut expando: MutableHandl /// Get the expando object, or create it if it doesn't exist yet. /// Fails on JSAPI failure. -pub unsafe fn ensure_expando_object(cx: *mut JSContext, obj: RawHandleObject, mut expando: MutableHandleObject) { +pub unsafe fn ensure_expando_object( + cx: *mut JSContext, + obj: RawHandleObject, + mut expando: MutableHandleObject, +) { assert!(is_dom_proxy(obj.get())); get_expando_object(obj, expando); if expando.is_null() { - expando.set(JS_NewObjectWithGivenProto(cx, ptr::null_mut(), HandleObject::null())); + expando.set(JS_NewObjectWithGivenProto( + cx, + ptr::null_mut(), + HandleObject::null(), + )); assert!(!expando.is_null()); SetProxyPrivate(obj.get(), &ObjectValue(expando.get())); @@ -182,9 +195,11 @@ pub unsafe fn ensure_expando_object(cx: *mut JSContext, obj: RawHandleObject, mu /// Set the property descriptor's object to `obj` and set it to enumerable, /// and writable if `readonly` is true. -pub fn fill_property_descriptor(mut desc: MutableHandle<PropertyDescriptor>, - obj: *mut JSObject, - attrs: u32) { +pub fn fill_property_descriptor( + mut desc: MutableHandle<PropertyDescriptor>, + obj: *mut JSObject, + attrs: u32, +) { desc.obj = obj; desc.attrs = attrs; desc.getter = None; diff --git a/components/script/dom/bindings/refcounted.rs b/components/script/dom/bindings/refcounted.rs index 2c5a179ca2b..11a422a2f3f 100644 --- a/components/script/dom/bindings/refcounted.rs +++ b/components/script/dom/bindings/refcounted.rs @@ -39,9 +39,9 @@ use std::rc::Rc; use std::sync::{Arc, Weak}; use task::TaskOnce; - -#[allow(missing_docs)] // FIXME -mod dummy { // Attributes don’t apply through the macro. +#[allow(missing_docs)] // FIXME +mod dummy { + // Attributes don’t apply through the macro. use std::cell::RefCell; use std::rc::Rc; use super::LiveDOMReferences; @@ -50,7 +50,6 @@ mod dummy { // Attributes don’t apply through the macro. } pub use self::dummy::LIVE_REFERENCES; - /// A pointer to a Rust DOM object that needs to be destroyed. pub struct TrustedReference(*const libc::c_void); unsafe impl Send for TrustedReference {} @@ -98,19 +97,28 @@ impl TrustedPromise { LIVE_REFERENCES.with(|ref r| { let r = r.borrow(); let live_references = r.as_ref().unwrap(); - assert_eq!(self.owner_thread, (&*live_references) as *const _ as *const libc::c_void); + assert_eq!( + self.owner_thread, + (&*live_references) as *const _ as *const libc::c_void + ); // Borrow-check error requires the redundant `let promise = ...; promise` here. - let promise = match live_references.promise_table.borrow_mut().entry(self.dom_object) { + let promise = match live_references + .promise_table + .borrow_mut() + .entry(self.dom_object) + { Occupied(mut entry) => { let promise = { let promises = entry.get_mut(); - promises.pop().expect("rooted promise list unexpectedly empty") + promises + .pop() + .expect("rooted promise list unexpectedly empty") }; if entry.get().is_empty() { entry.remove(); } promise - } + }, Vacant(_) => unreachable!(), }; promise @@ -182,9 +190,7 @@ impl<T: DomObject> Trusted<T> { let live_references = r.as_ref().unwrap(); self.owner_thread == (&*live_references) as *const _ as *const libc::c_void })); - unsafe { - DomRoot::from_ref(&*(self.refcount.0 as *const T)) - } + unsafe { DomRoot::from_ref(&*(self.refcount.0 as *const T)) } } } @@ -246,15 +252,15 @@ impl LiveDOMReferences { let refcount = Arc::new(TrustedReference::new(ptr)); entry.insert(Arc::downgrade(&refcount)); refcount - } + }, } } } /// Remove null entries from the live references table -fn remove_nulls<K: Eq + Hash + Clone, V> (table: &mut HashMap<K, Weak<V>>) { - let to_remove: Vec<K> = - table.iter() +fn remove_nulls<K: Eq + Hash + Clone, V>(table: &mut HashMap<K, Weak<V>>) { + let to_remove: Vec<K> = table + .iter() .filter(|&(_, value)| Weak::upgrade(value).is_none()) .map(|(key, _)| key.clone()) .collect(); diff --git a/components/script/dom/bindings/reflector.rs b/components/script/dom/bindings/reflector.rs index 416c3c3f552..2bf1983d40e 100644 --- a/components/script/dom/bindings/reflector.rs +++ b/components/script/dom/bindings/reflector.rs @@ -14,16 +14,16 @@ use std::default::Default; /// Create the reflector for a new DOM object and yield ownership to the /// reflector. pub fn reflect_dom_object<T, U>( - obj: Box<T>, - global: &U, - wrap_fn: unsafe fn(*mut JSContext, &GlobalScope, Box<T>) -> DomRoot<T>) - -> DomRoot<T> - where T: DomObject, U: DerivedFrom<GlobalScope> + obj: Box<T>, + global: &U, + wrap_fn: unsafe fn(*mut JSContext, &GlobalScope, Box<T>) -> DomRoot<T>, +) -> DomRoot<T> +where + T: DomObject, + U: DerivedFrom<GlobalScope>, { let global_scope = global.upcast(); - unsafe { - wrap_fn(global_scope.get_cx(), global_scope, obj) - } + unsafe { wrap_fn(global_scope.get_cx(), global_scope, obj) } } /// A struct to store a reference to the reflector of a DOM object. @@ -79,7 +79,10 @@ pub trait DomObject: 'static { fn reflector(&self) -> &Reflector; /// Returns the global scope of the realm that the DomObject was created in. - fn global(&self) -> DomRoot<GlobalScope> where Self: Sized { + fn global(&self) -> DomRoot<GlobalScope> + where + Self: Sized, + { GlobalScope::from_reflector(self) } } diff --git a/components/script/dom/bindings/root.rs b/components/script/dom/bindings/root.rs index f8336e6a85d..d974e75737c 100644 --- a/components/script/dom/bindings/root.rs +++ b/components/script/dom/bindings/root.rs @@ -96,9 +96,7 @@ where trace_reflector(tracer, "on stack", &self.0); } } - unsafe { - &*(self.reflector() as *const Reflector as *const ReflectorStackRoot) - } + unsafe { &*(self.reflector() as *const Reflector as *const ReflectorStackRoot) } } } @@ -131,15 +129,17 @@ pub type DomRoot<T> = Root<Dom<T>>; impl<T: Castable> DomRoot<T> { /// Cast a DOM object root upwards to one of the interfaces it derives from. pub fn upcast<U>(root: DomRoot<T>) -> DomRoot<U> - where U: Castable, - T: DerivedFrom<U> + where + U: Castable, + T: DerivedFrom<U>, { unsafe { mem::transmute(root) } } /// Cast a DOM object root downwards to one of the interfaces it might implement. pub fn downcast<U>(root: DomRoot<T>) -> Option<DomRoot<U>> - where U: DerivedFrom<T> + where + U: DerivedFrom<T>, { if root.is::<U>() { Some(unsafe { mem::transmute(root) }) @@ -207,9 +207,7 @@ pub struct ThreadLocalStackRoots<'a>(PhantomData<&'a u32>); impl<'a> ThreadLocalStackRoots<'a> { pub fn new(roots: &'a RootCollection) -> Self { - STACK_ROOTS.with(|ref r| { - r.set(Some(roots)) - }); + STACK_ROOTS.with(|ref r| r.set(Some(roots))); ThreadLocalStackRoots(PhantomData) } } @@ -363,9 +361,7 @@ unsafe impl<T: DomObject> JSTraceable for Dom<T> { #[cfg(not(all(feature = "unstable", debug_assertions)))] let trace_info = "for DOM object on heap"; - trace_reflector(trc, - trace_info, - (*self.ptr.as_ptr()).reflector()); + trace_reflector(trc, trace_info, (*self.ptr.as_ptr()).reflector()); } } @@ -379,8 +375,9 @@ pub struct LayoutDom<T> { impl<T: Castable> LayoutDom<T> { /// Cast a DOM object root upwards to one of the interfaces it derives from. pub fn upcast<U>(&self) -> LayoutDom<U> - where U: Castable, - T: DerivedFrom<U> + where + U: Castable, + T: DerivedFrom<U>, { debug_assert!(thread_state::get().is_layout()); let ptr: *mut T = self.ptr.as_ptr(); @@ -391,7 +388,8 @@ impl<T: Castable> LayoutDom<T> { /// Cast a DOM object downwards to one of the interfaces it might implement. pub fn downcast<U>(&self) -> Option<LayoutDom<U>> - where U: DerivedFrom<T> + where + U: DerivedFrom<T>, { debug_assert!(thread_state::get().is_layout()); unsafe { @@ -429,7 +427,6 @@ impl<'a, T: DomObject> PartialEq<&'a T> for Dom<T> { } } - impl<T> Eq for Dom<T> {} impl<T> PartialEq for LayoutDom<T> { @@ -452,7 +449,7 @@ impl<T> Hash for LayoutDom<T> { } } -impl <T> Clone for Dom<T> { +impl<T> Clone for Dom<T> { #[inline] #[allow(unrooted_must_root)] fn clone(&self) -> Dom<T> { @@ -463,7 +460,7 @@ impl <T> Clone for Dom<T> { } } -impl <T> Clone for LayoutDom<T> { +impl<T> Clone for LayoutDom<T> { #[inline] fn clone(&self) -> LayoutDom<T> { debug_assert!(thread_state::get().is_layout()); @@ -516,9 +513,7 @@ impl<T: DomObject> MutDom<T> { /// Get the value in this `MutDom`. pub fn get(&self) -> DomRoot<T> { debug_assert!(thread_state::get().is_script()); - unsafe { - DomRoot::from_ref(&*ptr::read(self.val.get())) - } + unsafe { DomRoot::from_ref(&*ptr::read(self.val.get())) } } } @@ -530,18 +525,14 @@ impl<T: DomObject> MallocSizeOf for MutDom<T> { } impl<T: DomObject> PartialEq for MutDom<T> { - fn eq(&self, other: &Self) -> bool { - unsafe { - *self.val.get() == *other.val.get() - } + fn eq(&self, other: &Self) -> bool { + unsafe { *self.val.get() == *other.val.get() } } } impl<T: DomObject + PartialEq> PartialEq<T> for MutDom<T> { fn eq(&self, other: &T) -> bool { - unsafe { - **self.val.get() == *other - } + unsafe { **self.val.get() == *other } } } @@ -569,7 +560,8 @@ impl<T: DomObject> MutNullableDom<T> { /// Retrieve a copy of the current inner value. If it is `None`, it is /// initialized with the result of `cb` first. pub fn or_init<F>(&self, cb: F) -> DomRoot<T> - where F: FnOnce() -> DomRoot<T> + where + F: FnOnce() -> DomRoot<T>, { debug_assert!(thread_state::get().is_script()); match self.get() { @@ -594,9 +586,7 @@ impl<T: DomObject> MutNullableDom<T> { #[allow(unrooted_must_root)] pub fn get(&self) -> Option<DomRoot<T>> { debug_assert!(thread_state::get().is_script()); - unsafe { - ptr::read(self.ptr.get()).map(|o| DomRoot::from_ref(&*o)) - } + unsafe { ptr::read(self.ptr.get()).map(|o| DomRoot::from_ref(&*o)) } } /// Set this `MutNullableDom` to the given value. @@ -617,17 +607,13 @@ impl<T: DomObject> MutNullableDom<T> { impl<T: DomObject> PartialEq for MutNullableDom<T> { fn eq(&self, other: &Self) -> bool { - unsafe { - *self.ptr.get() == *other.ptr.get() - } + unsafe { *self.ptr.get() == *other.ptr.get() } } } impl<'a, T: DomObject> PartialEq<Option<&'a T>> for MutNullableDom<T> { fn eq(&self, other: &Option<&T>) -> bool { - unsafe { - *self.ptr.get() == other.map(Dom::from_ref) - } + unsafe { *self.ptr.get() == other.map(Dom::from_ref) } } } @@ -661,13 +647,14 @@ pub struct DomOnceCell<T: DomObject> { impl<T> DomOnceCell<T> where - T: DomObject + T: DomObject, { /// Retrieve a copy of the current inner value. If it is `None`, it is /// initialized with the result of `cb` first. #[allow(unrooted_must_root)] pub fn init_once<F>(&self, cb: F) -> &T - where F: FnOnce() -> DomRoot<T> + where + F: FnOnce() -> DomRoot<T>, { debug_assert!(thread_state::get().is_script()); &self.ptr.init_once(|| Dom::from_ref(&cb())) @@ -725,14 +712,17 @@ pub trait OptionalHeapSetter { fn set(&mut self, v: Option<Self::Value>); } -impl<T: GCMethods + Copy> OptionalHeapSetter for Option<Heap<T>> where Heap<T>: Default { +impl<T: GCMethods + Copy> OptionalHeapSetter for Option<Heap<T>> +where + Heap<T>: Default, +{ type Value = T; fn set(&mut self, v: Option<T>) { let v = match v { None => { *self = None; return; - } + }, Some(v) => v, }; diff --git a/components/script/dom/bindings/settings_stack.rs b/components/script/dom/bindings/settings_stack.rs index f9438f17065..e5efea05e98 100644 --- a/components/script/dom/bindings/settings_stack.rs +++ b/components/script/dom/bindings/settings_stack.rs @@ -36,9 +36,7 @@ pub unsafe fn trace(tracer: *mut JSTracer) { } pub fn is_execution_stack_empty() -> bool { - STACK.with(|stack| { - stack.borrow().is_empty() - }) + STACK.with(|stack| stack.borrow().is_empty()) } /// RAII struct that pushes and pops entries from the script settings stack. @@ -69,9 +67,10 @@ impl Drop for AutoEntryScript { STACK.with(|stack| { let mut stack = stack.borrow_mut(); let entry = stack.pop().unwrap(); - assert_eq!(&*entry.global as *const GlobalScope, - &*self.global as *const GlobalScope, - "Dropped AutoEntryScript out of order."); + assert_eq!( + &*entry.global as *const GlobalScope, &*self.global as *const GlobalScope, + "Dropped AutoEntryScript out of order." + ); assert_eq!(entry.kind, StackEntryKind::Entry); trace!("Clean up after running script with {:p}", &*entry.global); }); @@ -87,13 +86,15 @@ impl Drop for AutoEntryScript { /// /// ["entry"]: https://html.spec.whatwg.org/multipage/#entry pub fn entry_global() -> DomRoot<GlobalScope> { - STACK.with(|stack| { - stack.borrow() - .iter() - .rev() - .find(|entry| entry.kind == StackEntryKind::Entry) - .map(|entry| DomRoot::from_ref(&*entry.global)) - }).unwrap() + STACK + .with(|stack| { + stack + .borrow() + .iter() + .rev() + .find(|entry| entry.kind == StackEntryKind::Entry) + .map(|entry| DomRoot::from_ref(&*entry.global)) + }).unwrap() } /// RAII struct that pushes and pops entries from the script settings stack. @@ -133,11 +134,15 @@ impl Drop for AutoIncumbentScript { let mut stack = stack.borrow_mut(); let entry = stack.pop().unwrap(); // Step 3. - assert_eq!(&*entry.global as *const GlobalScope as usize, - self.global, - "Dropped AutoIncumbentScript out of order."); + assert_eq!( + &*entry.global as *const GlobalScope as usize, self.global, + "Dropped AutoIncumbentScript out of order." + ); assert_eq!(entry.kind, StackEntryKind::Incumbent); - trace!("Clean up after running a callback with {:p}", &*entry.global); + trace!( + "Clean up after running a callback with {:p}", + &*entry.global + ); }); unsafe { // Step 1-2. @@ -169,8 +174,9 @@ pub fn incumbent_global() -> Option<DomRoot<GlobalScope>> { // Step 2: nothing from the JS engine. Let's use whatever's on the explicit stack. STACK.with(|stack| { - stack.borrow() - .last() - .map(|entry| DomRoot::from_ref(&*entry.global)) + stack + .borrow() + .last() + .map(|entry| DomRoot::from_ref(&*entry.global)) }) } diff --git a/components/script/dom/bindings/str.rs b/components/script/dom/bindings/str.rs index c4cc5f51d21..e52cf7755a3 100644 --- a/components/script/dom/bindings/str.rs +++ b/components/script/dom/bindings/str.rs @@ -82,7 +82,6 @@ impl ops::Deref for ByteString { #[derive(Clone, Default, MallocSizeOf)] pub struct USVString(pub String); - /// Returns whether `s` is a `token`, as defined by /// [RFC 2616](http://tools.ietf.org/html/rfc2616#page-17). pub fn is_token(s: &[u8]) -> bool { @@ -93,31 +92,14 @@ pub fn is_token(s: &[u8]) -> bool { // http://tools.ietf.org/html/rfc2616#section-2.2 match x { 0...31 | 127 => false, // CTLs - 40 | - 41 | - 60 | - 62 | - 64 | - 44 | - 59 | - 58 | - 92 | - 34 | - 47 | - 91 | - 93 | - 63 | - 61 | - 123 | - 125 | - 32 => false, // separators + 40 | 41 | 60 | 62 | 64 | 44 | 59 | 58 | 92 | 34 | 47 | 91 | 93 | 63 | 61 | 123 | + 125 | 32 => false, // separators x if x > 127 => false, // non-CHARs _ => true, } }) } - /// A DOMString. /// /// This type corresponds to the [`DOMString`](idl) type in WebIDL. @@ -196,14 +178,16 @@ impl DOMString { /// Removes leading and trailing ASCII whitespaces according to /// <https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace>. pub fn strip_leading_and_trailing_ascii_whitespace(&mut self) { - if self.0.len() == 0 { return; } + if self.0.len() == 0 { + return; + } let last_non_whitespace = match self.0.rfind(|ref c| !char::is_ascii_whitespace(c)) { Some(idx) => idx + 1, None => { self.0.clear(); return; - } + }, }; let first_non_whitespace = self.0.find(|ref c| !char::is_ascii_whitespace(c)).unwrap(); @@ -231,17 +215,21 @@ impl DOMString { Done, Error, } - let next_state = |valid: bool, next: State| -> State { if valid { next } else { State::Error } }; + let next_state = |valid: bool, next: State| -> State { + if valid { + next + } else { + State::Error + } + }; let state = self.chars().fold(State::HourHigh, |state, c| { match state { // Step 1 "HH" - State::HourHigh => { - match c { - '0' | '1' => State::HourLow09, - '2' => State::HourLow03, - _ => State::Error, - } + State::HourHigh => match c { + '0' | '1' => State::HourLow09, + '2' => State::HourLow03, + _ => State::Error, }, State::HourLow09 => next_state(c.is_digit(10), State::MinuteColon), State::HourLow03 => next_state(c.is_digit(4), State::MinuteColon), @@ -323,15 +311,21 @@ impl DOMString { /// where date and time are both valid, and the time string must be as short as possible /// https://html.spec.whatwg.org/multipage/#valid-normalised-local-date-and-time-string pub fn convert_valid_normalized_local_date_and_time_string(&mut self) -> Result<(), ()> { - let ((year, month, day), (hour, minute, second)) = parse_local_date_and_time_string(&*self.0)?; + let ((year, month, day), (hour, minute, second)) = + parse_local_date_and_time_string(&*self.0)?; if second == 0.0 { - self.0 = format!("{:04}-{:02}-{:02}T{:02}:{:02}", year, month, day, hour, minute); + self.0 = format!( + "{:04}-{:02}-{:02}T{:02}:{:02}", + year, month, day, hour, minute + ); } else { - self.0 = format!("{:04}-{:02}-{:02}T{:02}:{:02}:{}", year, month, day, hour, minute, second); + self.0 = format!( + "{:04}-{:02}-{:02}T{:02}:{:02}:{}", + year, month, day, hour, minute, second + ); } Ok(()) } - } impl Borrow<str> for DOMString { @@ -452,7 +446,10 @@ impl<'a> Into<CowRcStr<'a>> for DOMString { } impl Extend<char> for DOMString { - fn extend<I>(&mut self, iterable: I) where I: IntoIterator<Item=char> { + fn extend<I>(&mut self, iterable: I) + where + I: IntoIterator<Item = char>, + { self.0.extend(iterable) } } @@ -541,7 +538,7 @@ fn parse_month_component(value: &str) -> Result<(u32, u32), ()> { // Step 4, 5 let month_int = month.parse::<u32>().map_err(|_| ())?; - if month.len() != 2 || month_int > 12 || month_int < 1 { + if month.len() != 2 || month_int > 12 || month_int < 1 { return Err(()); } @@ -611,12 +608,12 @@ fn parse_time_component(value: &str) -> Result<(u32, u32, f32), ()> { return Err(()); } }, - None => {} + None => {}, } second.parse::<f32>().map_err(|_| ())? }, - None => 0.0 + None => 0.0, }; // Step 8 @@ -624,7 +621,7 @@ fn parse_time_component(value: &str) -> Result<(u32, u32, f32), ()> { } /// https://html.spec.whatwg.org/multipage/#parse-a-local-date-and-time-string -fn parse_local_date_and_time_string(value: &str) -> Result<((u32, u32, u32), (u32, u32, f32)), ()> { +fn parse_local_date_and_time_string(value: &str) -> Result<((u32, u32, u32), (u32, u32, f32)), ()> { // Step 1, 2, 4 let mut iterator = if value.contains('T') { value.split('T') @@ -651,8 +648,8 @@ fn parse_local_date_and_time_string(value: &str) -> Result<((u32, u32, u32), (u fn max_day_in_month(year_num: u32, month_num: u32) -> Result<u32, ()> { match month_num { - 1|3|5|7|8|10|12 => Ok(31), - 4|6|9|11 => Ok(30), + 1 | 3 | 5 | 7 | 8 | 10 | 12 => Ok(31), + 4 | 6 | 9 | 11 => Ok(30), 2 => { if is_leap_year(year_num) { Ok(29) @@ -660,7 +657,7 @@ fn max_day_in_month(year_num: u32, month_num: u32) -> Result<u32, ()> { Ok(28) } }, - _ => Err(()) + _ => Err(()), } } @@ -669,7 +666,7 @@ fn max_week_in_year(year: u32) -> u32 { match Utc.ymd(year as i32, 1, 1).weekday() { Weekday::Thu => 53, Weekday::Wed if is_leap_year(year) => 53, - _ => 52 + _ => 52, } } @@ -681,14 +678,16 @@ fn is_leap_year(year: u32) -> bool { /// https://html.spec.whatwg.org/multipage/#rules-for-parsing-floating-point-number-values fn parse_floating_point_number(input: &str) -> Result<f64, ()> { match input.trim().parse::<f64>() { - Ok(val) if !( + Ok(val) + if !( // A valid number is the same as what rust considers to be valid, // except for +1., NaN, and Infinity. val.is_infinite() || val.is_nan() || input.ends_with(".") || input.starts_with("+") - ) => { + ) => + { // TODO(#19773): need consider `min`, `max`, `step`, when they are implemented Ok(val.round()) - }, - _ => Err(()) + } + _ => Err(()), } } diff --git a/components/script/dom/bindings/structuredclone.rs b/components/script/dom/bindings/structuredclone.rs index d530a51e7bc..c4a68547247 100644 --- a/components/script/dom/bindings/structuredclone.rs +++ b/components/script/dom/bindings/structuredclone.rs @@ -47,35 +47,39 @@ enum StructuredCloneTags { } #[cfg(target_pointer_width = "64")] -unsafe fn write_length(w: *mut JSStructuredCloneWriter, - length: usize) { - let high: u32 = (length >> 32) as u32; - let low: u32 = length as u32; - assert!(JS_WriteUint32Pair(w, high, low)); +unsafe fn write_length(w: *mut JSStructuredCloneWriter, length: usize) { + let high: u32 = (length >> 32) as u32; + let low: u32 = length as u32; + assert!(JS_WriteUint32Pair(w, high, low)); } #[cfg(target_pointer_width = "32")] -unsafe fn write_length(w: *mut JSStructuredCloneWriter, - length: usize) { - assert!(JS_WriteUint32Pair(w, length as u32, 0)); +unsafe fn write_length(w: *mut JSStructuredCloneWriter, length: usize) { + assert!(JS_WriteUint32Pair(w, length as u32, 0)); } #[cfg(target_pointer_width = "64")] -unsafe fn read_length(r: *mut JSStructuredCloneReader) - -> usize { - let mut high: u32 = 0; - let mut low: u32 = 0; - assert!(JS_ReadUint32Pair(r, &mut high as *mut u32, &mut low as *mut u32)); - return (low << high) as usize; +unsafe fn read_length(r: *mut JSStructuredCloneReader) -> usize { + let mut high: u32 = 0; + let mut low: u32 = 0; + assert!(JS_ReadUint32Pair( + r, + &mut high as *mut u32, + &mut low as *mut u32 + )); + return (low << high) as usize; } #[cfg(target_pointer_width = "32")] -unsafe fn read_length(r: *mut JSStructuredCloneReader) - -> usize { - let mut length: u32 = 0; - let mut zero: u32 = 0; - assert!(JS_ReadUint32Pair(r, &mut length as *mut u32, &mut zero as *mut u32)); - return length as usize; +unsafe fn read_length(r: *mut JSStructuredCloneReader) -> usize { + let mut length: u32 = 0; + let mut zero: u32 = 0; + assert!(JS_ReadUint32Pair( + r, + &mut length as *mut u32, + &mut zero as *mut u32 + )); + return length as usize; } struct StructuredCloneWriter { @@ -86,7 +90,11 @@ impl StructuredCloneWriter { unsafe fn write_slice(&self, v: &[u8]) { let type_length = v.len(); write_length(self.w, type_length); - assert!(JS_WriteBytes(self.w, v.as_ptr() as *const raw::c_void, type_length)); + assert!(JS_WriteBytes( + self.w, + v.as_ptr() as *const raw::c_void, + type_length + )); } unsafe fn write_str(&self, s: &str) { self.write_slice(s.as_bytes()); @@ -101,7 +109,11 @@ impl StructuredCloneReader { unsafe fn read_bytes(&self) -> Vec<u8> { let mut bytes = vec![0u8; read_length(self.r)]; let blob_length = bytes.len(); - assert!(JS_ReadBytes(self.r, bytes.as_mut_ptr() as *mut raw::c_void, blob_length)); + assert!(JS_ReadBytes( + self.r, + bytes.as_mut_ptr() as *mut raw::c_void, + blob_length + )); return bytes; } unsafe fn read_str(&self) -> String { @@ -110,87 +122,105 @@ impl StructuredCloneReader { } } -unsafe fn read_blob(cx: *mut JSContext, - r: *mut JSStructuredCloneReader, - sc_holder: &mut StructuredCloneHolder) - -> *mut JSObject { +unsafe fn read_blob( + cx: *mut JSContext, + r: *mut JSStructuredCloneReader, + sc_holder: &mut StructuredCloneHolder, +) -> *mut JSObject { let structured_reader = StructuredCloneReader { r: r }; let blob_buffer = structured_reader.read_bytes(); let type_str = structured_reader.read_str(); let target_global = GlobalScope::from_context(cx); - let blob = Blob::new(&target_global, BlobImpl::new_from_bytes(blob_buffer), type_str); + let blob = Blob::new( + &target_global, + BlobImpl::new_from_bytes(blob_buffer), + type_str, + ); let js_object = blob.reflector().get_jsobject().get(); sc_holder.blob = Some(blob); js_object } -unsafe fn write_blob(blob: DomRoot<Blob>, - w: *mut JSStructuredCloneWriter) - -> Result<(), ()> { +unsafe fn write_blob(blob: DomRoot<Blob>, w: *mut JSStructuredCloneWriter) -> Result<(), ()> { let structured_writer = StructuredCloneWriter { w: w }; let blob_vec = blob.get_bytes()?; - assert!(JS_WriteUint32Pair(w, StructuredCloneTags::DomBlob as u32, 0)); + assert!(JS_WriteUint32Pair( + w, + StructuredCloneTags::DomBlob as u32, + 0 + )); structured_writer.write_slice(&blob_vec); structured_writer.write_str(&blob.type_string()); - return Ok(()) + return Ok(()); } -unsafe extern "C" fn read_callback(cx: *mut JSContext, - r: *mut JSStructuredCloneReader, - tag: u32, - _data: u32, - closure: *mut raw::c_void) - -> *mut JSObject { - assert!(tag < StructuredCloneTags::Max as u32, "tag should be lower than StructuredCloneTags::Max"); - assert!(tag > StructuredCloneTags::Min as u32, "tag should be higher than StructuredCloneTags::Min"); +unsafe extern "C" fn read_callback( + cx: *mut JSContext, + r: *mut JSStructuredCloneReader, + tag: u32, + _data: u32, + closure: *mut raw::c_void, +) -> *mut JSObject { + assert!( + tag < StructuredCloneTags::Max as u32, + "tag should be lower than StructuredCloneTags::Max" + ); + assert!( + tag > StructuredCloneTags::Min as u32, + "tag should be higher than StructuredCloneTags::Min" + ); if tag == StructuredCloneTags::DomBlob as u32 { - return read_blob(cx, r, &mut *(closure as *mut StructuredCloneHolder)) + return read_blob(cx, r, &mut *(closure as *mut StructuredCloneHolder)); } - return ptr::null_mut() + return ptr::null_mut(); } -unsafe extern "C" fn write_callback(_cx: *mut JSContext, - w: *mut JSStructuredCloneWriter, - obj: RawHandleObject, - _closure: *mut raw::c_void) - -> bool { +unsafe extern "C" fn write_callback( + _cx: *mut JSContext, + w: *mut JSStructuredCloneWriter, + obj: RawHandleObject, + _closure: *mut raw::c_void, +) -> bool { if let Ok(blob) = root_from_handleobject::<Blob>(Handle::from_raw(obj)) { - return write_blob(blob, w).is_ok() + return write_blob(blob, w).is_ok(); } - return false + return false; } -unsafe extern "C" fn read_transfer_callback(_cx: *mut JSContext, - _r: *mut JSStructuredCloneReader, - _tag: u32, - _content: *mut raw::c_void, - _extra_data: u64, - _closure: *mut raw::c_void, - _return_object: RawMutableHandleObject) - -> bool { +unsafe extern "C" fn read_transfer_callback( + _cx: *mut JSContext, + _r: *mut JSStructuredCloneReader, + _tag: u32, + _content: *mut raw::c_void, + _extra_data: u64, + _closure: *mut raw::c_void, + _return_object: RawMutableHandleObject, +) -> bool { false } -unsafe extern "C" fn write_transfer_callback(_cx: *mut JSContext, - _obj: RawHandleObject, - _closure: *mut raw::c_void, - _tag: *mut u32, - _ownership: *mut TransferableOwnership, - _content: *mut *mut raw::c_void, - _extra_data: *mut u64) - -> bool { +unsafe extern "C" fn write_transfer_callback( + _cx: *mut JSContext, + _obj: RawHandleObject, + _closure: *mut raw::c_void, + _tag: *mut u32, + _ownership: *mut TransferableOwnership, + _content: *mut *mut raw::c_void, + _extra_data: *mut u64, +) -> bool { false } -unsafe extern "C" fn free_transfer_callback(_tag: u32, - _ownership: TransferableOwnership, - _content: *mut raw::c_void, - _extra_data: u64, - _closure: *mut raw::c_void) { +unsafe extern "C" fn free_transfer_callback( + _tag: u32, + _ownership: TransferableOwnership, + _content: *mut raw::c_void, + _extra_data: u64, + _closure: *mut raw::c_void, +) { } -unsafe extern "C" fn report_error_callback(_cx: *mut JSContext, _errorid: u32) { -} +unsafe extern "C" fn report_error_callback(_cx: *mut JSContext, _errorid: u32) {} static STRUCTURED_CLONE_CALLBACKS: JSStructuredCloneCallbacks = JSStructuredCloneCallbacks { read: Some(read_callback), @@ -202,7 +232,7 @@ static STRUCTURED_CLONE_CALLBACKS: JSStructuredCloneCallbacks = JSStructuredClon }; struct StructuredCloneHolder { - blob: Option<DomRoot<Blob>> + blob: Option<DomRoot<Blob>>, } /// A buffer for a structured clone. @@ -210,7 +240,7 @@ pub enum StructuredCloneData { /// A non-serializable (default) variant Struct(*mut u64, size_t), /// A variant that can be serialized - Vector(Vec<u8>) + Vector(Vec<u8>), } impl StructuredCloneData { @@ -218,21 +248,25 @@ impl StructuredCloneData { /// Writes a structured clone. Returns a `DataClone` error if that fails. pub fn write(cx: *mut JSContext, message: HandleValue) -> Fallible<StructuredCloneData> { unsafe { - let scbuf = NewJSAutoStructuredCloneBuffer(StructuredCloneScope::DifferentProcess, - &STRUCTURED_CLONE_CALLBACKS); + let scbuf = NewJSAutoStructuredCloneBuffer( + StructuredCloneScope::DifferentProcess, + &STRUCTURED_CLONE_CALLBACKS, + ); let scdata = &mut ((*scbuf).data_); let policy = CloneDataPolicy { // TODO: SAB? sharedArrayBuffer_: false, }; - let result = JS_WriteStructuredClone(cx, - message, - scdata, - StructuredCloneScope::DifferentProcess, - policy, - &STRUCTURED_CLONE_CALLBACKS, - ptr::null_mut(), - HandleValue::undefined()); + let result = JS_WriteStructuredClone( + cx, + message, + scdata, + StructuredCloneScope::DifferentProcess, + policy, + &STRUCTURED_CLONE_CALLBACKS, + ptr::null_mut(), + HandleValue::undefined(), + ); if !result { JS_ClearPendingException(cx); return Err(Error::DataClone); @@ -252,41 +286,40 @@ impl StructuredCloneData { /// Converts a StructuredCloneData to Vec<u8> for inter-thread sharing pub fn move_to_arraybuffer(self) -> Vec<u8> { match self { - StructuredCloneData::Struct(data, nbytes) => { - unsafe { - slice::from_raw_parts(data as *mut u8, nbytes).to_vec() - } - } - StructuredCloneData::Vector(msg) => msg + StructuredCloneData::Struct(data, nbytes) => unsafe { + slice::from_raw_parts(data as *mut u8, nbytes).to_vec() + }, + StructuredCloneData::Vector(msg) => msg, } } /// Reads a structured clone. /// /// Panics if `JS_ReadStructuredClone` fails. - fn read_clone(global: &GlobalScope, - data: *mut u64, - nbytes: size_t, - rval: MutableHandleValue) { + fn read_clone(global: &GlobalScope, data: *mut u64, nbytes: size_t, rval: MutableHandleValue) { let cx = global.get_cx(); let globalhandle = global.reflector().get_jsobject(); let _ac = JSAutoCompartment::new(cx, globalhandle.get()); let mut sc_holder = StructuredCloneHolder { blob: None }; let sc_holder_ptr = &mut sc_holder as *mut _; unsafe { - let scbuf = NewJSAutoStructuredCloneBuffer(StructuredCloneScope::DifferentProcess, - &STRUCTURED_CLONE_CALLBACKS); + let scbuf = NewJSAutoStructuredCloneBuffer( + StructuredCloneScope::DifferentProcess, + &STRUCTURED_CLONE_CALLBACKS, + ); let scdata = &mut ((*scbuf).data_); WriteBytesToJSStructuredCloneData(data as *const u8, nbytes, scdata); - assert!(JS_ReadStructuredClone(cx, - scdata, - JS_STRUCTURED_CLONE_VERSION, - StructuredCloneScope::DifferentProcess, - rval, - &STRUCTURED_CLONE_CALLBACKS, - sc_holder_ptr as *mut raw::c_void)); + assert!(JS_ReadStructuredClone( + cx, + scdata, + JS_STRUCTURED_CLONE_VERSION, + StructuredCloneScope::DifferentProcess, + rval, + &STRUCTURED_CLONE_CALLBACKS, + sc_holder_ptr as *mut raw::c_void + )); DeleteJSAutoStructuredCloneBuffer(scbuf); } @@ -299,8 +332,10 @@ impl StructuredCloneData { let nbytes = vec_msg.len(); let data = vec_msg.as_mut_ptr() as *mut u64; StructuredCloneData::read_clone(global, data, nbytes, rval); - } - StructuredCloneData::Struct(data, nbytes) => StructuredCloneData::read_clone(global, data, nbytes, rval) + }, + StructuredCloneData::Struct(data, nbytes) => { + StructuredCloneData::read_clone(global, data, nbytes, rval) + }, } } } diff --git a/components/script/dom/bindings/trace.rs b/components/script/dom/bindings/trace.rs index ca01ff600d8..2c395094e7f 100644 --- a/components/script/dom/bindings/trace.rs +++ b/components/script/dom/bindings/trace.rs @@ -149,9 +149,11 @@ pub fn trace_jsval(tracer: *mut JSTracer, description: &str, val: &Heap<JSVal>) } trace!("tracing value {}", description); - CallValueTracer(tracer, - val.ptr.get() as *mut _, - GCTraceKindToAscii(val.get().trace_kind())); + CallValueTracer( + tracer, + val.ptr.get() as *mut _, + GCTraceKindToAscii(val.get().trace_kind()), + ); } } @@ -166,9 +168,11 @@ pub fn trace_reflector(tracer: *mut JSTracer, description: &str, reflector: &Ref pub fn trace_object(tracer: *mut JSTracer, description: &str, obj: &Heap<*mut JSObject>) { unsafe { trace!("tracing {}", description); - CallObjectTracer(tracer, - obj.ptr.get() as *mut _, - GCTraceKindToAscii(TraceKind::Object)); + CallObjectTracer( + tracer, + obj.ptr.get() as *mut _, + GCTraceKindToAscii(TraceKind::Object), + ); } } @@ -295,9 +299,10 @@ unsafe impl<T: JSTraceable, U: JSTraceable> JSTraceable for Result<T, U> { } unsafe impl<K, V, S> JSTraceable for HashMap<K, V, S> - where K: Hash + Eq + JSTraceable, - V: JSTraceable, - S: BuildHasher, +where + K: Hash + Eq + JSTraceable, + V: JSTraceable, + S: BuildHasher, { #[inline] unsafe fn trace(&self, trc: *mut JSTracer) { @@ -309,8 +314,9 @@ unsafe impl<K, V, S> JSTraceable for HashMap<K, V, S> } unsafe impl<T, S> JSTraceable for HashSet<T, S> - where T: Hash + Eq + JSTraceable, - S: BuildHasher, +where + T: Hash + Eq + JSTraceable, + S: BuildHasher, { #[inline] unsafe fn trace(&self, trc: *mut JSTracer) { @@ -365,7 +371,12 @@ unsafe_no_jsmanaged_fields!(PropertyDeclarationBlock); // These three are interdependent, if you plan to put jsmanaged data // in one of these make sure it is propagated properly to containing structs unsafe_no_jsmanaged_fields!(DocumentActivity, WindowSizeData, WindowSizeType); -unsafe_no_jsmanaged_fields!(BrowsingContextId, HistoryStateId, PipelineId, TopLevelBrowsingContextId); +unsafe_no_jsmanaged_fields!( + BrowsingContextId, + HistoryStateId, + PipelineId, + TopLevelBrowsingContextId +); unsafe_no_jsmanaged_fields!(TimerEventId, TimerSource); unsafe_no_jsmanaged_fields!(TimelineMarkerType); unsafe_no_jsmanaged_fields!(WorkerId); @@ -459,7 +470,10 @@ unsafe impl<'a, A, B> JSTraceable for fn(&A) -> B { } } -unsafe impl<T> JSTraceable for IpcSender<T> where T: for<'de> Deserialize<'de> + Serialize { +unsafe impl<T> JSTraceable for IpcSender<T> +where + T: for<'de> Deserialize<'de> + Serialize, +{ #[inline] unsafe fn trace(&self, _: *mut JSTracer) { // Do nothing @@ -481,7 +495,10 @@ unsafe impl JSTraceable for () { } } -unsafe impl<T> JSTraceable for IpcReceiver<T> where T: for<'de> Deserialize<'de> + Serialize { +unsafe impl<T> JSTraceable for IpcReceiver<T> +where + T: for<'de> Deserialize<'de> + Serialize, +{ #[inline] unsafe fn trace(&self, _: *mut JSTracer) { // Do nothing @@ -509,14 +526,20 @@ unsafe impl<T: Send> JSTraceable for Sender<T> { } } -unsafe impl<T: Send> JSTraceable for WebGLReceiver<T> where T: for<'de> Deserialize<'de> + Serialize { +unsafe impl<T: Send> JSTraceable for WebGLReceiver<T> +where + T: for<'de> Deserialize<'de> + Serialize, +{ #[inline] unsafe fn trace(&self, _: *mut JSTracer) { // Do nothing } } -unsafe impl<T: Send> JSTraceable for WebGLSender<T> where T: for<'de> Deserialize<'de> + Serialize { +unsafe impl<T: Send> JSTraceable for WebGLSender<T> +where + T: for<'de> Deserialize<'de> + Serialize, +{ #[inline] unsafe fn trace(&self, _: *mut JSTracer) { // Do nothing @@ -665,7 +688,10 @@ unsafe impl JSTraceable for StyleLocked<MediaList> { } } -unsafe impl<T> JSTraceable for TypedArray<T, Box<Heap<*mut JSObject>>> where T: TypedArrayElement { +unsafe impl<T> JSTraceable for TypedArray<T, Box<Heap<*mut JSObject>>> +where + T: TypedArrayElement, +{ unsafe fn trace(&self, trc: *mut JSTracer) { self.underlying_object().trace(trc); } @@ -682,34 +708,26 @@ where } } - /// Holds a set of JSTraceables that need to be rooted struct RootedTraceableSet { set: Vec<*const JSTraceable>, } -thread_local!( - /// TLV Holds a set of JSTraceables that need to be rooted - static ROOTED_TRACEABLES: RefCell<RootedTraceableSet> = - RefCell::new(RootedTraceableSet::new()); -); +thread_local!(/// TLV Holds a set of JSTraceables that need to be rooted +static ROOTED_TRACEABLES: RefCell<RootedTraceableSet> = RefCell::new(RootedTraceableSet::new());); impl RootedTraceableSet { fn new() -> RootedTraceableSet { - RootedTraceableSet { - set: vec![], - } + RootedTraceableSet { set: vec![] } } unsafe fn remove(traceable: *const JSTraceable) { ROOTED_TRACEABLES.with(|ref traceables| { let mut traceables = traceables.borrow_mut(); - let idx = - match traceables.set.iter() - .rposition(|x| *x == traceable) { - Some(idx) => idx, - None => unreachable!(), - }; + let idx = match traceables.set.iter().rposition(|x| *x == traceable) { + Some(idx) => idx, + None => unreachable!(), + }; traceables.set.remove(idx); }); } @@ -744,9 +762,7 @@ impl<'a, T: JSTraceable + 'static> RootedTraceable<'a, T> { unsafe { RootedTraceableSet::add(traceable); } - RootedTraceable { - ptr: traceable, - } + RootedTraceable { ptr: traceable } } } @@ -787,16 +803,14 @@ impl<T: JSTraceable + 'static> RootedTraceableBox<T> { unsafe { RootedTraceableSet::add(traceable); } - RootedTraceableBox { - ptr: traceable, - } + RootedTraceableBox { ptr: traceable } } } impl<T> RootedTraceableBox<Heap<T>> - where - Heap<T>: JSTraceable + 'static, - T: GCMethods + Copy, +where + Heap<T>: JSTraceable + 'static, + T: GCMethods + Copy, { pub fn handle(&self) -> Handle<T> { unsafe { Handle::from_raw((*self.ptr).handle()) } @@ -812,17 +826,13 @@ impl<T: JSTraceable + Default> Default for RootedTraceableBox<T> { impl<T: JSTraceable> Deref for RootedTraceableBox<T> { type Target = T; fn deref(&self) -> &T { - unsafe { - &*self.ptr - } + unsafe { &*self.ptr } } } impl<T: JSTraceable> DerefMut for RootedTraceableBox<T> { fn deref_mut(&mut self) -> &mut T { - unsafe { - &mut *self.ptr - } + unsafe { &mut *self.ptr } } } @@ -849,9 +859,7 @@ pub struct RootableVec<T: JSTraceable> { impl<T: JSTraceable> RootableVec<T> { /// Create a vector of items of type T that can be rooted later. pub fn new_unrooted() -> RootableVec<T> { - RootableVec { - v: vec![], - } + RootableVec { v: vec![] } } } @@ -868,9 +876,7 @@ impl<'a, T: 'static + JSTraceable> RootedVec<'a, T> { unsafe { RootedTraceableSet::add(root); } - RootedVec { - root: root, - } + RootedVec { root: root } } } @@ -878,15 +884,14 @@ impl<'a, T: 'static + JSTraceable + DomObject> RootedVec<'a, Dom<T>> { /// Create a vector of items of type Dom<T> that is rooted for /// the lifetime of this struct pub fn from_iter<I>(root: &'a mut RootableVec<Dom<T>>, iter: I) -> Self - where I: Iterator<Item = DomRoot<T>> + where + I: Iterator<Item = DomRoot<T>>, { unsafe { RootedTraceableSet::add(root); } root.v.extend(iter.map(|item| Dom::from_ref(&*item))); - RootedVec { - root: root, - } + RootedVec { root: root } } } diff --git a/components/script/dom/bindings/utils.rs b/components/script/dom/bindings/utils.rs index a82786f2143..7366401af51 100644 --- a/components/script/dom/bindings/utils.rs +++ b/components/script/dom/bindings/utils.rs @@ -85,7 +85,6 @@ pub const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT; // changes. pub const JSCLASS_DOM_GLOBAL: u32 = js::JSCLASS_USERBIT1; - /// The struct that holds inheritance information for DOM object reflectors. #[derive(Clone, Copy)] pub struct DOMClass { @@ -137,13 +136,14 @@ pub type ProtoOrIfaceArray = [*mut JSObject; PROTO_OR_IFACE_LENGTH]; /// set to true and `*vp` to the value, otherwise `*found` is set to false. /// /// Returns false on JSAPI failure. -pub unsafe fn get_property_on_prototype(cx: *mut JSContext, - proxy: HandleObject, - receiver: HandleValue, - id: HandleId, - found: *mut bool, - vp: MutableHandleValue) - -> bool { +pub unsafe fn get_property_on_prototype( + cx: *mut JSContext, + proxy: HandleObject, + receiver: HandleValue, + id: HandleId, + found: *mut bool, + vp: MutableHandleValue, +) -> bool { rooted!(in(cx) let mut proto = ptr::null_mut::<JSObject>()); if !JS_GetPrototype(cx, proxy, proto.handle_mut()) || proto.is_null() { *found = false; @@ -184,23 +184,29 @@ pub fn get_array_index_from_id(_cx: *mut JSContext, id: HandleId) -> Option<u32> return if StringIsArray(str, &mut i) != 0 { i } else { -1 } } else { IdToInt32(cx, id); - }*/ -} + }*/} /// Find the enum equivelent of a string given by `v` in `pairs`. /// Returns `Err(())` on JSAPI failure (there is a pending exception), and /// `Ok((None, value))` if there was no matching string. -pub unsafe fn find_enum_value<'a, T>(cx: *mut JSContext, - v: HandleValue, - pairs: &'a [(&'static str, T)]) - -> Result<(Option<&'a T>, DOMString), ()> { +pub unsafe fn find_enum_value<'a, T>( + cx: *mut JSContext, + v: HandleValue, + pairs: &'a [(&'static str, T)], +) -> Result<(Option<&'a T>, DOMString), ()> { let jsstr = ToString(cx, v); if jsstr.is_null() { return Err(()); } let search = jsstring_to_str(cx, jsstr); - Ok((pairs.iter().find(|&&(key, _)| search == *key).map(|&(_, ref ev)| ev), search)) + Ok(( + pairs + .iter() + .find(|&&(key, _)| search == *key) + .map(|&(_, ref ev)| ev), + search, + )) } /// Returns wether `obj` is a platform object @@ -228,23 +234,26 @@ pub fn is_platform_object(obj: *mut JSObject) -> bool { /// Get the property with name `property` from `object`. /// Returns `Err(())` on JSAPI failure (there is a pending exception), and /// `Ok(false)` if there was no property with the given name. -pub fn get_dictionary_property(cx: *mut JSContext, - object: HandleObject, - property: &str, - rval: MutableHandleValue) - -> Result<bool, ()> { - fn has_property(cx: *mut JSContext, - object: HandleObject, - property: &CString, - found: &mut bool) - -> bool { +pub fn get_dictionary_property( + cx: *mut JSContext, + object: HandleObject, + property: &str, + rval: MutableHandleValue, +) -> Result<bool, ()> { + fn has_property( + cx: *mut JSContext, + object: HandleObject, + property: &CString, + found: &mut bool, + ) -> bool { unsafe { JS_HasProperty(cx, object, property.as_ptr(), found) } } - fn get_property(cx: *mut JSContext, - object: HandleObject, - property: &CString, - value: MutableHandleValue) - -> bool { + fn get_property( + cx: *mut JSContext, + object: HandleObject, + property: &CString, + value: MutableHandleValue, + ) -> bool { unsafe { JS_GetProperty(cx, object, property.as_ptr(), value) } } @@ -272,11 +281,12 @@ pub fn get_dictionary_property(cx: *mut JSContext, /// Set the property with name `property` from `object`. /// Returns `Err(())` on JSAPI failure, or null object, /// and Ok(()) otherwise -pub fn set_dictionary_property(cx: *mut JSContext, - object: HandleObject, - property: &str, - value: HandleValue) - -> Result<(), ()> { +pub fn set_dictionary_property( + cx: *mut JSContext, + object: HandleObject, + property: &str, + value: HandleValue, +) -> Result<(), ()> { if object.get().is_null() { return Err(()); } @@ -292,11 +302,12 @@ pub fn set_dictionary_property(cx: *mut JSContext, } /// Returns whether `proxy` has a property `id` on its prototype. -pub unsafe fn has_property_on_prototype(cx: *mut JSContext, - proxy: HandleObject, - id: HandleId, - found: &mut bool) - -> bool { +pub unsafe fn has_property_on_prototype( + cx: *mut JSContext, + proxy: HandleObject, + id: HandleId, + found: &mut bool, +) -> bool { rooted!(in(cx) let mut proto = ptr::null_mut::<JSObject>()); if !JS_GetPrototype(cx, proxy, proto.handle_mut()) { return false; @@ -322,9 +333,11 @@ pub unsafe fn trace_global(tracer: *mut JSTracer, obj: *mut JSObject) { let array = get_proto_or_iface_array(obj); for proto in (*array).iter() { if !proto.is_null() { - trace_object(tracer, - "prototype", - &*(proto as *const *mut JSObject as *const Heap<*mut JSObject>)); + trace_object( + tracer, + "prototype", + &*(proto as *const *mut JSObject as *const Heap<*mut JSObject>), + ); } } } @@ -343,11 +356,11 @@ pub unsafe extern "C" fn enumerate_global(cx: *mut JSContext, obj: RawHandleObje /// Resolve a lazy global property, for interface objects and named constructors. pub unsafe extern "C" fn resolve_global( - cx: *mut JSContext, - obj: RawHandleObject, - id: RawHandleId, - rval: *mut bool) - -> bool { + cx: *mut JSContext, + obj: RawHandleObject, + id: RawHandleId, + rval: *mut bool, +) -> bool { assert!(JS_IsGlobalObject(obj.get())); if !JS_ResolveStandardClass(cx, obj, id, rval) { return false; @@ -379,20 +392,23 @@ pub unsafe extern "C" fn resolve_global( true } -unsafe extern "C" fn wrap(cx: *mut JSContext, - _existing: RawHandleObject, - obj: RawHandleObject) - -> *mut JSObject { +unsafe extern "C" fn wrap( + cx: *mut JSContext, + _existing: RawHandleObject, + obj: RawHandleObject, +) -> *mut JSObject { // FIXME terrible idea. need security wrappers // https://github.com/servo/servo/issues/2382 WrapperNew(cx, obj, GetCrossCompartmentWrapper(), ptr::null(), false) } -unsafe extern "C" fn pre_wrap(cx: *mut JSContext, - _scope: RawHandleObject, - obj: RawHandleObject, - _object_passed_to_wrap: RawHandleObject, - rval: RawMutableHandleObject) { +unsafe extern "C" fn pre_wrap( + cx: *mut JSContext, + _scope: RawHandleObject, + obj: RawHandleObject, + _object_passed_to_wrap: RawHandleObject, + rval: RawMutableHandleObject, +) { let _ac = JSAutoCompartment::new(cx, obj.get()); let obj = ToWindowProxyIfWindow(obj.get()); assert!(!obj.is_null()); @@ -406,23 +422,29 @@ pub static WRAP_CALLBACKS: JSWrapObjectCallbacks = JSWrapObjectCallbacks { }; /// Deletes the property `id` from `object`. -pub unsafe fn delete_property_by_id(cx: *mut JSContext, - object: HandleObject, - id: HandleId, - bp: *mut ObjectOpResult) - -> bool { +pub unsafe fn delete_property_by_id( + cx: *mut JSContext, + object: HandleObject, + id: HandleId, + bp: *mut ObjectOpResult, +) -> bool { JS_DeletePropertyById(cx, object, id, bp) } -unsafe fn generic_call(cx: *mut JSContext, - argc: libc::c_uint, - vp: *mut JSVal, - is_lenient: bool, - call: unsafe extern fn(*const JSJitInfo, *mut JSContext, - RawHandleObject, *mut libc::c_void, u32, - *mut JSVal) - -> bool) - -> bool { +unsafe fn generic_call( + cx: *mut JSContext, + argc: libc::c_uint, + vp: *mut JSVal, + is_lenient: bool, + call: unsafe extern "C" fn( + *const JSJitInfo, + *mut JSContext, + RawHandleObject, + *mut libc::c_void, + u32, + *mut JSVal, + ) -> bool, +) -> bool { let args = CallArgs::from_vp(vp, argc); let info = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp)); @@ -441,9 +463,8 @@ unsafe fn generic_call(cx: *mut JSContext, }; rooted!(in(cx) let obj = obj); let depth = (*info).depth; - let proto_check = |class: &'static DOMClass| { - class.interface_chain[depth as usize] as u16 == proto_id - }; + let proto_check = + |class: &'static DOMClass| class.interface_chain[depth as usize] as u16 == proto_id; let this = match private_from_proto_check(obj.get(), proto_check) { Ok(val) => val, Err(()) => { @@ -455,42 +476,53 @@ unsafe fn generic_call(cx: *mut JSContext, throw_invalid_this(cx, proto_id); return false; } - } + }, }; - call(info, cx, obj.handle().into(), this as *mut libc::c_void, argc, vp) + call( + info, + cx, + obj.handle().into(), + this as *mut libc::c_void, + argc, + vp, + ) } /// Generic method of IDL interface. -pub unsafe extern "C" fn generic_method(cx: *mut JSContext, - argc: libc::c_uint, - vp: *mut JSVal) - -> bool { +pub unsafe extern "C" fn generic_method( + cx: *mut JSContext, + argc: libc::c_uint, + vp: *mut JSVal, +) -> bool { generic_call(cx, argc, vp, false, CallJitMethodOp) } /// Generic getter of IDL interface. -pub unsafe extern "C" fn generic_getter(cx: *mut JSContext, - argc: libc::c_uint, - vp: *mut JSVal) - -> bool { +pub unsafe extern "C" fn generic_getter( + cx: *mut JSContext, + argc: libc::c_uint, + vp: *mut JSVal, +) -> bool { generic_call(cx, argc, vp, false, CallJitGetterOp) } /// Generic lenient getter of IDL interface. -pub unsafe extern "C" fn generic_lenient_getter(cx: *mut JSContext, - argc: libc::c_uint, - vp: *mut JSVal) - -> bool { +pub unsafe extern "C" fn generic_lenient_getter( + cx: *mut JSContext, + argc: libc::c_uint, + vp: *mut JSVal, +) -> bool { generic_call(cx, argc, vp, true, CallJitGetterOp) } -unsafe extern "C" fn call_setter(info: *const JSJitInfo, - cx: *mut JSContext, - handle: RawHandleObject, - this: *mut libc::c_void, - argc: u32, - vp: *mut JSVal) - -> bool { +unsafe extern "C" fn call_setter( + info: *const JSJitInfo, + cx: *mut JSContext, + handle: RawHandleObject, + this: *mut libc::c_void, + argc: u32, + vp: *mut JSVal, +) -> bool { if !CallJitSetterOp(info, cx, handle, this, argc, vp) { return false; } @@ -499,31 +531,34 @@ unsafe extern "C" fn call_setter(info: *const JSJitInfo, } /// Generic setter of IDL interface. -pub unsafe extern "C" fn generic_setter(cx: *mut JSContext, - argc: libc::c_uint, - vp: *mut JSVal) - -> bool { +pub unsafe extern "C" fn generic_setter( + cx: *mut JSContext, + argc: libc::c_uint, + vp: *mut JSVal, +) -> bool { generic_call(cx, argc, vp, false, call_setter) } /// Generic lenient setter of IDL interface. -pub unsafe extern "C" fn generic_lenient_setter(cx: *mut JSContext, - argc: libc::c_uint, - vp: *mut JSVal) - -> bool { +pub unsafe extern "C" fn generic_lenient_setter( + cx: *mut JSContext, + argc: libc::c_uint, + vp: *mut JSVal, +) -> bool { generic_call(cx, argc, vp, true, call_setter) } -unsafe extern "C" fn instance_class_has_proto_at_depth(clasp: *const js::jsapi::Class, - proto_id: u32, - depth: u32) - -> bool { +unsafe extern "C" fn instance_class_has_proto_at_depth( + clasp: *const js::jsapi::Class, + proto_id: u32, + depth: u32, +) -> bool { let domclass: *const DOMJSClass = clasp as *const _; let domclass = &*domclass; domclass.dom_class.interface_chain[depth as usize] as u32 == proto_id } -#[allow(missing_docs)] // FIXME +#[allow(missing_docs)] // FIXME pub const DOM_CALLBACKS: DOMCallbacks = DOMCallbacks { instanceClassMatchesProto: Some(instance_class_has_proto_at_depth), }; diff --git a/components/script/dom/bindings/weakref.rs b/components/script/dom/bindings/weakref.rs index 4cafafc0440..aed0d9ec6f8 100644 --- a/components/script/dom/bindings/weakref.rs +++ b/components/script/dom/bindings/weakref.rs @@ -70,9 +70,11 @@ pub trait WeakReferenceable: DomObject + Sized { let box_ = &*ptr; assert!(box_.value.get().is_some()); let new_count = box_.count.get() + 1; - trace!("Incrementing WeakBox refcount for {:p} to {}.", - self, - new_count); + trace!( + "Incrementing WeakBox refcount for {:p} to {}.", + self, + new_count + ); box_.count.set(new_count); WeakRef { ptr: ptr::NonNull::new_unchecked(ptr), @@ -91,9 +93,10 @@ impl<T: WeakReferenceable> WeakRef<T> { /// DomRoot a weak reference. Returns `None` if the object was already collected. pub fn root(&self) -> Option<DomRoot<T>> { - unsafe { &*self.ptr.as_ptr() }.value.get().map(|ptr| unsafe { - DomRoot::from_ref(&*ptr.as_ptr()) - }) + unsafe { &*self.ptr.as_ptr() } + .value + .get() + .map(|ptr| unsafe { DomRoot::from_ref(&*ptr.as_ptr()) }) } /// Return whether the weakly-referenced object is still alive. @@ -108,9 +111,7 @@ impl<T: WeakReferenceable> Clone for WeakRef<T> { let box_ = &*self.ptr.as_ptr(); let new_count = box_.count.get() + 1; box_.count.set(new_count); - WeakRef { - ptr: self.ptr, - } + WeakRef { ptr: self.ptr } } } } @@ -122,10 +123,10 @@ impl<T: WeakReferenceable> MallocSizeOf for WeakRef<T> { } impl<T: WeakReferenceable> PartialEq for WeakRef<T> { - fn eq(&self, other: &Self) -> bool { + fn eq(&self, other: &Self) -> bool { unsafe { (*self.ptr.as_ptr()).value.get().map(ptr::NonNull::as_ptr) == - (*other.ptr.as_ptr()).value.get().map(ptr::NonNull::as_ptr) + (*other.ptr.as_ptr()).value.get().map(ptr::NonNull::as_ptr) } } } @@ -190,7 +191,9 @@ impl<T: WeakReferenceable> MutableWeakRef<T> { /// DomRoot a mutable weak reference. Returns `None` if the object /// was already collected. pub fn root(&self) -> Option<DomRoot<T>> { - unsafe { &*self.cell.get() }.as_ref().and_then(WeakRef::root) + unsafe { &*self.cell.get() } + .as_ref() + .and_then(WeakRef::root) } } @@ -233,7 +236,10 @@ impl<T: WeakReferenceable> WeakRefVec<T> { let mut i = 0; while i < self.vec.len() { if self.vec[i].is_alive() { - f(WeakRefEntry { vec: self, index: &mut i }); + f(WeakRefEntry { + vec: self, + index: &mut i, + }); } else { self.vec.swap_remove(i); } @@ -293,13 +299,13 @@ impl<'a, T: WeakReferenceable + 'a> Drop for WeakRefEntry<'a, T> { #[derive(MallocSizeOf)] pub struct DOMTracker<T: WeakReferenceable> { - dom_objects: DomRefCell<WeakRefVec<T>> + dom_objects: DomRefCell<WeakRefVec<T>>, } impl<T: WeakReferenceable> DOMTracker<T> { pub fn new() -> Self { Self { - dom_objects: DomRefCell::new(WeakRefVec::new()) + dom_objects: DomRefCell::new(WeakRefVec::new()), } } diff --git a/components/script/dom/bindings/xmlname.rs b/components/script/dom/bindings/xmlname.rs index fc330b7563d..2a2b8a462a0 100644 --- a/components/script/dom/bindings/xmlname.rs +++ b/components/script/dom/bindings/xmlname.rs @@ -25,9 +25,10 @@ pub fn validate_qualified_name(qualified_name: &str) -> ErrorResult { /// Validate a namespace and qualified name and extract their parts. /// See https://dom.spec.whatwg.org/#validate-and-extract for details. -pub fn validate_and_extract(namespace: Option<DOMString>, - qualified_name: &str) - -> Fallible<(Namespace, Option<Prefix>, LocalName)> { +pub fn validate_and_extract( + namespace: Option<DOMString>, + qualified_name: &str, +) -> Fallible<(Namespace, Option<Prefix>, LocalName)> { // Step 1. let namespace = namespace_from_domstring(namespace); @@ -76,7 +77,7 @@ pub fn validate_and_extract(namespace: Option<DOMString>, (ns, p) => { // Step 10. Ok((ns, p.map(Prefix::from), LocalName::from(local_name))) - } + }, } } @@ -115,14 +116,10 @@ pub fn xml_name_type(name: &str) -> XMLName { } fn is_valid_continuation(c: char) -> bool { - is_valid_start(c) || - match c { - '-' | - '.' | - '0'...'9' | - '\u{B7}' | - '\u{300}'...'\u{36F}' | - '\u{203F}'...'\u{2040}' => true, + is_valid_start(c) || match c { + '-' | '.' | '0'...'9' | '\u{B7}' | '\u{300}'...'\u{36F}' | '\u{203F}'...'\u{2040}' => { + true + }, _ => false, } } @@ -140,7 +137,7 @@ pub fn xml_name_type(name: &str) -> XMLName { non_qname_colons = true; } c - } + }, }; for c in iter { diff --git a/components/script/dom/blob.rs b/components/script/dom/blob.rs index d8017f23ffa..490404bbf32 100644 --- a/components/script/dom/blob.rs +++ b/components/script/dom/blob.rs @@ -30,7 +30,6 @@ pub struct FileBlob { size: u64, } - /// Different backends of Blob #[must_root] #[derive(JSTraceable)] @@ -43,7 +42,7 @@ pub enum BlobImpl { /// relative positions of current slicing range, /// IMPORTANT: The depth of tree is only two, i.e. the parent Blob must be /// either File-based or Memory-based - Sliced(Dom<Blob>, RelativePos) + Sliced(Dom<Blob>, RelativePos), } impl BlobImpl { @@ -76,9 +75,7 @@ pub struct Blob { impl Blob { #[allow(unrooted_must_root)] - pub fn new( - global: &GlobalScope, blob_impl: BlobImpl, typeString: String) - -> DomRoot<Blob> { + pub fn new(global: &GlobalScope, blob_impl: BlobImpl, typeString: String) -> DomRoot<Blob> { let boxed_blob = Box::new(Blob::new_inherited(blob_impl, typeString)); reflect_dom_object(boxed_blob, global, BlobBinding::Wrap) } @@ -95,41 +92,49 @@ impl Blob { } #[allow(unrooted_must_root)] - fn new_sliced(parent: &Blob, rel_pos: RelativePos, - relative_content_type: DOMString) -> DomRoot<Blob> { + fn new_sliced( + parent: &Blob, + rel_pos: RelativePos, + relative_content_type: DOMString, + ) -> DomRoot<Blob> { let blob_impl = match *parent.blob_impl.borrow() { BlobImpl::File(_) => { // Create new parent node BlobImpl::Sliced(Dom::from_ref(parent), rel_pos) - } + }, BlobImpl::Memory(_) => { // Create new parent node BlobImpl::Sliced(Dom::from_ref(parent), rel_pos) - } + }, BlobImpl::Sliced(ref grandparent, ref old_rel_pos) => { // Adjust the slicing position, using same parent BlobImpl::Sliced(grandparent.clone(), old_rel_pos.slice_inner(&rel_pos)) - } + }, }; Blob::new(&parent.global(), blob_impl, relative_content_type.into()) } // https://w3c.github.io/FileAPI/#constructorBlob - pub fn Constructor(global: &GlobalScope, - blobParts: Option<Vec<ArrayBufferOrArrayBufferViewOrBlobOrString>>, - blobPropertyBag: &BlobBinding::BlobPropertyBag) - -> Fallible<DomRoot<Blob>> { + pub fn Constructor( + global: &GlobalScope, + blobParts: Option<Vec<ArrayBufferOrArrayBufferViewOrBlobOrString>>, + blobPropertyBag: &BlobBinding::BlobPropertyBag, + ) -> Fallible<DomRoot<Blob>> { // TODO: accept other blobParts types - ArrayBuffer or ArrayBufferView 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), - } + }, }; - Ok(Blob::new(global, BlobImpl::new_from_bytes(bytes), blobPropertyBag.type_.to_string())) + Ok(Blob::new( + global, + BlobImpl::new_from_bytes(bytes), + blobPropertyBag.type_.to_string(), + )) } /// Get a slice to inner data, this might incur synchronous read and caching @@ -141,7 +146,7 @@ impl Blob { None => { let bytes = read_file(&self.global(), f.id.clone())?; (bytes, true) - } + }, }; // Cache @@ -150,14 +155,12 @@ impl Blob { } Ok(buffer) - } + }, BlobImpl::Memory(ref s) => Ok(s.clone()), - BlobImpl::Sliced(ref parent, ref rel_pos) => { - parent.get_bytes().map(|v| { - let range = rel_pos.to_abs_range(v.len()); - v.index(range).to_vec() - }) - } + BlobImpl::Sliced(ref parent, ref rel_pos) => parent.get_bytes().map(|v| { + let range = rel_pos.to_abs_range(v.len()); + v.index(range).to_vec() + }), } } @@ -171,13 +174,19 @@ impl Blob { pub fn get_blob_url_id(&self) -> Uuid { let opt_sliced_parent = match *self.blob_impl.borrow() { BlobImpl::Sliced(ref parent, ref rel_pos) => { - Some((parent.promote(/* set_valid is */ false), rel_pos.clone(), parent.Size())) - } - _ => None + Some(( + parent.promote(/* set_valid is */ false), + rel_pos.clone(), + parent.Size(), + )) + }, + _ => None, }; match opt_sliced_parent { - Some((parent_id, rel_pos, size)) => self.create_sliced_url_id(&parent_id, &rel_pos, size), + Some((parent_id, rel_pos, size)) => { + self.create_sliced_url_id(&parent_id, &rel_pos, size) + }, None => self.promote(/* set_valid is */ true), } } @@ -196,13 +205,15 @@ impl Blob { debug!("Sliced can't have a sliced parent"); // Return dummy id return Uuid::new_v4(); - } + }, BlobImpl::File(ref f) => { if set_valid { let origin = get_blob_origin(&global_url); - let (tx, rx) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); + let (tx, rx) = + ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); - let msg = FileManagerThreadMsg::ActivateBlobURL(f.id.clone(), tx, origin.clone()); + let msg = + FileManagerThreadMsg::ActivateBlobURL(f.id.clone(), tx, origin.clone()); self.send_to_file_manager(msg); match rx.recv().unwrap() { @@ -214,7 +225,7 @@ impl Blob { // no need to activate return f.id.clone(); } - } + }, BlobImpl::Memory(ref mut bytes_in) => mem::swap(bytes_in, &mut bytes), }; @@ -240,21 +251,28 @@ impl Blob { size: bytes.len() as u64, }); id - } + }, // Dummy id Err(_) => Uuid::new_v4(), } } /// Get a FileID representing sliced parent-blob content - fn create_sliced_url_id(&self, parent_id: &Uuid, - rel_pos: &RelativePos, parent_len: u64) -> Uuid { + fn create_sliced_url_id( + &self, + parent_id: &Uuid, + rel_pos: &RelativePos, + parent_len: u64, + ) -> Uuid { let origin = get_blob_origin(&self.global().get_url()); let (tx, rx) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); - let msg = FileManagerThreadMsg::AddSlicedURLEntry(parent_id.clone(), - rel_pos.clone(), - tx, origin.clone()); + let msg = FileManagerThreadMsg::AddSlicedURLEntry( + parent_id.clone(), + rel_pos.clone(), + tx, + origin.clone(), + ); self.send_to_file_manager(msg); match rx.recv().expect("File manager thread is down") { Ok(new_id) => { @@ -267,11 +285,11 @@ impl Blob { // Return the indirect id reference new_id - } + }, Err(_) => { // Return dummy id Uuid::new_v4() - } + }, } } @@ -303,7 +321,7 @@ impl Drop for Blob { fn read_file(global: &GlobalScope, id: Uuid) -> Result<Vec<u8>, ()> { let resource_threads = global.resource_threads(); - let (chan, recv) = ipc::channel(global.time_profiler_chan().clone()).map_err(|_|())?; + let (chan, recv) = ipc::channel(global.time_profiler_chan().clone()).map_err(|_| ())?; let origin = get_blob_origin(&global.get_url()); let check_url_validity = false; let msg = FileManagerThreadMsg::ReadFile(chan, id, check_url_validity, origin); @@ -315,13 +333,13 @@ fn read_file(global: &GlobalScope, id: Uuid) -> Result<Vec<u8>, ()> { match recv.recv().unwrap() { Ok(ReadFileProgress::Meta(mut blob_buf)) => { bytes.append(&mut blob_buf.bytes); - } + }, Ok(ReadFileProgress::Partial(mut bytes_in)) => { bytes.append(&mut bytes_in); - } + }, Ok(ReadFileProgress::EOF) => { return Ok(bytes); - } + }, Err(_) => return Err(()), } } @@ -330,7 +348,9 @@ fn read_file(global: &GlobalScope, id: Uuid) -> Result<Vec<u8>, ()> { /// Extract bytes from BlobParts, used by Blob and File constructor /// <https://w3c.github.io/FileAPI/#constructorBlob> #[allow(unsafe_code)] -pub fn blob_parts_to_bytes(mut blobparts: Vec<ArrayBufferOrArrayBufferViewOrBlobOrString>) -> Result<Vec<u8>, ()> { +pub fn blob_parts_to_bytes( + mut blobparts: Vec<ArrayBufferOrArrayBufferViewOrBlobOrString>, +) -> Result<Vec<u8>, ()> { let mut ret = vec![]; for blobpart in &mut blobparts { match blobpart { @@ -348,7 +368,7 @@ pub fn blob_parts_to_bytes(mut blobparts: Vec<ArrayBufferOrArrayBufferViewOrBlob &mut ArrayBufferOrArrayBufferViewOrBlobOrString::ArrayBufferView(ref mut a) => unsafe { let bytes = a.as_slice(); ret.extend(bytes); - } + }, } } @@ -359,10 +379,11 @@ impl BlobMethods for Blob { // https://w3c.github.io/FileAPI/#dfn-size fn Size(&self) -> u64 { match *self.blob_impl.borrow() { - BlobImpl::File(ref f) => f.size, - BlobImpl::Memory(ref v) => v.len() as u64, - BlobImpl::Sliced(ref parent, ref rel_pos) => - rel_pos.to_abs_range(parent.Size() as usize).len() as u64, + BlobImpl::File(ref f) => f.size, + BlobImpl::Memory(ref v) => v.len() as u64, + BlobImpl::Sliced(ref parent, ref rel_pos) => { + rel_pos.to_abs_range(parent.Size() as usize).len() as u64 + }, } } @@ -372,11 +393,12 @@ impl BlobMethods for Blob { } // https://w3c.github.io/FileAPI/#slice-method-algo - fn Slice(&self, - start: Option<i64>, - end: Option<i64>, - content_type: Option<DOMString>) - -> DomRoot<Blob> { + fn Slice( + &self, + start: Option<i64>, + end: Option<i64>, + content_type: Option<DOMString>, + ) -> DomRoot<Blob> { let rel_pos = RelativePos::from_opts(start, end); Blob::new_sliced(self, rel_pos, content_type.unwrap_or(DOMString::from(""))) } @@ -391,8 +413,8 @@ fn normalize_type_string(s: &str) -> String { if is_ascii_printable(s) { let s_lower = s.to_ascii_lowercase(); // match s_lower.parse() as Result<Mime, ()> { - // Ok(_) => s_lower, - // Err(_) => "".to_string() + // Ok(_) => s_lower, + // Err(_) => "".to_string() s_lower } else { "".to_string() diff --git a/components/script/dom/bluetooth.rs b/components/script/dom/bluetooth.rs index b980562c46d..99c02576a1b 100644 --- a/components/script/dom/bluetooth.rs +++ b/components/script/dom/bluetooth.rs @@ -12,7 +12,7 @@ use dom::bindings::codegen::Bindings::BluetoothBinding::{self, BluetoothDataFilt use dom::bindings::codegen::Bindings::BluetoothBinding::{BluetoothMethods, RequestDeviceOptions}; use dom::bindings::codegen::Bindings::BluetoothPermissionResultBinding::BluetoothPermissionDescriptor; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerBinding:: - BluetoothRemoteGATTServerMethods; +BluetoothRemoteGATTServerMethods; use dom::bindings::codegen::Bindings::PermissionStatusBinding::{PermissionName, PermissionState}; use dom::bindings::codegen::UnionTypes::{ArrayBufferViewOrArrayBuffer, StringOrUnsignedLong}; use dom::bindings::error::Error::{self, Network, Security, Type}; @@ -42,20 +42,26 @@ use std::str::FromStr; use std::sync::{Arc, Mutex}; use task::TaskOnce; -const KEY_CONVERSION_ERROR: &'static str = "This `manufacturerData` key can not be parsed as unsigned short:"; -const FILTER_EMPTY_ERROR: &'static str = "'filters' member, if present, must be nonempty to find any devices."; +const KEY_CONVERSION_ERROR: &'static str = + "This `manufacturerData` key can not be parsed as unsigned short:"; +const FILTER_EMPTY_ERROR: &'static str = + "'filters' member, if present, must be nonempty to find any devices."; const FILTER_ERROR: &'static str = "A filter must restrict the devices in some way."; -const MANUFACTURER_DATA_ERROR: &'static str = "'manufacturerData', if present, must be non-empty to filter devices."; -const MASK_LENGTH_ERROR: &'static str = "`mask`, if present, must have the same length as `dataPrefix`."; +const MANUFACTURER_DATA_ERROR: &'static str = + "'manufacturerData', if present, must be non-empty to filter devices."; +const MASK_LENGTH_ERROR: &'static str = + "`mask`, if present, must have the same length as `dataPrefix`."; // 248 is the maximum number of UTF-8 code units in a Bluetooth Device Name. const MAX_DEVICE_NAME_LENGTH: usize = 248; const NAME_PREFIX_ERROR: &'static str = "'namePrefix', if present, must be nonempty."; const NAME_TOO_LONG_ERROR: &'static str = "A device name can't be longer than 248 bytes."; -const SERVICE_DATA_ERROR: &'static str = "'serviceData', if present, must be non-empty to filter devices."; +const SERVICE_DATA_ERROR: &'static str = + "'serviceData', if present, must be non-empty to filter devices."; const SERVICE_ERROR: &'static str = "'services', if present, must contain at least one service."; const OPTIONS_ERROR: &'static str = "Fields of 'options' conflict with each other. Either 'acceptAllDevices' member must be true, or 'filters' member must be set to a value."; -const BT_DESC_CONVERSION_ERROR: &'static str = "Can't convert to an IDL value of type BluetoothPermissionDescriptor"; +const BT_DESC_CONVERSION_ERROR: &'static str = + "Can't convert to an IDL value of type BluetoothPermissionDescriptor"; #[derive(JSTraceable, MallocSizeOf)] pub struct AllowedBluetoothDevice { @@ -84,7 +90,10 @@ impl BluetoothExtraPermissionData { } pub fn allowed_devices_contains_id(&self, id: DOMString) -> bool { - self.allowed_devices.borrow().iter().any(|d| d.deviceId == id) + self.allowed_devices + .borrow() + .iter() + .any(|d| d.deviceId == id) } } @@ -132,9 +141,11 @@ impl Bluetooth { } pub fn new(global: &GlobalScope) -> DomRoot<Bluetooth> { - reflect_dom_object(Box::new(Bluetooth::new_inherited()), - global, - BluetoothBinding::Wrap) + reflect_dom_object( + Box::new(Bluetooth::new_inherited()), + global, + BluetoothBinding::Wrap, + ) } fn get_bluetooth_thread(&self) -> IpcSender<BluetoothRequest> { @@ -146,19 +157,21 @@ impl Bluetooth { } // https://webbluetoothcg.github.io/web-bluetooth/#request-bluetooth-devices - fn request_bluetooth_devices(&self, - p: &Rc<Promise>, - filters: &Option<Vec<BluetoothLEScanFilterInit>>, - optional_services: &Option<Vec<BluetoothServiceUUID>>, - sender: IpcSender<BluetoothResponseResult>) { + fn request_bluetooth_devices( + &self, + p: &Rc<Promise>, + filters: &Option<Vec<BluetoothLEScanFilterInit>>, + optional_services: &Option<Vec<BluetoothServiceUUID>>, + sender: IpcSender<BluetoothResponseResult>, + ) { // TODO: Step 1: Triggered by user activation. // Step 2.2: There are no requiredServiceUUIDS, we scan for all devices. - let mut uuid_filters = vec!(); + let mut uuid_filters = vec![]; if let &Some(ref filters) = filters { // Step 2.1. - if filters.is_empty() { + if filters.is_empty() { p.reject_error(Type(FILTER_EMPTY_ERROR.to_owned())); return; } @@ -180,7 +193,7 @@ impl Bluetooth { } } - let mut optional_services_uuids = vec!(); + let mut optional_services_uuids = vec![]; if let &Some(ref opt_services) = optional_services { for opt_service in opt_services { // Step 2.5 - 2.6. @@ -201,71 +214,83 @@ impl Bluetooth { } } - let option = RequestDeviceoptions::new(BluetoothScanfilterSequence::new(uuid_filters), - ServiceUUIDSequence::new(optional_services_uuids)); + let option = RequestDeviceoptions::new( + BluetoothScanfilterSequence::new(uuid_filters), + ServiceUUIDSequence::new(optional_services_uuids), + ); // Step 4 - 5. - if let PermissionState::Denied = get_descriptor_permission_state(PermissionName::Bluetooth, None) { + if let PermissionState::Denied = + get_descriptor_permission_state(PermissionName::Bluetooth, None) + { return p.reject_error(Error::NotFound); } // Note: Step 3, 6 - 8 are implemented in // components/net/bluetooth_thread.rs in request_device function. - self.get_bluetooth_thread().send(BluetoothRequest::RequestDevice(option, sender)).unwrap(); + self.get_bluetooth_thread() + .send(BluetoothRequest::RequestDevice(option, sender)) + .unwrap(); } } pub fn response_async<T: AsyncBluetoothListener + DomObject + 'static>( - promise: &Rc<Promise>, - receiver: &T) -> IpcSender<BluetoothResponseResult> { + promise: &Rc<Promise>, + receiver: &T, +) -> IpcSender<BluetoothResponseResult> { let (action_sender, action_receiver) = ipc::channel().unwrap(); let task_source = receiver.global().networking_task_source(); let context = Arc::new(Mutex::new(BluetoothContext { promise: Some(TrustedPromise::new(promise.clone())), receiver: Trusted::new(receiver), })); - ROUTER.add_route(action_receiver.to_opaque(), Box::new(move |message| { - struct ListenerTask<T: AsyncBluetoothListener + DomObject> { - context: Arc<Mutex<BluetoothContext<T>>>, - action: BluetoothResponseResult, - } + ROUTER.add_route( + action_receiver.to_opaque(), + Box::new(move |message| { + struct ListenerTask<T: AsyncBluetoothListener + DomObject> { + context: Arc<Mutex<BluetoothContext<T>>>, + action: BluetoothResponseResult, + } - impl<T> TaskOnce for ListenerTask<T> - where - T: AsyncBluetoothListener + DomObject, - { - fn run_once(self) { - let mut context = self.context.lock().unwrap(); - context.response(self.action); + impl<T> TaskOnce for ListenerTask<T> + where + T: AsyncBluetoothListener + DomObject, + { + fn run_once(self) { + let mut context = self.context.lock().unwrap(); + context.response(self.action); + } } - } - let task = ListenerTask { - context: context.clone(), - action: message.to().unwrap(), - }; + let task = ListenerTask { + context: context.clone(), + action: message.to().unwrap(), + }; - let result = task_source.queue_unconditionally(task); - if let Err(err) = result { - warn!("failed to deliver network data: {:?}", err); - } - })); + let result = task_source.queue_unconditionally(task); + if let Err(err) = result { + warn!("failed to deliver network data: {:?}", err); + } + }), + ); action_sender } #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#getgattchildren -pub fn get_gatt_children<T, F> ( - attribute: &T, - single: bool, - uuid_canonicalizer: F, - uuid: Option<StringOrUnsignedLong>, - instance_id: String, - connected: bool, - child_type: GATTType) - -> Rc<Promise> - where T: AsyncBluetoothListener + DomObject + 'static, - F: FnOnce(StringOrUnsignedLong) -> Fallible<UUID> { +pub fn get_gatt_children<T, F>( + attribute: &T, + single: bool, + uuid_canonicalizer: F, + uuid: Option<StringOrUnsignedLong>, + instance_id: String, + connected: bool, + child_type: GATTType, +) -> Rc<Promise> +where + T: AsyncBluetoothListener + DomObject + 'static, + F: FnOnce(StringOrUnsignedLong) -> Fallible<UUID>, +{ let p = Promise::new(&attribute.global()); let result_uuid = if let Some(u) = uuid { @@ -275,7 +300,7 @@ pub fn get_gatt_children<T, F> ( Err(e) => { p.reject_error(e); return p; - } + }, }; // Step 2. if uuid_is_blocklisted(canonicalized.as_ref(), Blocklist::All) { @@ -298,8 +323,17 @@ pub fn get_gatt_children<T, F> ( // Note: Steps 6 - 7 are implemented in components/bluetooth/lib.rs in get_descriptor function // and in handle_response function. let sender = response_async(&p, attribute); - attribute.global().as_window().bluetooth_thread().send( - BluetoothRequest::GetGATTChildren(instance_id, result_uuid, single, child_type, sender)).unwrap(); + attribute + .global() + .as_window() + .bluetooth_thread() + .send(BluetoothRequest::GetGATTChildren( + instance_id, + result_uuid, + single, + child_type, + sender, + )).unwrap(); return p; } @@ -307,11 +341,12 @@ pub fn get_gatt_children<T, F> ( fn canonicalize_filter(filter: &BluetoothLEScanFilterInit) -> Fallible<BluetoothScanfilter> { // Step 1. if filter.services.is_none() && - filter.name.is_none() && - filter.namePrefix.is_none() && - filter.manufacturerData.is_none() && - filter.serviceData.is_none() { - return Err(Type(FILTER_ERROR.to_owned())); + filter.name.is_none() && + filter.namePrefix.is_none() && + filter.manufacturerData.is_none() && + filter.serviceData.is_none() + { + return Err(Type(FILTER_ERROR.to_owned())); } // Step 2: There is no empty canonicalizedFilter member, @@ -325,7 +360,7 @@ fn canonicalize_filter(filter: &BluetoothLEScanFilterInit) -> Fallible<Bluetooth return Err(Type(SERVICE_ERROR.to_owned())); } - let mut services_vec = vec!(); + let mut services_vec = vec![]; for service in services { // Step 3.2 - 3.3. @@ -333,7 +368,7 @@ fn canonicalize_filter(filter: &BluetoothLEScanFilterInit) -> Fallible<Bluetooth // Step 3.4. if uuid_is_blocklisted(uuid.as_ref(), Blocklist::All) { - return Err(Security) + return Err(Security); } services_vec.push(uuid); @@ -341,7 +376,7 @@ fn canonicalize_filter(filter: &BluetoothLEScanFilterInit) -> Fallible<Bluetooth // Step 3.5. services_vec }, - None => vec!(), + None => vec![], }; // Step 4. @@ -388,13 +423,18 @@ fn canonicalize_filter(filter: &BluetoothLEScanFilterInit) -> Fallible<Bluetooth // Step 7.1 - 7.2. let manufacturer_id = match u16::from_str(key.as_ref()) { Ok(id) => id, - Err(err) => return Err(Type(format!("{} {} {}", KEY_CONVERSION_ERROR, key, err))), + Err(err) => { + return Err(Type(format!("{} {} {}", KEY_CONVERSION_ERROR, key, err))) + }, }; // Step 7.3: No need to convert to IDL values since this is only used by native code. // Step 7.4 - 7.5. - map.insert(manufacturer_id, canonicalize_bluetooth_data_filter_init(bdfi)?); + map.insert( + manufacturer_id, + canonicalize_bluetooth_data_filter_init(bdfi)?, + ); } Some(map) }, @@ -414,7 +454,7 @@ fn canonicalize_filter(filter: &BluetoothLEScanFilterInit) -> Fallible<Bluetooth // Step 9.1. Ok(number) => StringOrUnsignedLong::UnsignedLong(number), // Step 9.2. - _ => StringOrUnsignedLong::String(key.clone()) + _ => StringOrUnsignedLong::String(key.clone()), }; // Step 9.3 - 9.4. @@ -436,16 +476,24 @@ fn canonicalize_filter(filter: &BluetoothLEScanFilterInit) -> Fallible<Bluetooth }; // Step 10. - Ok(BluetoothScanfilter::new(name, name_prefix, services_vec, manufacturer_data, service_data)) + Ok(BluetoothScanfilter::new( + name, + name_prefix, + services_vec, + manufacturer_data, + service_data, + )) } // https://webbluetoothcg.github.io/web-bluetooth/#bluetoothdatafilterinit-canonicalizing -fn canonicalize_bluetooth_data_filter_init(bdfi: &BluetoothDataFilterInit) -> Fallible<(Vec<u8>, Vec<u8>)> { +fn canonicalize_bluetooth_data_filter_init( + bdfi: &BluetoothDataFilterInit, +) -> Fallible<(Vec<u8>, Vec<u8>)> { // Step 1. let data_prefix = match bdfi.dataPrefix { Some(ArrayBufferViewOrArrayBuffer::ArrayBufferView(ref avb)) => avb.to_vec(), Some(ArrayBufferViewOrArrayBuffer::ArrayBuffer(ref ab)) => ab.to_vec(), - None => vec![] + None => vec![], }; // Step 2. @@ -454,7 +502,7 @@ fn canonicalize_bluetooth_data_filter_init(bdfi: &BluetoothDataFilterInit) -> Fa let mask = match bdfi.mask { Some(ArrayBufferViewOrArrayBuffer::ArrayBufferView(ref avb)) => avb.to_vec(), Some(ArrayBufferViewOrArrayBuffer::ArrayBuffer(ref ab)) => ab.to_vec(), - None => vec![0xFF; data_prefix.len()] + None => vec![0xFF; data_prefix.len()], }; // Step 3. @@ -486,7 +534,8 @@ impl BluetoothMethods for Bluetooth { let p = Promise::new(&self.global()); // Step 1. if (option.filters.is_some() && option.acceptAllDevices) || - (option.filters.is_none() && !option.acceptAllDevices) { + (option.filters.is_none() && !option.acceptAllDevices) + { p.reject_error(Error::Type(OPTIONS_ERROR.to_owned())); return p; } @@ -505,13 +554,18 @@ impl BluetoothMethods for Bluetooth { // Step 1. We did not override the method // Step 2 - 3. in handle_response let sender = response_async(&p, self); - self.get_bluetooth_thread().send( - BluetoothRequest::GetAvailability(sender)).unwrap(); + self.get_bluetooth_thread() + .send(BluetoothRequest::GetAvailability(sender)) + .unwrap(); p } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-onavailabilitychanged - event_handler!(availabilitychanged, GetOnavailabilitychanged, SetOnavailabilitychanged); + event_handler!( + availabilitychanged, + GetOnavailabilitychanged, + SetOnavailabilitychanged + ); } impl AsyncBluetoothListener for Bluetooth { @@ -524,18 +578,21 @@ impl AsyncBluetoothListener for Bluetooth { if let Some(existing_device) = device_instance_map.get(&device.id.clone()) { return promise.resolve_native(&**existing_device); } - let bt_device = BluetoothDevice::new(&self.global(), - DOMString::from(device.id.clone()), - device.name.map(DOMString::from), - &self); + let bt_device = BluetoothDevice::new( + &self.global(), + DOMString::from(device.id.clone()), + device.name.map(DOMString::from), + &self, + ); device_instance_map.insert(device.id.clone(), Dom::from_ref(&bt_device)); - self.global().as_window().bluetooth_extra_permission_data().add_new_allowed_device( - AllowedBluetoothDevice { + self.global() + .as_window() + .bluetooth_extra_permission_data() + .add_new_allowed_device(AllowedBluetoothDevice { deviceId: DOMString::from(device.id), mayUseGATT: true, - } - ); + }); // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-requestdevice // Step 5. promise.resolve_native(&bt_device); @@ -544,7 +601,7 @@ impl AsyncBluetoothListener for Bluetooth { // Step 2 - 3. BluetoothResponse::GetAvailability(is_available) => { promise.resolve_native(&is_available); - } + }, _ => promise.reject_error(Error::Type("Something went wrong...".to_owned())), } } @@ -555,11 +612,14 @@ impl PermissionAlgorithm for Bluetooth { type Status = BluetoothPermissionResult; #[allow(unsafe_code)] - fn create_descriptor(cx: *mut JSContext, - permission_descriptor_obj: *mut JSObject) - -> Result<BluetoothPermissionDescriptor, Error> { + fn create_descriptor( + cx: *mut JSContext, + permission_descriptor_obj: *mut JSObject, + ) -> Result<BluetoothPermissionDescriptor, Error> { rooted!(in(cx) let mut property = UndefinedValue()); - property.handle_mut().set(ObjectValue(permission_descriptor_obj)); + property + .handle_mut() + .set(ObjectValue(permission_descriptor_obj)); unsafe { match BluetoothPermissionDescriptor::new(cx, property.handle()) { Ok(ConversionResult::Success(descriptor)) => Ok(descriptor), @@ -592,7 +652,10 @@ impl PermissionAlgorithm for Bluetooth { // Step 5. let global = status.global(); - let allowed_devices = global.as_window().bluetooth_extra_permission_data().get_allowed_devices(); + let allowed_devices = global + .as_window() + .bluetooth_extra_permission_data() + .get_allowed_devices(); let bluetooth = status.get_bluetooth(); let device_map = bluetooth.get_device_map().borrow(); @@ -622,11 +685,15 @@ impl PermissionAlgorithm for Bluetooth { // Step 6.2.2. // Instead of creating an internal slot we send an ipc message to the Bluetooth thread // to check if one of the filters matches. - let (sender, receiver) = ProfiledIpc::channel(global.time_profiler_chan().clone()).unwrap(); - status.get_bluetooth_thread() - .send(BluetoothRequest::MatchesFilter(device_id.clone(), - BluetoothScanfilterSequence::new(scan_filters), - sender)).unwrap(); + let (sender, receiver) = + ProfiledIpc::channel(global.time_profiler_chan().clone()).unwrap(); + status + .get_bluetooth_thread() + .send(BluetoothRequest::MatchesFilter( + device_id.clone(), + BluetoothScanfilterSequence::new(scan_filters), + sender, + )).unwrap(); match receiver.recv().unwrap() { Ok(true) => (), @@ -666,17 +733,28 @@ impl PermissionAlgorithm for Bluetooth { // Step 2. let sender = response_async(promise, status); let bluetooth = status.get_bluetooth(); - bluetooth.request_bluetooth_devices(promise, &descriptor.filters, &descriptor.optionalServices, sender); + bluetooth.request_bluetooth_devices( + promise, + &descriptor.filters, + &descriptor.optionalServices, + sender, + ); // NOTE: Step 3. is in BluetoothPermissionResult's `handle_response` function. } #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#revoke-bluetooth-access - fn permission_revoke(_descriptor: &BluetoothPermissionDescriptor, status: &BluetoothPermissionResult) { + fn permission_revoke( + _descriptor: &BluetoothPermissionDescriptor, + status: &BluetoothPermissionResult, + ) { // Step 1. let global = status.global(); - let allowed_devices = global.as_window().bluetooth_extra_permission_data().get_allowed_devices(); + let allowed_devices = global + .as_window() + .bluetooth_extra_permission_data() + .get_allowed_devices(); // Step 2. let bluetooth = status.get_bluetooth(); let device_map = bluetooth.get_device_map().borrow(); @@ -684,7 +762,8 @@ impl PermissionAlgorithm for Bluetooth { let id = DOMString::from(id.clone()); // Step 2.1. if allowed_devices.iter().any(|d| d.deviceId == id) && - !device.is_represented_device_null() { + !device.is_represented_device_null() + { // Note: We don't need to update the allowed_services, // because we store it in the lower level // where it is already up-to-date diff --git a/components/script/dom/bluetoothadvertisingevent.rs b/components/script/dom/bluetoothadvertisingevent.rs index 452c43eac98..2dffb0a4dfc 100644 --- a/components/script/dom/bluetoothadvertisingevent.rs +++ b/components/script/dom/bluetoothadvertisingevent.rs @@ -29,12 +29,13 @@ pub struct BluetoothAdvertisingEvent { } impl BluetoothAdvertisingEvent { - pub fn new_inherited(device: &BluetoothDevice, - name: Option<DOMString>, - appearance: Option<u16>, - tx_power: Option<i8>, - rssi: Option<i8>) - -> BluetoothAdvertisingEvent { + pub fn new_inherited( + device: &BluetoothDevice, + name: Option<DOMString>, + appearance: Option<u16>, + tx_power: Option<i8>, + rssi: Option<i8>, + ) -> BluetoothAdvertisingEvent { BluetoothAdvertisingEvent { event: Event::new_inherited(), device: Dom::from_ref(device), @@ -45,26 +46,23 @@ impl BluetoothAdvertisingEvent { } } - pub fn new(global: &GlobalScope, - type_: Atom, - bubbles: EventBubbles, - cancelable: EventCancelable, - device: &BluetoothDevice, - name: Option<DOMString>, - appearance: Option<u16>, - txPower: Option<i8>, - rssi: Option<i8>) - -> DomRoot<BluetoothAdvertisingEvent> { + pub fn new( + global: &GlobalScope, + type_: Atom, + bubbles: EventBubbles, + cancelable: EventCancelable, + device: &BluetoothDevice, + name: Option<DOMString>, + appearance: Option<u16>, + txPower: Option<i8>, + rssi: Option<i8>, + ) -> DomRoot<BluetoothAdvertisingEvent> { let ev = reflect_dom_object( Box::new(BluetoothAdvertisingEvent::new_inherited( - device, - name, - appearance, - txPower, - rssi + device, name, appearance, txPower, rssi, )), global, - BluetoothAdvertisingEventBinding::Wrap + BluetoothAdvertisingEventBinding::Wrap, ); { let event = ev.upcast::<Event>(); @@ -74,10 +72,11 @@ impl BluetoothAdvertisingEvent { } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothadvertisingevent-bluetoothadvertisingevent - pub fn Constructor(window: &Window, - type_: DOMString, - init: &BluetoothAdvertisingEventInit) - -> Fallible<DomRoot<BluetoothAdvertisingEvent>> { + pub fn Constructor( + window: &Window, + type_: DOMString, + init: &BluetoothAdvertisingEventInit, + ) -> Fallible<DomRoot<BluetoothAdvertisingEvent>> { let global = window.upcast::<GlobalScope>(); let device = init.device.r(); let name = init.name.clone(); @@ -86,15 +85,17 @@ impl BluetoothAdvertisingEvent { let rssi = init.rssi.clone(); let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::from(init.parent.cancelable); - Ok(BluetoothAdvertisingEvent::new(global, - Atom::from(type_), - bubbles, - cancelable, - device, - name, - appearance, - txPower, - rssi)) + Ok(BluetoothAdvertisingEvent::new( + global, + Atom::from(type_), + bubbles, + cancelable, + device, + name, + appearance, + txPower, + rssi, + )) } } diff --git a/components/script/dom/bluetoothcharacteristicproperties.rs b/components/script/dom/bluetoothcharacteristicproperties.rs index 4a0b6029224..900ec257c7d 100644 --- a/components/script/dom/bluetoothcharacteristicproperties.rs +++ b/components/script/dom/bluetoothcharacteristicproperties.rs @@ -4,14 +4,14 @@ use dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding; use dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding:: - BluetoothCharacteristicPropertiesMethods; +BluetoothCharacteristicPropertiesMethods; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; // https://webbluetoothcg.github.io/web-bluetooth/#characteristicproperties - #[dom_struct] +#[dom_struct] pub struct BluetoothCharacteristicProperties { reflector_: Reflector, broadcast: bool, @@ -26,16 +26,17 @@ pub struct BluetoothCharacteristicProperties { } impl BluetoothCharacteristicProperties { - pub fn new_inherited(broadcast: bool, - read: bool, - write_without_response: bool, - write: bool, - notify: bool, - indicate: bool, - authenticated_signed_writes: bool, - reliable_write: bool, - writable_auxiliaries: bool) - -> BluetoothCharacteristicProperties { + pub fn new_inherited( + broadcast: bool, + read: bool, + write_without_response: bool, + write: bool, + notify: bool, + indicate: bool, + authenticated_signed_writes: bool, + reliable_write: bool, + writable_auxiliaries: bool, + ) -> BluetoothCharacteristicProperties { BluetoothCharacteristicProperties { reflector_: Reflector::new(), broadcast: broadcast, @@ -50,17 +51,18 @@ impl BluetoothCharacteristicProperties { } } - pub fn new(global: &GlobalScope, - broadcast: bool, - read: bool, - writeWithoutResponse: bool, - write: bool, - notify: bool, - indicate: bool, - authenticatedSignedWrites: bool, - reliableWrite: bool, - writableAuxiliaries: bool) - -> DomRoot<BluetoothCharacteristicProperties> { + pub fn new( + global: &GlobalScope, + broadcast: bool, + read: bool, + writeWithoutResponse: bool, + write: bool, + notify: bool, + indicate: bool, + authenticatedSignedWrites: bool, + reliableWrite: bool, + writableAuxiliaries: bool, + ) -> DomRoot<BluetoothCharacteristicProperties> { reflect_dom_object( Box::new(BluetoothCharacteristicProperties::new_inherited( broadcast, @@ -71,10 +73,10 @@ impl BluetoothCharacteristicProperties { indicate, authenticatedSignedWrites, reliableWrite, - writableAuxiliaries + writableAuxiliaries, )), global, - BluetoothCharacteristicPropertiesBinding::Wrap + BluetoothCharacteristicPropertiesBinding::Wrap, ) } } diff --git a/components/script/dom/bluetoothdevice.rs b/components/script/dom/bluetoothdevice.rs index b8e08618960..ae97626b60e 100644 --- a/components/script/dom/bluetoothdevice.rs +++ b/components/script/dom/bluetoothdevice.rs @@ -38,118 +38,144 @@ pub struct BluetoothDevice { name: Option<DOMString>, gatt: MutNullableDom<BluetoothRemoteGATTServer>, context: Dom<Bluetooth>, - attribute_instance_map: (DomRefCell<HashMap<String, Dom<BluetoothRemoteGATTService>>>, - DomRefCell<HashMap<String, Dom<BluetoothRemoteGATTCharacteristic>>>, - DomRefCell<HashMap<String, Dom<BluetoothRemoteGATTDescriptor>>>), + attribute_instance_map: ( + DomRefCell<HashMap<String, Dom<BluetoothRemoteGATTService>>>, + DomRefCell<HashMap<String, Dom<BluetoothRemoteGATTCharacteristic>>>, + DomRefCell<HashMap<String, Dom<BluetoothRemoteGATTDescriptor>>>, + ), watching_advertisements: Cell<bool>, } impl BluetoothDevice { - pub fn new_inherited(id: DOMString, - name: Option<DOMString>, - context: &Bluetooth) - -> BluetoothDevice { + pub fn new_inherited( + id: DOMString, + name: Option<DOMString>, + context: &Bluetooth, + ) -> BluetoothDevice { BluetoothDevice { eventtarget: EventTarget::new_inherited(), id: id, name: name, gatt: Default::default(), context: Dom::from_ref(context), - attribute_instance_map: (DomRefCell::new(HashMap::new()), - DomRefCell::new(HashMap::new()), - DomRefCell::new(HashMap::new())), + attribute_instance_map: ( + DomRefCell::new(HashMap::new()), + DomRefCell::new(HashMap::new()), + DomRefCell::new(HashMap::new()), + ), watching_advertisements: Cell::new(false), } } - pub fn new(global: &GlobalScope, - id: DOMString, - name: Option<DOMString>, - context: &Bluetooth) - -> DomRoot<BluetoothDevice> { - reflect_dom_object(Box::new(BluetoothDevice::new_inherited(id, name, context)), - global, - BluetoothDeviceBinding::Wrap) + pub fn new( + global: &GlobalScope, + id: DOMString, + name: Option<DOMString>, + context: &Bluetooth, + ) -> DomRoot<BluetoothDevice> { + reflect_dom_object( + Box::new(BluetoothDevice::new_inherited(id, name, context)), + global, + BluetoothDeviceBinding::Wrap, + ) } pub fn get_gatt(&self) -> DomRoot<BluetoothRemoteGATTServer> { - self.gatt.or_init(|| { - BluetoothRemoteGATTServer::new(&self.global(), self) - }) + self.gatt + .or_init(|| BluetoothRemoteGATTServer::new(&self.global(), self)) } fn get_context(&self) -> DomRoot<Bluetooth> { DomRoot::from_ref(&self.context) } - pub fn get_or_create_service(&self, - service: &BluetoothServiceMsg, - server: &BluetoothRemoteGATTServer) - -> DomRoot<BluetoothRemoteGATTService> { + pub fn get_or_create_service( + &self, + service: &BluetoothServiceMsg, + server: &BluetoothRemoteGATTServer, + ) -> DomRoot<BluetoothRemoteGATTService> { let (ref service_map_ref, _, _) = self.attribute_instance_map; let mut service_map = service_map_ref.borrow_mut(); if let Some(existing_service) = service_map.get(&service.instance_id) { return DomRoot::from_ref(&existing_service); } - let bt_service = BluetoothRemoteGATTService::new(&server.global(), - &server.Device(), - DOMString::from(service.uuid.clone()), - service.is_primary, - service.instance_id.clone()); + let bt_service = BluetoothRemoteGATTService::new( + &server.global(), + &server.Device(), + DOMString::from(service.uuid.clone()), + service.is_primary, + service.instance_id.clone(), + ); service_map.insert(service.instance_id.clone(), Dom::from_ref(&bt_service)); return bt_service; } - pub fn get_or_create_characteristic(&self, - characteristic: &BluetoothCharacteristicMsg, - service: &BluetoothRemoteGATTService) - -> DomRoot<BluetoothRemoteGATTCharacteristic> { + pub fn get_or_create_characteristic( + &self, + characteristic: &BluetoothCharacteristicMsg, + service: &BluetoothRemoteGATTService, + ) -> DomRoot<BluetoothRemoteGATTCharacteristic> { let (_, ref characteristic_map_ref, _) = self.attribute_instance_map; let mut characteristic_map = characteristic_map_ref.borrow_mut(); if let Some(existing_characteristic) = characteristic_map.get(&characteristic.instance_id) { return DomRoot::from_ref(&existing_characteristic); } - let properties = - BluetoothCharacteristicProperties::new(&service.global(), - characteristic.broadcast, - characteristic.read, - characteristic.write_without_response, - characteristic.write, - characteristic.notify, - characteristic.indicate, - characteristic.authenticated_signed_writes, - characteristic.reliable_write, - characteristic.writable_auxiliaries); - let bt_characteristic = BluetoothRemoteGATTCharacteristic::new(&service.global(), - service, - DOMString::from(characteristic.uuid.clone()), - &properties, - characteristic.instance_id.clone()); - characteristic_map.insert(characteristic.instance_id.clone(), Dom::from_ref(&bt_characteristic)); + let properties = BluetoothCharacteristicProperties::new( + &service.global(), + characteristic.broadcast, + characteristic.read, + characteristic.write_without_response, + characteristic.write, + characteristic.notify, + characteristic.indicate, + characteristic.authenticated_signed_writes, + characteristic.reliable_write, + characteristic.writable_auxiliaries, + ); + let bt_characteristic = BluetoothRemoteGATTCharacteristic::new( + &service.global(), + service, + DOMString::from(characteristic.uuid.clone()), + &properties, + characteristic.instance_id.clone(), + ); + characteristic_map.insert( + characteristic.instance_id.clone(), + Dom::from_ref(&bt_characteristic), + ); return bt_characteristic; } pub fn is_represented_device_null(&self) -> bool { let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); - self.get_bluetooth_thread().send( - BluetoothRequest::IsRepresentedDeviceNull(self.Id().to_string(), sender)).unwrap(); + self.get_bluetooth_thread() + .send(BluetoothRequest::IsRepresentedDeviceNull( + self.Id().to_string(), + sender, + )).unwrap(); receiver.recv().unwrap() } - pub fn get_or_create_descriptor(&self, - descriptor: &BluetoothDescriptorMsg, - characteristic: &BluetoothRemoteGATTCharacteristic) - -> DomRoot<BluetoothRemoteGATTDescriptor> { + pub fn get_or_create_descriptor( + &self, + descriptor: &BluetoothDescriptorMsg, + characteristic: &BluetoothRemoteGATTCharacteristic, + ) -> DomRoot<BluetoothRemoteGATTDescriptor> { let (_, _, ref descriptor_map_ref) = self.attribute_instance_map; let mut descriptor_map = descriptor_map_ref.borrow_mut(); if let Some(existing_descriptor) = descriptor_map.get(&descriptor.instance_id) { return DomRoot::from_ref(&existing_descriptor); } - let bt_descriptor = BluetoothRemoteGATTDescriptor::new(&characteristic.global(), - characteristic, - DOMString::from(descriptor.uuid.clone()), - descriptor.instance_id.clone()); - descriptor_map.insert(descriptor.instance_id.clone(), Dom::from_ref(&bt_descriptor)); + let bt_descriptor = BluetoothRemoteGATTDescriptor::new( + &characteristic.global(), + characteristic, + DOMString::from(descriptor.uuid.clone()), + descriptor.instance_id.clone(), + ); + descriptor_map.insert( + descriptor.instance_id.clone(), + Dom::from_ref(&bt_descriptor), + ); return bt_descriptor; } @@ -180,11 +206,17 @@ impl BluetoothDevice { // Step 5, 6.4, 7. // TODO: Step 6: Implement `active notification context set` for BluetoothRemoteGATTCharacteristic. - let _ = self.get_bluetooth_thread().send( - BluetoothRequest::SetRepresentedToNull(service_ids, characteristic_ids, descriptor_ids)); + let _ = self + .get_bluetooth_thread() + .send(BluetoothRequest::SetRepresentedToNull( + service_ids, + characteristic_ids, + descriptor_ids, + )); // Step 8. - self.upcast::<EventTarget>().fire_bubbling_event(atom!("gattserverdisconnected")); + self.upcast::<EventTarget>() + .fire_bubbling_event(atom!("gattserverdisconnected")); } // https://webbluetoothcg.github.io/web-bluetooth/#garbage-collect-the-connection @@ -206,14 +238,17 @@ impl BluetoothDevice { // Step 3. let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); - self.get_bluetooth_thread().send( - BluetoothRequest::GATTServerDisconnect(String::from(self.Id()), sender)).unwrap(); + self.get_bluetooth_thread() + .send(BluetoothRequest::GATTServerDisconnect( + String::from(self.Id()), + sender, + )).unwrap(); receiver.recv().unwrap().map_err(Error::from) } } impl BluetoothDeviceMethods for BluetoothDevice { - // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-id + // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-id fn Id(&self) -> DOMString { self.id.clone() } @@ -226,9 +261,14 @@ impl BluetoothDeviceMethods for BluetoothDevice { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-gatt fn GetGatt(&self) -> Option<DomRoot<BluetoothRemoteGATTServer>> { // Step 1. - if self.global().as_window().bluetooth_extra_permission_data() - .allowed_devices_contains_id(self.id.clone()) && !self.is_represented_device_null() { - return Some(self.get_gatt()) + if self + .global() + .as_window() + .bluetooth_extra_permission_data() + .allowed_devices_contains_id(self.id.clone()) && + !self.is_represented_device_null() + { + return Some(self.get_gatt()); } // Step 2. None @@ -242,8 +282,11 @@ impl BluetoothDeviceMethods for BluetoothDevice { // TODO: Step 1. // Note: Steps 2 - 3 are implemented in components/bluetooth/lib.rs in watch_advertisements function // and in handle_response function. - self.get_bluetooth_thread().send( - BluetoothRequest::WatchAdvertisements(String::from(self.Id()), sender)).unwrap(); + self.get_bluetooth_thread() + .send(BluetoothRequest::WatchAdvertisements( + String::from(self.Id()), + sender, + )).unwrap(); return p; } @@ -260,7 +303,11 @@ impl BluetoothDeviceMethods for BluetoothDevice { } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdeviceeventhandlers-ongattserverdisconnected - event_handler!(gattserverdisconnected, GetOngattserverdisconnected, SetOngattserverdisconnected); + event_handler!( + gattserverdisconnected, + GetOngattserverdisconnected, + SetOngattserverdisconnected + ); } impl AsyncBluetoothListener for BluetoothDevice { diff --git a/components/script/dom/bluetoothpermissionresult.rs b/components/script/dom/bluetoothpermissionresult.rs index 047325c5ed3..a9208ed8cb2 100644 --- a/components/script/dom/bluetoothpermissionresult.rs +++ b/components/script/dom/bluetoothpermissionresult.rs @@ -40,10 +40,15 @@ impl BluetoothPermissionResult { result } - pub fn new(global: &GlobalScope, status: &PermissionStatus) -> DomRoot<BluetoothPermissionResult> { - reflect_dom_object(Box::new(BluetoothPermissionResult::new_inherited(status)), - global, - BluetoothPermissionResultBinding::Wrap) + pub fn new( + global: &GlobalScope, + status: &PermissionStatus, + ) -> DomRoot<BluetoothPermissionResult> { + reflect_dom_object( + Box::new(BluetoothPermissionResult::new_inherited(status)), + global, + BluetoothPermissionResultBinding::Wrap, + ) } pub fn get_bluetooth(&self) -> DomRoot<Bluetooth> { @@ -75,8 +80,12 @@ impl BluetoothPermissionResult { impl BluetoothPermissionResultMethods for BluetoothPermissionResult { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothpermissionresult-devices fn Devices(&self) -> Vec<DomRoot<BluetoothDevice>> { - let device_vec: Vec<DomRoot<BluetoothDevice>> = - self.devices.borrow().iter().map(|d| DomRoot::from_ref(&**d)).collect(); + let device_vec: Vec<DomRoot<BluetoothDevice>> = self + .devices + .borrow() + .iter() + .map(|d| DomRoot::from_ref(&**d)) + .collect(); device_vec } } @@ -93,26 +102,29 @@ impl AsyncBluetoothListener for BluetoothPermissionResult { if let Some(ref existing_device) = device_instance_map.get(&device.id) { // https://webbluetoothcg.github.io/web-bluetooth/#request-the-bluetooth-permission // Step 3. - self.set_devices(vec!(Dom::from_ref(&*existing_device))); + self.set_devices(vec![Dom::from_ref(&*existing_device)]); // https://w3c.github.io/permissions/#dom-permissions-request // Step 8. return promise.resolve_native(self); } - let bt_device = BluetoothDevice::new(&self.global(), - DOMString::from(device.id.clone()), - device.name.map(DOMString::from), - &bluetooth); + let bt_device = BluetoothDevice::new( + &self.global(), + DOMString::from(device.id.clone()), + device.name.map(DOMString::from), + &bluetooth, + ); device_instance_map.insert(device.id.clone(), Dom::from_ref(&bt_device)); - self.global().as_window().bluetooth_extra_permission_data().add_new_allowed_device( - AllowedBluetoothDevice { + self.global() + .as_window() + .bluetooth_extra_permission_data() + .add_new_allowed_device(AllowedBluetoothDevice { deviceId: DOMString::from(device.id), mayUseGATT: true, - } - ); + }); // https://webbluetoothcg.github.io/web-bluetooth/#request-the-bluetooth-permission // Step 3. - self.set_devices(vec!(Dom::from_ref(&bt_device))); + self.set_devices(vec![Dom::from_ref(&bt_device)]); // https://w3c.github.io/permissions/#dom-permissions-request // Step 8. diff --git a/components/script/dom/bluetoothremotegattcharacteristic.rs b/components/script/dom/bluetoothremotegattcharacteristic.rs index 8034623ff5c..70cbf23ffd2 100644 --- a/components/script/dom/bluetoothremotegattcharacteristic.rs +++ b/components/script/dom/bluetoothremotegattcharacteristic.rs @@ -6,10 +6,10 @@ use bluetooth_traits::{BluetoothRequest, BluetoothResponse, GATTType}; use bluetooth_traits::blocklist::{Blocklist, uuid_is_blocklisted}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding:: - BluetoothCharacteristicPropertiesMethods; +BluetoothCharacteristicPropertiesMethods; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTCharacteristicBinding; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTCharacteristicBinding:: - BluetoothRemoteGATTCharacteristicMethods; +BluetoothRemoteGATTCharacteristicMethods; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods; use dom::bindings::codegen::UnionTypes::ArrayBufferViewOrArrayBuffer; @@ -45,11 +45,12 @@ pub struct BluetoothRemoteGATTCharacteristic { } impl BluetoothRemoteGATTCharacteristic { - pub fn new_inherited(service: &BluetoothRemoteGATTService, - uuid: DOMString, - properties: &BluetoothCharacteristicProperties, - instance_id: String) - -> BluetoothRemoteGATTCharacteristic { + pub fn new_inherited( + service: &BluetoothRemoteGATTService, + uuid: DOMString, + properties: &BluetoothCharacteristicProperties, + instance_id: String, + ) -> BluetoothRemoteGATTCharacteristic { BluetoothRemoteGATTCharacteristic { eventtarget: EventTarget::new_inherited(), service: Dom::from_ref(service), @@ -60,18 +61,19 @@ impl BluetoothRemoteGATTCharacteristic { } } - pub fn new(global: &GlobalScope, - service: &BluetoothRemoteGATTService, - uuid: DOMString, - properties: &BluetoothCharacteristicProperties, - instanceID: String) - -> DomRoot<BluetoothRemoteGATTCharacteristic> { + pub fn new( + global: &GlobalScope, + service: &BluetoothRemoteGATTService, + uuid: DOMString, + properties: &BluetoothCharacteristicProperties, + instanceID: String, + ) -> DomRoot<BluetoothRemoteGATTCharacteristic> { reflect_dom_object( Box::new(BluetoothRemoteGATTCharacteristic::new_inherited( - service, uuid, properties, instanceID + service, uuid, properties, instanceID, )), global, - BluetoothRemoteGATTCharacteristicBinding::Wrap + BluetoothRemoteGATTCharacteristicBinding::Wrap, ) } @@ -103,17 +105,29 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-getdescriptor fn GetDescriptor(&self, descriptor: BluetoothDescriptorUUID) -> Rc<Promise> { - get_gatt_children(self, true, BluetoothUUID::descriptor, Some(descriptor), self.get_instance_id(), - self.Service().Device().get_gatt().Connected(), GATTType::Descriptor) + get_gatt_children( + self, + true, + BluetoothUUID::descriptor, + Some(descriptor), + self.get_instance_id(), + self.Service().Device().get_gatt().Connected(), + GATTType::Descriptor, + ) } #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-getdescriptors - fn GetDescriptors(&self, - descriptor: Option<BluetoothDescriptorUUID>) - -> Rc<Promise> { - get_gatt_children(self, false, BluetoothUUID::descriptor, descriptor, self.get_instance_id(), - self.Service().Device().get_gatt().Connected(), GATTType::Descriptor) + fn GetDescriptors(&self, descriptor: Option<BluetoothDescriptorUUID>) -> Rc<Promise> { + get_gatt_children( + self, + false, + BluetoothUUID::descriptor, + descriptor, + self.get_instance_id(), + self.Service().Device().get_gatt().Connected(), + GATTType::Descriptor, + ) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-value @@ -149,8 +163,9 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris // Note: Steps 3 - 4 and the remaining substeps of Step 5 are implemented in components/bluetooth/lib.rs // in readValue function and in handle_response function. let sender = response_async(&p, self); - self.get_bluetooth_thread().send( - BluetoothRequest::ReadValue(self.get_instance_id(), sender)).unwrap(); + self.get_bluetooth_thread() + .send(BluetoothRequest::ReadValue(self.get_instance_id(), sender)) + .unwrap(); return p; } @@ -186,8 +201,9 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris // Step 7.1. if !(self.Properties().Write() || - self.Properties().WriteWithoutResponse() || - self.Properties().AuthenticatedSignedWrites()) { + self.Properties().WriteWithoutResponse() || + self.Properties().AuthenticatedSignedWrites()) + { p.reject_error(NotSupported); return p; } @@ -195,8 +211,12 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris // Note: Steps 5 - 6 and the remaining substeps of Step 7 are implemented in components/bluetooth/lib.rs // in writeValue function and in handle_response function. let sender = response_async(&p, self); - self.get_bluetooth_thread().send( - BluetoothRequest::WriteValue(self.get_instance_id(), vec, sender)).unwrap(); + self.get_bluetooth_thread() + .send(BluetoothRequest::WriteValue( + self.get_instance_id(), + vec, + sender, + )).unwrap(); return p; } @@ -218,8 +238,7 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris } // Step 5. - if !(self.Properties().Notify() || - self.Properties().Indicate()) { + if !(self.Properties().Notify() || self.Properties().Indicate()) { p.reject_error(NotSupported); return p; } @@ -229,10 +248,12 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris // Note: Steps 3 - 4, 7 - 11 are implemented in components/bluetooth/lib.rs in enable_notification function // and in handle_response function. let sender = response_async(&p, self); - self.get_bluetooth_thread().send( - BluetoothRequest::EnableNotification(self.get_instance_id(), - true, - sender)).unwrap(); + self.get_bluetooth_thread() + .send(BluetoothRequest::EnableNotification( + self.get_instance_id(), + true, + sender, + )).unwrap(); return p; } @@ -246,15 +267,21 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris // Note: Steps 1 - 2, and part of Step 4 and Step 5 are implemented in components/bluetooth/lib.rs // in enable_notification function and in handle_response function. - self.get_bluetooth_thread().send( - BluetoothRequest::EnableNotification(self.get_instance_id(), - false, - sender)).unwrap(); + self.get_bluetooth_thread() + .send(BluetoothRequest::EnableNotification( + self.get_instance_id(), + false, + sender, + )).unwrap(); return p; } // https://webbluetoothcg.github.io/web-bluetooth/#dom-characteristiceventhandlers-oncharacteristicvaluechanged - event_handler!(characteristicvaluechanged, GetOncharacteristicvaluechanged, SetOncharacteristicvaluechanged); + event_handler!( + characteristicvaluechanged, + GetOncharacteristicvaluechanged, + SetOncharacteristicvaluechanged + ); } impl AsyncBluetoothListener for BluetoothRemoteGATTCharacteristic { @@ -265,10 +292,12 @@ impl AsyncBluetoothListener for BluetoothRemoteGATTCharacteristic { // Step 7. BluetoothResponse::GetDescriptors(descriptors_vec, single) => { if single { - promise.resolve_native(&device.get_or_create_descriptor(&descriptors_vec[0], &self)); + promise.resolve_native( + &device.get_or_create_descriptor(&descriptors_vec[0], &self), + ); return; } - let mut descriptors = vec!(); + let mut descriptors = vec![]; for descriptor in descriptors_vec { let bt_descriptor = device.get_or_create_descriptor(&descriptor, &self); descriptors.push(bt_descriptor); @@ -285,7 +314,8 @@ impl AsyncBluetoothListener for BluetoothRemoteGATTCharacteristic { *self.value.borrow_mut() = Some(value.clone()); // Step 5.5.3. - self.upcast::<EventTarget>().fire_bubbling_event(atom!("characteristicvaluechanged")); + self.upcast::<EventTarget>() + .fire_bubbling_event(atom!("characteristicvaluechanged")); // Step 5.5.4. promise.resolve_native(&value); diff --git a/components/script/dom/bluetoothremotegattdescriptor.rs b/components/script/dom/bluetoothremotegattdescriptor.rs index 493550ee91b..b0eb6476fe3 100644 --- a/components/script/dom/bluetoothremotegattdescriptor.rs +++ b/components/script/dom/bluetoothremotegattdescriptor.rs @@ -6,7 +6,7 @@ use bluetooth_traits::{BluetoothRequest, BluetoothResponse}; use bluetooth_traits::blocklist::{Blocklist, uuid_is_blocklisted}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTCharacteristicBinding:: - BluetoothRemoteGATTCharacteristicMethods; +BluetoothRemoteGATTCharacteristicMethods; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTDescriptorBinding; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTDescriptorBinding::BluetoothRemoteGATTDescriptorMethods; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; @@ -35,10 +35,11 @@ pub struct BluetoothRemoteGATTDescriptor { } impl BluetoothRemoteGATTDescriptor { - pub fn new_inherited(characteristic: &BluetoothRemoteGATTCharacteristic, - uuid: DOMString, - instance_id: String) - -> BluetoothRemoteGATTDescriptor { + pub fn new_inherited( + characteristic: &BluetoothRemoteGATTCharacteristic, + uuid: DOMString, + instance_id: String, + ) -> BluetoothRemoteGATTDescriptor { BluetoothRemoteGATTDescriptor { reflector_: Reflector::new(), characteristic: Dom::from_ref(characteristic), @@ -48,17 +49,20 @@ impl BluetoothRemoteGATTDescriptor { } } - pub fn new(global: &GlobalScope, - characteristic: &BluetoothRemoteGATTCharacteristic, - uuid: DOMString, - instanceID: String) - -> DomRoot<BluetoothRemoteGATTDescriptor>{ + pub fn new( + global: &GlobalScope, + characteristic: &BluetoothRemoteGATTCharacteristic, + uuid: DOMString, + instanceID: String, + ) -> DomRoot<BluetoothRemoteGATTDescriptor> { reflect_dom_object( Box::new(BluetoothRemoteGATTDescriptor::new_inherited( - characteristic, uuid, instanceID + characteristic, + uuid, + instanceID, )), global, - BluetoothRemoteGATTDescriptorBinding::Wrap + BluetoothRemoteGATTDescriptorBinding::Wrap, ) } @@ -74,7 +78,7 @@ impl BluetoothRemoteGATTDescriptor { impl BluetoothRemoteGATTDescriptorMethods for BluetoothRemoteGATTDescriptor { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattdescriptor-characteristic fn Characteristic(&self) -> DomRoot<BluetoothRemoteGATTCharacteristic> { - DomRoot::from_ref(&self.characteristic) + DomRoot::from_ref(&self.characteristic) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattdescriptor-uuid @@ -82,7 +86,7 @@ impl BluetoothRemoteGATTDescriptorMethods for BluetoothRemoteGATTDescriptor { self.uuid.clone() } - // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattdescriptor-value + // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattdescriptor-value fn GetValue(&self) -> Option<ByteString> { self.value.borrow().clone() } @@ -99,7 +103,13 @@ impl BluetoothRemoteGATTDescriptorMethods for BluetoothRemoteGATTDescriptor { } // Step 2. - if !self.Characteristic().Service().Device().get_gatt().Connected() { + if !self + .Characteristic() + .Service() + .Device() + .get_gatt() + .Connected() + { p.reject_error(Network); return p; } @@ -108,8 +118,9 @@ impl BluetoothRemoteGATTDescriptorMethods for BluetoothRemoteGATTDescriptor { // Note: Steps 3 - 4 and substeps of Step 5 are implemented in components/bluetooth/lib.rs // in readValue function and in handle_response function. let sender = response_async(&p, self); - self.get_bluetooth_thread().send( - BluetoothRequest::ReadValue(self.get_instance_id(), sender)).unwrap(); + self.get_bluetooth_thread() + .send(BluetoothRequest::ReadValue(self.get_instance_id(), sender)) + .unwrap(); return p; } @@ -135,7 +146,13 @@ impl BluetoothRemoteGATTDescriptorMethods for BluetoothRemoteGATTDescriptor { } // Step 4. - if !self.Characteristic().Service().Device().get_gatt().Connected() { + if !self + .Characteristic() + .Service() + .Device() + .get_gatt() + .Connected() + { p.reject_error(Network); return p; } @@ -144,8 +161,12 @@ impl BluetoothRemoteGATTDescriptorMethods for BluetoothRemoteGATTDescriptor { // Note: Steps 5 - 6 and substeps of Step 7 are implemented in components/bluetooth/lib.rs // in writeValue function and in handle_response function. let sender = response_async(&p, self); - self.get_bluetooth_thread().send( - BluetoothRequest::WriteValue(self.get_instance_id(), vec, sender)).unwrap(); + self.get_bluetooth_thread() + .send(BluetoothRequest::WriteValue( + self.get_instance_id(), + vec, + sender, + )).unwrap(); return p; } } diff --git a/components/script/dom/bluetoothremotegattserver.rs b/components/script/dom/bluetoothremotegattserver.rs index 2c2fb3da351..3d4e5125b3e 100644 --- a/components/script/dom/bluetoothremotegattserver.rs +++ b/components/script/dom/bluetoothremotegattserver.rs @@ -37,10 +37,15 @@ impl BluetoothRemoteGATTServer { } } - pub fn new(global: &GlobalScope, device: &BluetoothDevice) -> DomRoot<BluetoothRemoteGATTServer> { - reflect_dom_object(Box::new(BluetoothRemoteGATTServer::new_inherited(device)), - global, - BluetoothRemoteGATTServerBinding::Wrap) + pub fn new( + global: &GlobalScope, + device: &BluetoothDevice, + ) -> DomRoot<BluetoothRemoteGATTServer> { + reflect_dom_object( + Box::new(BluetoothRemoteGATTServer::new_inherited(device)), + global, + BluetoothRemoteGATTServerBinding::Wrap, + ) } fn get_bluetooth_thread(&self) -> IpcSender<BluetoothRequest> { @@ -78,8 +83,11 @@ impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer { // Note: Steps 2, 5.1.1 and 5.1.3 are in components/bluetooth/lib.rs in the gatt_server_connect function. // Steps 5.2.3 - 5.2.5 are in response function. - self.get_bluetooth_thread().send( - BluetoothRequest::GATTServerConnect(String::from(self.Device().Id()), sender)).unwrap(); + self.get_bluetooth_thread() + .send(BluetoothRequest::GATTServerConnect( + String::from(self.Device().Id()), + sender, + )).unwrap(); // Step 5: return promise. return p; } @@ -90,7 +98,7 @@ impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer { // Step 2. if !self.Connected() { - return Ok(()) + return Ok(()); } // Step 3. @@ -104,17 +112,30 @@ impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-getprimaryservice fn GetPrimaryService(&self, service: BluetoothServiceUUID) -> Rc<Promise> { // Step 1 - 2. - get_gatt_children(self, true, BluetoothUUID::service, Some(service), String::from(self.Device().Id()), - self.Device().get_gatt().Connected(), GATTType::PrimaryService) + get_gatt_children( + self, + true, + BluetoothUUID::service, + Some(service), + String::from(self.Device().Id()), + self.Device().get_gatt().Connected(), + GATTType::PrimaryService, + ) } #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-getprimaryservices fn GetPrimaryServices(&self, service: Option<BluetoothServiceUUID>) -> Rc<Promise> { // Step 1 - 2. - get_gatt_children(self, false, BluetoothUUID::service, service, String::from(self.Device().Id()), - self.Connected(), GATTType::PrimaryService) - + get_gatt_children( + self, + false, + BluetoothUUID::service, + service, + String::from(self.Device().Id()), + self.Connected(), + GATTType::PrimaryService, + ) } } @@ -145,7 +166,7 @@ impl AsyncBluetoothListener for BluetoothRemoteGATTServer { promise.resolve_native(&device.get_or_create_service(&services_vec[0], &self)); return; } - let mut services = vec!(); + let mut services = vec![]; for service in services_vec { let bt_service = device.get_or_create_service(&service, &self); services.push(bt_service); diff --git a/components/script/dom/bluetoothremotegattservice.rs b/components/script/dom/bluetoothremotegattservice.rs index 74568b9a7df..85aa40c874c 100644 --- a/components/script/dom/bluetoothremotegattservice.rs +++ b/components/script/dom/bluetoothremotegattservice.rs @@ -30,11 +30,12 @@ pub struct BluetoothRemoteGATTService { } impl BluetoothRemoteGATTService { - pub fn new_inherited(device: &BluetoothDevice, - uuid: DOMString, - is_primary: bool, - instance_id: String) - -> BluetoothRemoteGATTService { + pub fn new_inherited( + device: &BluetoothDevice, + uuid: DOMString, + is_primary: bool, + instance_id: String, + ) -> BluetoothRemoteGATTService { BluetoothRemoteGATTService { eventtarget: EventTarget::new_inherited(), device: Dom::from_ref(device), @@ -44,18 +45,19 @@ impl BluetoothRemoteGATTService { } } - pub fn new(global: &GlobalScope, - device: &BluetoothDevice, - uuid: DOMString, - isPrimary: bool, - instanceID: String) - -> DomRoot<BluetoothRemoteGATTService> { + pub fn new( + global: &GlobalScope, + device: &BluetoothDevice, + uuid: DOMString, + isPrimary: bool, + instanceID: String, + ) -> DomRoot<BluetoothRemoteGATTService> { reflect_dom_object( Box::new(BluetoothRemoteGATTService::new_inherited( - device, uuid, isPrimary, instanceID + device, uuid, isPrimary, instanceID, )), global, - BluetoothRemoteGATTServiceBinding::Wrap + BluetoothRemoteGATTServiceBinding::Wrap, ) } @@ -82,39 +84,61 @@ impl BluetoothRemoteGATTServiceMethods for BluetoothRemoteGATTService { #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattservice-getcharacteristic - fn GetCharacteristic(&self, - characteristic: BluetoothCharacteristicUUID) - -> Rc<Promise> { - get_gatt_children(self, true, BluetoothUUID::characteristic, Some(characteristic), self.get_instance_id(), - self.Device().get_gatt().Connected(), GATTType::Characteristic) + fn GetCharacteristic(&self, characteristic: BluetoothCharacteristicUUID) -> Rc<Promise> { + get_gatt_children( + self, + true, + BluetoothUUID::characteristic, + Some(characteristic), + self.get_instance_id(), + self.Device().get_gatt().Connected(), + GATTType::Characteristic, + ) } #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattservice-getcharacteristics - fn GetCharacteristics(&self, - characteristic: Option<BluetoothCharacteristicUUID>) - -> Rc<Promise> { - get_gatt_children(self, false, BluetoothUUID::characteristic, characteristic, self.get_instance_id(), - self.Device().get_gatt().Connected(), GATTType::Characteristic) + fn GetCharacteristics( + &self, + characteristic: Option<BluetoothCharacteristicUUID>, + ) -> Rc<Promise> { + get_gatt_children( + self, + false, + BluetoothUUID::characteristic, + characteristic, + self.get_instance_id(), + self.Device().get_gatt().Connected(), + GATTType::Characteristic, + ) } #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattservice-getincludedservice - fn GetIncludedService(&self, - service: BluetoothServiceUUID) - -> Rc<Promise> { - get_gatt_children(self, false, BluetoothUUID::service, Some(service), self.get_instance_id(), - self.Device().get_gatt().Connected(), GATTType::IncludedService) + fn GetIncludedService(&self, service: BluetoothServiceUUID) -> Rc<Promise> { + get_gatt_children( + self, + false, + BluetoothUUID::service, + Some(service), + self.get_instance_id(), + self.Device().get_gatt().Connected(), + GATTType::IncludedService, + ) } - #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattservice-getincludedservices - fn GetIncludedServices(&self, - service: Option<BluetoothServiceUUID>) - -> Rc<Promise> { - get_gatt_children(self, false, BluetoothUUID::service, service, self.get_instance_id(), - self.Device().get_gatt().Connected(), GATTType::IncludedService) + fn GetIncludedServices(&self, service: Option<BluetoothServiceUUID>) -> Rc<Promise> { + get_gatt_children( + self, + false, + BluetoothUUID::service, + service, + self.get_instance_id(), + self.Device().get_gatt().Connected(), + GATTType::IncludedService, + ) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-serviceeventhandlers-onserviceadded @@ -135,12 +159,15 @@ impl AsyncBluetoothListener for BluetoothRemoteGATTService { // Step 7. BluetoothResponse::GetCharacteristics(characteristics_vec, single) => { if single { - promise.resolve_native(&device.get_or_create_characteristic(&characteristics_vec[0], &self)); + promise.resolve_native( + &device.get_or_create_characteristic(&characteristics_vec[0], &self), + ); return; } - let mut characteristics = vec!(); + let mut characteristics = vec![]; for characteristic in characteristics_vec { - let bt_characteristic = device.get_or_create_characteristic(&characteristic, &self); + let bt_characteristic = + device.get_or_create_characteristic(&characteristic, &self); characteristics.push(bt_characteristic); } promise.resolve_native(&characteristics); @@ -149,9 +176,11 @@ impl AsyncBluetoothListener for BluetoothRemoteGATTService { // Step 7. BluetoothResponse::GetIncludedServices(services_vec, single) => { if single { - return promise.resolve_native(&device.get_or_create_service(&services_vec[0], &device.get_gatt())); + return promise.resolve_native( + &device.get_or_create_service(&services_vec[0], &device.get_gatt()), + ); } - let mut services = vec!(); + let mut services = vec![]; for service in services_vec { let bt_service = device.get_or_create_service(&service, &device.get_gatt()); services.push(bt_service); diff --git a/components/script/dom/bluetoothuuid.rs b/components/script/dom/bluetoothuuid.rs index a4ef66568a6..212318650c7 100644 --- a/components/script/dom/bluetoothuuid.rs +++ b/components/script/dom/bluetoothuuid.rs @@ -17,7 +17,7 @@ pub type BluetoothCharacteristicUUID = StringOrUnsignedLong; pub type BluetoothDescriptorUUID = StringOrUnsignedLong; // https://webbluetoothcg.github.io/web-bluetooth/#bluetoothuuid - #[dom_struct] +#[dom_struct] pub struct BluetoothUUID { reflector_: Reflector, } @@ -30,10 +30,16 @@ const BLUETOOTH_ASSIGNED_SERVICES: &'static [(&'static str, u32)] = &[ ("org.bluetooth.service.blood_pressure", 0x1810_u32), ("org.bluetooth.service.body_composition", 0x181b_u32), ("org.bluetooth.service.bond_management", 0x181e_u32), - ("org.bluetooth.service.continuous_glucose_monitoring", 0x181f_u32), + ( + "org.bluetooth.service.continuous_glucose_monitoring", + 0x181f_u32, + ), ("org.bluetooth.service.current_time", 0x1805_u32), ("org.bluetooth.service.cycling_power", 0x1818_u32), - ("org.bluetooth.service.cycling_speed_and_cadence", 0x1816_u32), + ( + "org.bluetooth.service.cycling_speed_and_cadence", + 0x1816_u32, + ), ("org.bluetooth.service.device_information", 0x180a_u32), ("org.bluetooth.service.environmental_sensing", 0x181a_u32), ("org.bluetooth.service.generic_access", 0x1800_u32), @@ -45,7 +51,10 @@ const BLUETOOTH_ASSIGNED_SERVICES: &'static [(&'static str, u32)] = &[ ("org.bluetooth.service.human_interface_device", 0x1812_u32), ("org.bluetooth.service.immediate_alert", 0x1802_u32), ("org.bluetooth.service.indoor_positioning", 0x1821_u32), - ("org.bluetooth.service.internet_protocol_support", 0x1820_u32), + ( + "org.bluetooth.service.internet_protocol_support", + 0x1820_u32, + ), ("org.bluetooth.service.link_loss", 0x1803_u32), ("org.bluetooth.service.location_and_navigation", 0x1819_u32), ("org.bluetooth.service.next_dst_change", 0x1807_u32), @@ -53,7 +62,10 @@ const BLUETOOTH_ASSIGNED_SERVICES: &'static [(&'static str, u32)] = &[ ("org.bluetooth.service.phone_alert_status", 0x180e_u32), ("org.bluetooth.service.pulse_oximeter", 0x1822_u32), ("org.bluetooth.service.reference_time_update", 0x1806_u32), - ("org.bluetooth.service.running_speed_and_cadence", 0x1814_u32), + ( + "org.bluetooth.service.running_speed_and_cadence", + 0x1814_u32, + ), ("org.bluetooth.service.scan_parameters", 0x1813_u32), ("org.bluetooth.service.transport_discovery", 0x1824), ("org.bluetooth.service.tx_power", 0x1804_u32), @@ -63,57 +75,150 @@ const BLUETOOTH_ASSIGNED_SERVICES: &'static [(&'static str, u32)] = &[ //https://developer.bluetooth.org/gatt/services/Pages/ServicesHome.aspx const BLUETOOTH_ASSIGNED_CHARCTERISTICS: &'static [(&'static str, u32)] = &[ - ("org.bluetooth.characteristic.aerobic_heart_rate_lower_limit", 0x2a7e_u32), - ("org.bluetooth.characteristic.aerobic_heart_rate_upper_limit", 0x2a84_u32), + ( + "org.bluetooth.characteristic.aerobic_heart_rate_lower_limit", + 0x2a7e_u32, + ), + ( + "org.bluetooth.characteristic.aerobic_heart_rate_upper_limit", + 0x2a84_u32, + ), ("org.bluetooth.characteristic.aerobic_threshold", 0x2a7f_u32), ("org.bluetooth.characteristic.age", 0x2a80_u32), ("org.bluetooth.characteristic.aggregate", 0x2a5a_u32), ("org.bluetooth.characteristic.alert_category_id", 0x2a43_u32), - ("org.bluetooth.characteristic.alert_category_id_bit_mask", 0x2a42_u32), + ( + "org.bluetooth.characteristic.alert_category_id_bit_mask", + 0x2a42_u32, + ), ("org.bluetooth.characteristic.alert_level", 0x2a06_u32), - ("org.bluetooth.characteristic.alert_notification_control_point", 0x2a44_u32), + ( + "org.bluetooth.characteristic.alert_notification_control_point", + 0x2a44_u32, + ), ("org.bluetooth.characteristic.alert_status", 0x2a3f_u32), ("org.bluetooth.characteristic.altitude", 0x2ab3_u32), - ("org.bluetooth.characteristic.anaerobic_heart_rate_lower_limit", 0x2a81_u32), - ("org.bluetooth.characteristic.anaerobic_heart_rate_upper_limit", 0x2a82_u32), - ("org.bluetooth.characteristic.anaerobic_threshold", 0x2a83_u32), + ( + "org.bluetooth.characteristic.anaerobic_heart_rate_lower_limit", + 0x2a81_u32, + ), + ( + "org.bluetooth.characteristic.anaerobic_heart_rate_upper_limit", + 0x2a82_u32, + ), + ( + "org.bluetooth.characteristic.anaerobic_threshold", + 0x2a83_u32, + ), ("org.bluetooth.characteristic.analog", 0x2a58_u32), - ("org.bluetooth.characteristic.apparent_wind_direction", 0x2a73_u32), - ("org.bluetooth.characteristic.apparent_wind_speed", 0x2a72_u32), + ( + "org.bluetooth.characteristic.apparent_wind_direction", + 0x2a73_u32, + ), + ( + "org.bluetooth.characteristic.apparent_wind_speed", + 0x2a72_u32, + ), ("org.bluetooth.characteristic.gap.appearance", 0x2a01_u32), - ("org.bluetooth.characteristic.barometric_pressure_trend", 0x2aa3_u32), + ( + "org.bluetooth.characteristic.barometric_pressure_trend", + 0x2aa3_u32, + ), ("org.bluetooth.characteristic.battery_level", 0x2a19_u32), - ("org.bluetooth.characteristic.blood_pressure_feature", 0x2a49_u32), - ("org.bluetooth.characteristic.blood_pressure_measurement", 0x2a35_u32), - ("org.bluetooth.characteristic.body_composition_feature", 0x2a9b_u32), - ("org.bluetooth.characteristic.body_composition_measurement", 0x2a9c_u32), - ("org.bluetooth.characteristic.body_sensor_location", 0x2a38_u32), - ("org.bluetooth.characteristic.bond_management_control_point", 0x2aa4_u32), - ("org.bluetooth.characteristic.bond_management_feature", 0x2aa5_u32), - ("org.bluetooth.characteristic.boot_keyboard_input_report", 0x2a22_u32), - ("org.bluetooth.characteristic.boot_keyboard_output_report", 0x2a32_u32), - ("org.bluetooth.characteristic.boot_mouse_input_report", 0x2a33_u32), - ("org.bluetooth.characteristic.gap.central_address_resolution_support", 0x2aa6_u32), + ( + "org.bluetooth.characteristic.blood_pressure_feature", + 0x2a49_u32, + ), + ( + "org.bluetooth.characteristic.blood_pressure_measurement", + 0x2a35_u32, + ), + ( + "org.bluetooth.characteristic.body_composition_feature", + 0x2a9b_u32, + ), + ( + "org.bluetooth.characteristic.body_composition_measurement", + 0x2a9c_u32, + ), + ( + "org.bluetooth.characteristic.body_sensor_location", + 0x2a38_u32, + ), + ( + "org.bluetooth.characteristic.bond_management_control_point", + 0x2aa4_u32, + ), + ( + "org.bluetooth.characteristic.bond_management_feature", + 0x2aa5_u32, + ), + ( + "org.bluetooth.characteristic.boot_keyboard_input_report", + 0x2a22_u32, + ), + ( + "org.bluetooth.characteristic.boot_keyboard_output_report", + 0x2a32_u32, + ), + ( + "org.bluetooth.characteristic.boot_mouse_input_report", + 0x2a33_u32, + ), + ( + "org.bluetooth.characteristic.gap.central_address_resolution_support", + 0x2aa6_u32, + ), ("org.bluetooth.characteristic.cgm_feature", 0x2aa8_u32), ("org.bluetooth.characteristic.cgm_measurement", 0x2aa7_u32), - ("org.bluetooth.characteristic.cgm_session_run_time", 0x2aab_u32), - ("org.bluetooth.characteristic.cgm_session_start_time", 0x2aaa_u32), - ("org.bluetooth.characteristic.cgm_specific_ops_control_point", 0x2aac_u32), + ( + "org.bluetooth.characteristic.cgm_session_run_time", + 0x2aab_u32, + ), + ( + "org.bluetooth.characteristic.cgm_session_start_time", + 0x2aaa_u32, + ), + ( + "org.bluetooth.characteristic.cgm_specific_ops_control_point", + 0x2aac_u32, + ), ("org.bluetooth.characteristic.cgm_status", 0x2aa9_u32), ("org.bluetooth.characteristic.csc_feature", 0x2a5c_u32), ("org.bluetooth.characteristic.csc_measurement", 0x2a5b_u32), ("org.bluetooth.characteristic.current_time", 0x2a2b_u32), - ("org.bluetooth.characteristic.cycling_power_control_point", 0x2a66_u32), - ("org.bluetooth.characteristic.cycling_power_feature", 0x2a65_u32), - ("org.bluetooth.characteristic.cycling_power_measurement", 0x2a63_u32), - ("org.bluetooth.characteristic.cycling_power_vector", 0x2a64_u32), - ("org.bluetooth.characteristic.database_change_increment", 0x2a99_u32), + ( + "org.bluetooth.characteristic.cycling_power_control_point", + 0x2a66_u32, + ), + ( + "org.bluetooth.characteristic.cycling_power_feature", + 0x2a65_u32, + ), + ( + "org.bluetooth.characteristic.cycling_power_measurement", + 0x2a63_u32, + ), + ( + "org.bluetooth.characteristic.cycling_power_vector", + 0x2a64_u32, + ), + ( + "org.bluetooth.characteristic.database_change_increment", + 0x2a99_u32, + ), ("org.bluetooth.characteristic.date_of_birth", 0x2a85_u32), - ("org.bluetooth.characteristic.date_of_threshold_assessment", 0x2a86_u32), + ( + "org.bluetooth.characteristic.date_of_threshold_assessment", + 0x2a86_u32, + ), ("org.bluetooth.characteristic.date_time", 0x2a08_u32), ("org.bluetooth.characteristic.day_date_time", 0x2a0a_u32), ("org.bluetooth.characteristic.day_of_week", 0x2a09_u32), - ("org.bluetooth.characteristic.descriptor_value_changed", 0x2a7d_u32), + ( + "org.bluetooth.characteristic.descriptor_value_changed", + 0x2a7d_u32, + ), ("org.bluetooth.characteristic.gap.device_name", 0x2a00_u32), ("org.bluetooth.characteristic.dew_point", 0x2a7b_u32), ("org.bluetooth.characteristic.digital", 0x2a56_u32), @@ -121,140 +226,332 @@ const BLUETOOTH_ASSIGNED_CHARCTERISTICS: &'static [(&'static str, u32)] = &[ ("org.bluetooth.characteristic.elevation", 0x2a6c_u32), ("org.bluetooth.characteristic.email_address", 0x2a87_u32), ("org.bluetooth.characteristic.exact_time_256", 0x2a0c_u32), - ("org.bluetooth.characteristic.fat_burn_heart_rate_lower_limit", 0x2a88_u32), - ("org.bluetooth.characteristic.fat_burn_heart_rate_upper_limit", 0x2a89_u32), - ("org.bluetooth.characteristic.firmware_revision_string", 0x2a26_u32), + ( + "org.bluetooth.characteristic.fat_burn_heart_rate_lower_limit", + 0x2a88_u32, + ), + ( + "org.bluetooth.characteristic.fat_burn_heart_rate_upper_limit", + 0x2a89_u32, + ), + ( + "org.bluetooth.characteristic.firmware_revision_string", + 0x2a26_u32, + ), ("org.bluetooth.characteristic.first_name", 0x2a8a_u32), - ("org.bluetooth.characteristic.five_zone_heart_rate_limits", 0x2a8b_u32), + ( + "org.bluetooth.characteristic.five_zone_heart_rate_limits", + 0x2a8b_u32, + ), ("org.bluetooth.characteristic.floor_number", 0x2ab2_u32), ("org.bluetooth.characteristic.gender", 0x2a8c_u32), ("org.bluetooth.characteristic.glucose_feature", 0x2a51_u32), - ("org.bluetooth.characteristic.glucose_measurement", 0x2a18_u32), - ("org.bluetooth.characteristic.glucose_measurement_context", 0x2a34_u32), + ( + "org.bluetooth.characteristic.glucose_measurement", + 0x2a18_u32, + ), + ( + "org.bluetooth.characteristic.glucose_measurement_context", + 0x2a34_u32, + ), ("org.bluetooth.characteristic.gust_factor", 0x2a74_u32), - ("org.bluetooth.characteristic.hardware_revision_string", 0x2a27_u32), - ("org.bluetooth.characteristic.heart_rate_control_point", 0x2a39_u32), + ( + "org.bluetooth.characteristic.hardware_revision_string", + 0x2a27_u32, + ), + ( + "org.bluetooth.characteristic.heart_rate_control_point", + 0x2a39_u32, + ), ("org.bluetooth.characteristic.heart_rate_max", 0x2a8d_u32), - ("org.bluetooth.characteristic.heart_rate_measurement", 0x2a37_u32), + ( + "org.bluetooth.characteristic.heart_rate_measurement", + 0x2a37_u32, + ), ("org.bluetooth.characteristic.heat_index", 0x2a7a_u32), ("org.bluetooth.characteristic.height", 0x2a8e_u32), ("org.bluetooth.characteristic.hid_control_point", 0x2a4c_u32), ("org.bluetooth.characteristic.hid_information", 0x2a4a_u32), ("org.bluetooth.characteristic.hip_circumference", 0x2a8f_u32), - ("org.bluetooth.characteristic.http_control_point", 0x2aba_u32), + ( + "org.bluetooth.characteristic.http_control_point", + 0x2aba_u32, + ), ("org.bluetooth.characteristic.http_entity_body", 0x2ab9_u32), ("org.bluetooth.characteristic.http_headers", 0x2ab7_u32), ("org.bluetooth.characteristic.http_status_code", 0x2ab8_u32), ("org.bluetooth.characteristic.https_security", 0x2abb_u32), ("org.bluetooth.characteristic.humidity", 0x2a6f_u32), - ("org.bluetooth.characteristic.ieee_11073-20601_regulatory_certification_data_list", 0x2a2a_u32), - ("org.bluetooth.characteristic.indoor_positioning_configuration", 0x2aad_u32), - ("org.bluetooth.characteristic.intermediate_cuff_pressure", 0x2a36_u32), - ("org.bluetooth.characteristic.intermediate_temperature", 0x2a1e_u32), + ( + "org.bluetooth.characteristic.ieee_11073-20601_regulatory_certification_data_list", + 0x2a2a_u32, + ), + ( + "org.bluetooth.characteristic.indoor_positioning_configuration", + 0x2aad_u32, + ), + ( + "org.bluetooth.characteristic.intermediate_cuff_pressure", + 0x2a36_u32, + ), + ( + "org.bluetooth.characteristic.intermediate_temperature", + 0x2a1e_u32, + ), ("org.bluetooth.characteristic.irradiance", 0x2a77_u32), ("org.bluetooth.characteristic.language", 0x2aa2_u32), ("org.bluetooth.characteristic.last_name", 0x2a90_u32), ("org.bluetooth.characteristic.latitude", 0x2aae_u32), ("org.bluetooth.characteristic.ln_control_point", 0x2a6b_u32), ("org.bluetooth.characteristic.ln_feature", 0x2a6a_u32), - ("org.bluetooth.characteristic.local_east_coordinate.xml", 0x2ab1_u32), - ("org.bluetooth.characteristic.local_north_coordinate", 0x2ab0_u32), - ("org.bluetooth.characteristic.local_time_information", 0x2a0f_u32), - ("org.bluetooth.characteristic.location_and_speed", 0x2a67_u32), + ( + "org.bluetooth.characteristic.local_east_coordinate.xml", + 0x2ab1_u32, + ), + ( + "org.bluetooth.characteristic.local_north_coordinate", + 0x2ab0_u32, + ), + ( + "org.bluetooth.characteristic.local_time_information", + 0x2a0f_u32, + ), + ( + "org.bluetooth.characteristic.location_and_speed", + 0x2a67_u32, + ), ("org.bluetooth.characteristic.location_name", 0x2ab5_u32), ("org.bluetooth.characteristic.longitude", 0x2aaf_u32), - ("org.bluetooth.characteristic.magnetic_declination", 0x2a2c_u32), - ("org.bluetooth.characteristic.magnetic_flux_density_2d", 0x2aa0_u32), - ("org.bluetooth.characteristic.magnetic_flux_density_3d", 0x2aa1_u32), - ("org.bluetooth.characteristic.manufacturer_name_string", 0x2a29_u32), - ("org.bluetooth.characteristic.maximum_recommended_heart_rate", 0x2a91_u32), - ("org.bluetooth.characteristic.measurement_interval", 0x2a21_u32), - ("org.bluetooth.characteristic.model_number_string", 0x2a24_u32), + ( + "org.bluetooth.characteristic.magnetic_declination", + 0x2a2c_u32, + ), + ( + "org.bluetooth.characteristic.magnetic_flux_density_2d", + 0x2aa0_u32, + ), + ( + "org.bluetooth.characteristic.magnetic_flux_density_3d", + 0x2aa1_u32, + ), + ( + "org.bluetooth.characteristic.manufacturer_name_string", + 0x2a29_u32, + ), + ( + "org.bluetooth.characteristic.maximum_recommended_heart_rate", + 0x2a91_u32, + ), + ( + "org.bluetooth.characteristic.measurement_interval", + 0x2a21_u32, + ), + ( + "org.bluetooth.characteristic.model_number_string", + 0x2a24_u32, + ), ("org.bluetooth.characteristic.navigation", 0x2a68_u32), ("org.bluetooth.characteristic.new_alert", 0x2a46_u32), - ("org.bluetooth.characteristic.object_action_control_point", 0x2ac5_u32), + ( + "org.bluetooth.characteristic.object_action_control_point", + 0x2ac5_u32, + ), ("org.bluetooth.characteristic.object_changed", 0x2ac8_u32), - ("org.bluetooth.characteristic.object_first_created", 0x2ac1_u32), + ( + "org.bluetooth.characteristic.object_first_created", + 0x2ac1_u32, + ), ("org.bluetooth.characteristic.object_id", 0x2ac3_u32), - ("org.bluetooth.characteristic.object_last_modified", 0x2ac2_u32), - ("org.bluetooth.characteristic.object_list_control_point", 0x2ac6_u32), - ("org.bluetooth.characteristic.object_list_filter", 0x2ac7_u32), + ( + "org.bluetooth.characteristic.object_last_modified", + 0x2ac2_u32, + ), + ( + "org.bluetooth.characteristic.object_list_control_point", + 0x2ac6_u32, + ), + ( + "org.bluetooth.characteristic.object_list_filter", + 0x2ac7_u32, + ), ("org.bluetooth.characteristic.object_name", 0x2abe_u32), ("org.bluetooth.characteristic.object_properties", 0x2ac4_u32), ("org.bluetooth.characteristic.object_size", 0x2ac0_u32), ("org.bluetooth.characteristic.object_type", 0x2abf_u32), ("org.bluetooth.characteristic.ots_feature", 0x2abd_u32), - ("org.bluetooth.characteristic.gap.peripheral_preferred_connection_parameters", 0x2a04_u32), - ("org.bluetooth.characteristic.gap.peripheral_privacy_flag", 0x2a02_u32), - ("org.bluetooth.characteristic.plx_continuous_measurement", 0x2a5f_u32), + ( + "org.bluetooth.characteristic.gap.peripheral_preferred_connection_parameters", + 0x2a04_u32, + ), + ( + "org.bluetooth.characteristic.gap.peripheral_privacy_flag", + 0x2a02_u32, + ), + ( + "org.bluetooth.characteristic.plx_continuous_measurement", + 0x2a5f_u32, + ), ("org.bluetooth.characteristic.plx_features", 0x2a60_u32), - ("org.bluetooth.characteristic.plx_spot_check_measurement", 0x2a5e_u32), + ( + "org.bluetooth.characteristic.plx_spot_check_measurement", + 0x2a5e_u32, + ), ("org.bluetooth.characteristic.pnp_id", 0x2a50_u32), - ("org.bluetooth.characteristic.pollen_concentration", 0x2a75_u32), + ( + "org.bluetooth.characteristic.pollen_concentration", + 0x2a75_u32, + ), ("org.bluetooth.characteristic.position_quality", 0x2a69_u32), ("org.bluetooth.characteristic.pressure", 0x2a6d_u32), ("org.bluetooth.characteristic.protocol_mode", 0x2a4e_u32), ("org.bluetooth.characteristic.rainfall", 0x2a78_u32), - ("org.bluetooth.characteristic.gap.reconnection_address", 0x2a03_u32), - ("org.bluetooth.characteristic.record_access_control_point", 0x2a52_u32), - ("org.bluetooth.characteristic.reference_time_information", 0x2a14_u32), + ( + "org.bluetooth.characteristic.gap.reconnection_address", + 0x2a03_u32, + ), + ( + "org.bluetooth.characteristic.record_access_control_point", + 0x2a52_u32, + ), + ( + "org.bluetooth.characteristic.reference_time_information", + 0x2a14_u32, + ), ("org.bluetooth.characteristic.report", 0x2a4d_u32), ("org.bluetooth.characteristic.report_map", 0x2a4b_u32), - ("org.bluetooth.characteristic.resting_heart_rate", 0x2a92_u32), - ("org.bluetooth.characteristic.ringer_control_point", 0x2a40_u32), + ( + "org.bluetooth.characteristic.resting_heart_rate", + 0x2a92_u32, + ), + ( + "org.bluetooth.characteristic.ringer_control_point", + 0x2a40_u32, + ), ("org.bluetooth.characteristic.ringer_setting", 0x2a41_u32), ("org.bluetooth.characteristic.rsc_feature", 0x2a54_u32), ("org.bluetooth.characteristic.rsc_measurement", 0x2a53_u32), ("org.bluetooth.characteristic.sc_control_point", 0x2a55_u32), - ("org.bluetooth.characteristic.scan_interval_window", 0x2a4f_u32), + ( + "org.bluetooth.characteristic.scan_interval_window", + 0x2a4f_u32, + ), ("org.bluetooth.characteristic.scan_refresh", 0x2a31_u32), ("org.bluetooth.characteristic.sensor_location", 0x2a5d_u32), - ("org.bluetooth.characteristic.serial_number_string", 0x2a25_u32), - ("org.bluetooth.characteristic.gatt.service_changed", 0x2a05_u32), - ("org.bluetooth.characteristic.software_revision_string", 0x2a28_u32), - ("org.bluetooth.characteristic.sport_type_for_aerobic_and_anaerobic_thresholds", 0x2a93_u32), - ("org.bluetooth.characteristic.supported_new_alert_category", 0x2a47_u32), - ("org.bluetooth.characteristic.supported_unread_alert_category", 0x2a48_u32), + ( + "org.bluetooth.characteristic.serial_number_string", + 0x2a25_u32, + ), + ( + "org.bluetooth.characteristic.gatt.service_changed", + 0x2a05_u32, + ), + ( + "org.bluetooth.characteristic.software_revision_string", + 0x2a28_u32, + ), + ( + "org.bluetooth.characteristic.sport_type_for_aerobic_and_anaerobic_thresholds", + 0x2a93_u32, + ), + ( + "org.bluetooth.characteristic.supported_new_alert_category", + 0x2a47_u32, + ), + ( + "org.bluetooth.characteristic.supported_unread_alert_category", + 0x2a48_u32, + ), ("org.bluetooth.characteristic.system_id", 0x2a23_u32), ("org.bluetooth.characteristic.tds_control_point", 0x2abc_u32), ("org.bluetooth.characteristic.temperature", 0x2a6e_u32), - ("org.bluetooth.characteristic.temperature_measurement", 0x2a1c_u32), + ( + "org.bluetooth.characteristic.temperature_measurement", + 0x2a1c_u32, + ), ("org.bluetooth.characteristic.temperature_type", 0x2a1d_u32), - ("org.bluetooth.characteristic.three_zone_heart_rate_limits", 0x2a94_u32), + ( + "org.bluetooth.characteristic.three_zone_heart_rate_limits", + 0x2a94_u32, + ), ("org.bluetooth.characteristic.time_accuracy", 0x2a12_u32), ("org.bluetooth.characteristic.time_source", 0x2a13_u32), - ("org.bluetooth.characteristic.time_update_control_point", 0x2a16_u32), + ( + "org.bluetooth.characteristic.time_update_control_point", + 0x2a16_u32, + ), ("org.bluetooth.characteristic.time_update_state", 0x2a17_u32), ("org.bluetooth.characteristic.time_with_dst", 0x2a11_u32), ("org.bluetooth.characteristic.time_zone", 0x2a0e_u32), - ("org.bluetooth.characteristic.true_wind_direction", 0x2a71_u32), + ( + "org.bluetooth.characteristic.true_wind_direction", + 0x2a71_u32, + ), ("org.bluetooth.characteristic.true_wind_speed", 0x2a70_u32), - ("org.bluetooth.characteristic.two_zone_heart_rate_limit", 0x2a95_u32), + ( + "org.bluetooth.characteristic.two_zone_heart_rate_limit", + 0x2a95_u32, + ), ("org.bluetooth.characteristic.tx_power_level", 0x2a07_u32), ("org.bluetooth.characteristic.uncertainty", 0x2ab4_u32), - ("org.bluetooth.characteristic.unread_alert_status", 0x2a45_u32), + ( + "org.bluetooth.characteristic.unread_alert_status", + 0x2a45_u32, + ), ("org.bluetooth.characteristic.uri", 0x2ab6_u32), - ("org.bluetooth.characteristic.user_control_point", 0x2a9f_u32), + ( + "org.bluetooth.characteristic.user_control_point", + 0x2a9f_u32, + ), ("org.bluetooth.characteristic.user_index", 0x2a9a_u32), ("org.bluetooth.characteristic.uv_index", 0x2a76_u32), ("org.bluetooth.characteristic.vo2_max", 0x2a96_u32), - ("org.bluetooth.characteristic.waist_circumference", 0x2a97_u32), + ( + "org.bluetooth.characteristic.waist_circumference", + 0x2a97_u32, + ), ("org.bluetooth.characteristic.weight", 0x2a98_u32), - ("org.bluetooth.characteristic.weight_measurement", 0x2a9d_u32), - ("org.bluetooth.characteristic.weight_scale_feature", 0x2a9e_u32), + ( + "org.bluetooth.characteristic.weight_measurement", + 0x2a9d_u32, + ), + ( + "org.bluetooth.characteristic.weight_scale_feature", + 0x2a9e_u32, + ), ("org.bluetooth.characteristic.wind_chill", 0x2a79_u32), ]; //https://developer.bluetooth.org/gatt/services/Pages/ServicesHome.aspx const BLUETOOTH_ASSIGNED_DESCRIPTORS: &'static [(&'static str, u32)] = &[ - ("org.bluetooth.descriptor.gatt.characteristic_extended_properties", 0x2900_u32), - ("org.bluetooth.descriptor.gatt.characteristic_user_description", 0x2901_u32), - ("org.bluetooth.descriptor.gatt.client_characteristic_configuration", 0x2902_u32), - ("org.bluetooth.descriptor.gatt.server_characteristic_configuration", 0x2903_u32), - ("org.bluetooth.descriptor.gatt.characteristic_presentation_format", 0x2904_u32), - ("org.bluetooth.descriptor.gatt.characteristic_aggregate_format", 0x2905_u32), + ( + "org.bluetooth.descriptor.gatt.characteristic_extended_properties", + 0x2900_u32, + ), + ( + "org.bluetooth.descriptor.gatt.characteristic_user_description", + 0x2901_u32, + ), + ( + "org.bluetooth.descriptor.gatt.client_characteristic_configuration", + 0x2902_u32, + ), + ( + "org.bluetooth.descriptor.gatt.server_characteristic_configuration", + 0x2903_u32, + ), + ( + "org.bluetooth.descriptor.gatt.characteristic_presentation_format", + 0x2904_u32, + ), + ( + "org.bluetooth.descriptor.gatt.characteristic_aggregate_format", + 0x2905_u32, + ), ("org.bluetooth.descriptor.valid_range", 0x2906_u32), - ("org.bluetooth.descriptor.external_report_reference", 0x2907_u32), + ( + "org.bluetooth.descriptor.external_report_reference", + 0x2907_u32, + ), ("org.bluetooth.descriptor.report_reference", 0x2908_u32), ("org.bluetooth.descriptor.number_of_digitals", 0x2909_u32), ("org.bluetooth.descriptor.value_trigger_setting", 0x290a_u32), @@ -268,19 +565,23 @@ const BASE_UUID: &'static str = "-0000-1000-8000-00805f9b34fb"; const SERVICE_PREFIX: &'static str = "org.bluetooth.service"; const CHARACTERISTIC_PREFIX: &'static str = "org.bluetooth.characteristic"; const DESCRIPTOR_PREFIX: &'static str = "org.bluetooth.descriptor"; -const VALID_UUID_REGEX: &'static str = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"; +const VALID_UUID_REGEX: &'static str = + "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"; // https://cs.chromium.org/chromium/src/third_party/WebKit/Source/modules/bluetooth/BluetoothUUID.cpp?l=314 const UUID_ERROR_MESSAGE: &'static str = "It must be a valid UUID alias (e.g. 0x1234), \ UUID (lowercase hex characters e.g. '00001234-0000-1000-8000-00805f9b34fb'),\nor recognized standard name from"; // https://cs.chromium.org/chromium/src/third_party/WebKit/Source/modules/bluetooth/BluetoothUUID.cpp?l=321 -const SERVICES_ERROR_MESSAGE: &'static str = "https://developer.bluetooth.org/gatt/services/Pages/ServicesHome.aspx\ - \ne.g. 'alert_notification'."; +const SERVICES_ERROR_MESSAGE: &'static str = + "https://developer.bluetooth.org/gatt/services/Pages/ServicesHome.aspx\ + \ne.g. 'alert_notification'."; // https://cs.chromium.org/chromium/src/third_party/WebKit/Source/modules/bluetooth/BluetoothUUID.cpp?l=327 -const CHARACTERISTIC_ERROR_MESSAGE: &'static str = "https://developer.bluetooth.org/gatt/characteristics/Pages/\ - CharacteristicsHome.aspx\ne.g. 'aerobic_heart_rate_lower_limit'."; +const CHARACTERISTIC_ERROR_MESSAGE: &'static str = + "https://developer.bluetooth.org/gatt/characteristics/Pages/\ + CharacteristicsHome.aspx\ne.g. 'aerobic_heart_rate_lower_limit'."; // https://cs.chromium.org/chromium/src/third_party/WebKit/Source/modules/bluetooth/BluetoothUUID.cpp?l=333 -const DESCRIPTOR_ERROR_MESSAGE: &'static str = "https://developer.bluetooth.org/gatt/descriptors/Pages/\ - DescriptorsHomePage.aspx\ne.g. 'gatt.characteristic_presentation_format'."; +const DESCRIPTOR_ERROR_MESSAGE: &'static str = + "https://developer.bluetooth.org/gatt/descriptors/Pages/\ + DescriptorsHomePage.aspx\ne.g. 'gatt.characteristic_presentation_format'."; impl BluetoothUUID { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothuuid-canonicaluuid @@ -310,7 +611,11 @@ impl BluetoothUUID { } pub fn characteristic(name: BluetoothCharacteristicUUID) -> Fallible<UUID> { - resolve_uuid_name(name, BLUETOOTH_ASSIGNED_CHARCTERISTICS, CHARACTERISTIC_PREFIX) + resolve_uuid_name( + name, + BLUETOOTH_ASSIGNED_CHARCTERISTICS, + CHARACTERISTIC_PREFIX, + ) } pub fn descriptor(name: BluetoothDescriptorUUID) -> Fallible<UUID> { @@ -333,22 +638,20 @@ fn canonical_uuid(alias: u32) -> UUID { // https://webbluetoothcg.github.io/web-bluetooth/#resolveuuidname fn resolve_uuid_name( - name: StringOrUnsignedLong, - assigned_numbers_table: &'static [(&'static str, u32)], - prefix: &str) - -> Fallible<DOMString> { + name: StringOrUnsignedLong, + assigned_numbers_table: &'static [(&'static str, u32)], + prefix: &str, +) -> Fallible<DOMString> { match name { // Step 1. - StringOrUnsignedLong::UnsignedLong(unsigned32) => { - Ok(canonical_uuid(unsigned32)) - }, + StringOrUnsignedLong::UnsignedLong(unsigned32) => Ok(canonical_uuid(unsigned32)), StringOrUnsignedLong::String(dstring) => { - // Step 2. + // Step 2. let regex = Regex::new(VALID_UUID_REGEX).unwrap(); if regex.is_match(&*dstring) { Ok(dstring) } else { - // Step 3. + // Step 3. let concatenated = format!("{}.{}", prefix, dstring); let is_in_table = assigned_numbers_table.iter().find(|p| p.0 == concatenated); match is_in_table { @@ -356,16 +659,17 @@ fn resolve_uuid_name( None => { let (attribute_type, error_url_message) = match prefix { SERVICE_PREFIX => ("Service", SERVICES_ERROR_MESSAGE), - CHARACTERISTIC_PREFIX => ("Characteristic", CHARACTERISTIC_ERROR_MESSAGE), + CHARACTERISTIC_PREFIX => { + ("Characteristic", CHARACTERISTIC_ERROR_MESSAGE) + }, DESCRIPTOR_PREFIX => ("Descriptor", DESCRIPTOR_ERROR_MESSAGE), _ => unreachable!(), }; // Step 4. - return Err(Type(format!("Invalid {} name : '{}'.\n{} {}", - attribute_type, - dstring, - UUID_ERROR_MESSAGE, - error_url_message))); + return Err(Type(format!( + "Invalid {} name : '{}'.\n{} {}", + attribute_type, dstring, UUID_ERROR_MESSAGE, error_url_message + ))); }, } } diff --git a/components/script/dom/canvasgradient.rs b/components/script/dom/canvasgradient.rs index ab6ad47d905..e3f4ea54f4b 100644 --- a/components/script/dom/canvasgradient.rs +++ b/components/script/dom/canvasgradient.rs @@ -40,9 +40,11 @@ impl CanvasGradient { } pub fn new(global: &GlobalScope, style: CanvasGradientStyle) -> DomRoot<CanvasGradient> { - reflect_dom_object(Box::new(CanvasGradient::new_inherited(style)), - global, - CanvasGradientBinding::Wrap) + reflect_dom_object( + Box::new(CanvasGradient::new_inherited(style)), + global, + CanvasGradientBinding::Wrap, + ) } } @@ -60,10 +62,10 @@ impl CanvasGradientMethods for CanvasGradient { match color { Ok(CSSColor::RGBA(rgba)) => rgba, Ok(CSSColor::CurrentColor) => RGBA::new(0, 0, 0, 255), - _ => return Err(Error::Syntax) + _ => return Err(Error::Syntax), } } else { - return Err(Error::Syntax) + return Err(Error::Syntax); }; self.stops.borrow_mut().push(CanvasGradientStop { @@ -83,21 +85,25 @@ impl<'a> ToFillOrStrokeStyle for &'a CanvasGradient { let gradient_stops = self.stops.borrow().clone(); match self.style { CanvasGradientStyle::Linear(ref gradient) => { - FillOrStrokeStyle::LinearGradient(LinearGradientStyle::new(gradient.x0, - gradient.y0, - gradient.x1, - gradient.y1, - gradient_stops)) - } + FillOrStrokeStyle::LinearGradient(LinearGradientStyle::new( + gradient.x0, + gradient.y0, + gradient.x1, + gradient.y1, + gradient_stops, + )) + }, CanvasGradientStyle::Radial(ref gradient) => { - FillOrStrokeStyle::RadialGradient(RadialGradientStyle::new(gradient.x0, - gradient.y0, - gradient.r0, - gradient.x1, - gradient.y1, - gradient.r1, - gradient_stops)) - } + FillOrStrokeStyle::RadialGradient(RadialGradientStyle::new( + gradient.x0, + gradient.y0, + gradient.r0, + gradient.x1, + gradient.y1, + gradient.r1, + gradient_stops, + )) + }, } } } diff --git a/components/script/dom/canvaspattern.rs b/components/script/dom/canvaspattern.rs index d1bf89f3e63..ced7a6bb11b 100644 --- a/components/script/dom/canvaspattern.rs +++ b/components/script/dom/canvaspattern.rs @@ -23,11 +23,12 @@ pub struct CanvasPattern { } impl CanvasPattern { - fn new_inherited(surface_data: Vec<u8>, - surface_size: Size2D<i32>, - repeat: RepetitionStyle, - origin_clean: bool) - -> CanvasPattern { + fn new_inherited( + surface_data: Vec<u8>, + surface_size: Size2D<i32>, + repeat: RepetitionStyle, + origin_clean: bool, + ) -> CanvasPattern { let (x, y) = match repeat { RepetitionStyle::Repeat => (true, true), RepetitionStyle::RepeatX => (true, false), @@ -44,30 +45,36 @@ impl CanvasPattern { origin_clean: origin_clean, } } - pub fn new(global: &GlobalScope, - surface_data: Vec<u8>, - surface_size: Size2D<i32>, - repeat: RepetitionStyle, - origin_clean: bool) - -> DomRoot<CanvasPattern> { + pub fn new( + global: &GlobalScope, + surface_data: Vec<u8>, + surface_size: Size2D<i32>, + repeat: RepetitionStyle, + origin_clean: bool, + ) -> DomRoot<CanvasPattern> { reflect_dom_object( Box::new(CanvasPattern::new_inherited( - surface_data, surface_size, repeat, origin_clean + surface_data, + surface_size, + repeat, + origin_clean, )), global, - CanvasPatternBinding::Wrap + CanvasPatternBinding::Wrap, ) } pub fn origin_is_clean(&self) -> bool { - self.origin_clean + self.origin_clean } } impl<'a> ToFillOrStrokeStyle for &'a CanvasPattern { fn to_fill_or_stroke_style(self) -> FillOrStrokeStyle { - FillOrStrokeStyle::Surface(SurfaceStyle::new(self.surface_data.clone(), - self.surface_size, - self.repeat_x, - self.repeat_y)) + FillOrStrokeStyle::Surface(SurfaceStyle::new( + self.surface_data.clone(), + self.surface_size, + self.repeat_x, + self.repeat_y, + )) } } diff --git a/components/script/dom/canvasrenderingcontext2d.rs b/components/script/dom/canvasrenderingcontext2d.rs index 948fd0b9efe..e3ca01c311e 100644 --- a/components/script/dom/canvasrenderingcontext2d.rs +++ b/components/script/dom/canvasrenderingcontext2d.rs @@ -123,17 +123,21 @@ impl CanvasContextState { } impl CanvasRenderingContext2D { - pub fn new_inherited(global: &GlobalScope, - canvas: Option<&HTMLCanvasElement>, - image_cache: Arc<ImageCache>, - base_url: ServoUrl, - size: Size2D<i32>) - -> CanvasRenderingContext2D { + pub fn new_inherited( + global: &GlobalScope, + canvas: Option<&HTMLCanvasElement>, + image_cache: Arc<ImageCache>, + base_url: ServoUrl, + size: Size2D<i32>, + ) -> CanvasRenderingContext2D { debug!("Creating new canvas rendering context."); - let (sender, receiver) = profiled_ipc::channel(global.time_profiler_chan().clone()).unwrap(); + let (sender, receiver) = + profiled_ipc::channel(global.time_profiler_chan().clone()).unwrap(); let script_to_constellation_chan = global.script_to_constellation_chan(); debug!("Asking constellation to create new canvas thread."); - script_to_constellation_chan.send(ScriptMsg::CreateCanvasPaintThread(size, sender)).unwrap(); + script_to_constellation_chan + .send(ScriptMsg::CreateCanvasPaintThread(size, sender)) + .unwrap(); let (ipc_renderer, canvas_id) = receiver.recv().unwrap(); debug!("Done."); CanvasRenderingContext2D { @@ -150,15 +154,20 @@ impl CanvasRenderingContext2D { } } - pub fn new(global: &GlobalScope, - canvas: &HTMLCanvasElement, - size: Size2D<i32>) - -> DomRoot<CanvasRenderingContext2D> { + pub fn new( + global: &GlobalScope, + canvas: &HTMLCanvasElement, + size: Size2D<i32>, + ) -> DomRoot<CanvasRenderingContext2D> { let window = window_from_node(canvas); let image_cache = window.image_cache(); let base_url = window.get_url(); let boxed = Box::new(CanvasRenderingContext2D::new_inherited( - global, Some(canvas), image_cache, base_url, size + global, + Some(canvas), + image_cache, + base_url, + size, )); reflect_dom_object(boxed, global, CanvasRenderingContext2DBinding::Wrap) } @@ -191,28 +200,35 @@ impl CanvasRenderingContext2D { // on the drawImage call arguments // source rectangle = area of the original image to be copied // destination rectangle = area of the destination canvas where the source image is going to be drawn - fn adjust_source_dest_rects(&self, - image_size: Size2D<f64>, - sx: f64, - sy: f64, - sw: f64, - sh: f64, - dx: f64, - dy: f64, - dw: f64, - dh: f64) - -> (Rect<f64>, Rect<f64>) { - let image_rect = Rect::new(Point2D::new(0f64, 0f64), - Size2D::new(image_size.width as f64, image_size.height as f64)); + fn adjust_source_dest_rects( + &self, + image_size: Size2D<f64>, + sx: f64, + sy: f64, + sw: f64, + sh: f64, + dx: f64, + dy: f64, + dw: f64, + dh: f64, + ) -> (Rect<f64>, Rect<f64>) { + let image_rect = Rect::new( + Point2D::new(0f64, 0f64), + Size2D::new(image_size.width as f64, image_size.height as f64), + ); // The source rectangle is the rectangle whose corners are the four points (sx, sy), // (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh). - let source_rect = Rect::new(Point2D::new(sx.min(sx + sw), sy.min(sy + sh)), - Size2D::new(sw.abs(), sh.abs())); + let source_rect = Rect::new( + Point2D::new(sx.min(sx + sw), sy.min(sy + sh)), + Size2D::new(sw.abs(), sh.abs()), + ); // When the source rectangle is outside the source image, // the source rectangle must be clipped to the source image - let source_rect_clipped = source_rect.intersection(&image_rect).unwrap_or(Rect::zero()); + let source_rect_clipped = source_rect + .intersection(&image_rect) + .unwrap_or(Rect::zero()); // Width and height ratios between the non clipped and clipped source rectangles let width_ratio: f64 = source_rect_clipped.size.width / source_rect.size.width; @@ -225,27 +241,29 @@ impl CanvasRenderingContext2D { // The destination rectangle is the rectangle whose corners are the four points (dx, dy), // (dx+dw, dy), (dx+dw, dy+dh), (dx, dy+dh). - let dest_rect = Rect::new(Point2D::new(dx.min(dx + dest_rect_width_scaled), - dy.min(dy + dest_rect_height_scaled)), - Size2D::new(dest_rect_width_scaled.abs(), - dest_rect_height_scaled.abs())); + let dest_rect = Rect::new( + Point2D::new( + dx.min(dx + dest_rect_width_scaled), + dy.min(dy + dest_rect_height_scaled), + ), + Size2D::new(dest_rect_width_scaled.abs(), dest_rect_height_scaled.abs()), + ); - let source_rect = Rect::new(Point2D::new(source_rect_clipped.origin.x, - source_rect_clipped.origin.y), - Size2D::new(source_rect_clipped.size.width, - source_rect_clipped.size.height)); + let source_rect = Rect::new( + Point2D::new(source_rect_clipped.origin.x, source_rect_clipped.origin.y), + Size2D::new( + source_rect_clipped.size.width, + source_rect_clipped.size.height, + ), + ); (source_rect, dest_rect) } // https://html.spec.whatwg.org/multipage/#the-image-argument-is-not-origin-clean - fn is_origin_clean(&self, - image: CanvasImageSource) - -> bool { + fn is_origin_clean(&self, image: CanvasImageSource) -> bool { match image { - CanvasImageSource::HTMLCanvasElement(canvas) => { - canvas.origin_is_clean() - } + CanvasImageSource::HTMLCanvasElement(canvas) => canvas.origin_is_clean(), CanvasImageSource::HTMLImageElement(image) => { image.same_origin(GlobalScope::entry().origin()) } @@ -274,38 +292,35 @@ impl CanvasRenderingContext2D { // is copied on the rectangle (dx, dy, dh, dw) of the destination canvas // // https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage - fn draw_image(&self, - image: CanvasImageSource, - sx: f64, - sy: f64, - sw: Option<f64>, - sh: Option<f64>, - dx: f64, - dy: f64, - dw: Option<f64>, - dh: Option<f64>) - -> ErrorResult { + fn draw_image( + &self, + image: CanvasImageSource, + sx: f64, + sy: f64, + sw: Option<f64>, + sh: Option<f64>, + dx: f64, + dy: f64, + dw: Option<f64>, + dh: Option<f64>, + ) -> ErrorResult { let result = match image { CanvasImageSource::HTMLCanvasElement(ref canvas) => { - self.draw_html_canvas_element(&canvas, - sx, sy, sw, sh, - dx, dy, dw, dh) - } + self.draw_html_canvas_element(&canvas, sx, sy, sw, sh, dx, dy, dw, dh) + }, CanvasImageSource::HTMLImageElement(ref image) => { // https://html.spec.whatwg.org/multipage/#img-error // If the image argument is an HTMLImageElement object that is in the broken state, // then throw an InvalidStateError exception let url = image.get_url().ok_or(Error::InvalidState)?; - self.fetch_and_draw_image_data(url, - sx, sy, sw, sh, - dx, dy, dw, dh) - } + self.fetch_and_draw_image_data(url, sx, sy, sw, sh, dx, dy, dw, dh) + }, CanvasImageSource::CSSStyleValue(ref value) => { - let url = value.get_url(self.base_url.clone()).ok_or(Error::InvalidState)?; - self.fetch_and_draw_image_data(url, - sx, sy, sw, sh, - dx, dy, dw, dh) - } + let url = value + .get_url(self.base_url.clone()) + .ok_or(Error::InvalidState)?; + self.fetch_and_draw_image_data(url, sx, sy, sw, sh, dx, dy, dw, dh) + }, }; if result.is_ok() && !self.is_origin_clean(image) { @@ -339,17 +354,8 @@ impl CanvasRenderingContext2D { let image_size = Size2D::new(canvas_size.width as f64, canvas_size.height as f64); // 2. Establish the source and destination rectangles - let (source_rect, dest_rect) = self.adjust_source_dest_rects( - image_size, - sx, - sy, - sw, - sh, - dx, - dy, - dw, - dh, - ); + let (source_rect, dest_rect) = + self.adjust_source_dest_rects(image_size, sx, sy, sw, sh, dx, dy, dw, dh); if !is_rect_valid(source_rect) || !is_rect_valid(dest_rect) { return Ok(()); @@ -384,17 +390,18 @@ impl CanvasRenderingContext2D { Ok(()) } - fn fetch_and_draw_image_data(&self, - url: ServoUrl, - sx: f64, - sy: f64, - sw: Option<f64>, - sh: Option<f64>, - dx: f64, - dy: f64, - dw: Option<f64>, - dh: Option<f64>) - -> ErrorResult { + fn fetch_and_draw_image_data( + &self, + url: ServoUrl, + sx: f64, + sy: f64, + sw: Option<f64>, + sh: Option<f64>, + dx: f64, + dy: f64, + dw: Option<f64>, + dh: Option<f64>, + ) -> ErrorResult { debug!("Fetching image {}.", url); // https://html.spec.whatwg.org/multipage/#img-error // If the image argument is an HTMLImageElement object that is in the broken state, @@ -413,34 +420,25 @@ impl CanvasRenderingContext2D { let dh = dh.unwrap_or(image_size.height); let sw = sw.unwrap_or(image_size.width); let sh = sh.unwrap_or(image_size.height); - self.draw_image_data(image_data, - image_size, - sx, sy, sw, sh, - dx, dy, dw, dh) - } - - fn draw_image_data(&self, - image_data: Vec<u8>, - image_size: Size2D<f64>, - sx: f64, - sy: f64, - sw: f64, - sh: f64, - dx: f64, - dy: f64, - dw: f64, - dh: f64) - -> ErrorResult { + self.draw_image_data(image_data, image_size, sx, sy, sw, sh, dx, dy, dw, dh) + } + + fn draw_image_data( + &self, + image_data: Vec<u8>, + image_size: Size2D<f64>, + sx: f64, + sy: f64, + sw: f64, + sh: f64, + dx: f64, + dy: f64, + dw: f64, + dh: f64, + ) -> ErrorResult { // Establish the source and destination rectangles - let (source_rect, dest_rect) = self.adjust_source_dest_rects(image_size, - sx, - sy, - sw, - sh, - dx, - dy, - dw, - dh); + let (source_rect, dest_rect) = + self.adjust_source_dest_rects(image_size, sx, sy, sw, sh, dx, dy, dw, dh); if !is_rect_valid(source_rect) || !is_rect_valid(dest_rect) { return Ok(()); @@ -465,7 +463,7 @@ impl CanvasRenderingContext2D { ImageResponse::None | ImageResponse::MetadataLoaded(_) => { return None; - } + }, }; let image_size = Size2D::new(img.width as i32, img.height as i32); @@ -481,15 +479,16 @@ impl CanvasRenderingContext2D { #[inline] fn request_image_from_cache(&self, url: ServoUrl) -> ImageResponse { - let response = self.image_cache - .find_image_or_metadata(url.clone(), - UsePlaceholder::No, - CanRequestImages::No); + let response = self.image_cache.find_image_or_metadata( + url.clone(), + UsePlaceholder::No, + CanRequestImages::No, + ); match response { - Ok(ImageOrMetadataAvailable::ImageAvailable(image, url)) => - ImageResponse::Loaded(image, url), - Err(ImageState::Pending(_)) => - ImageResponse::None, + Ok(ImageOrMetadataAvailable::ImageAvailable(image, url)) => { + ImageResponse::Loaded(image, url) + }, + Err(ImageState::Pending(_)) => ImageResponse::None, _ => { // Rather annoyingly, we get the same response back from // A load which really failed and from a load which hasn't started yet. @@ -512,8 +511,10 @@ impl CanvasRenderingContext2D { return None; } - Some(Rect::new(Point2D::new(x as f32, y as f32), - Size2D::new(w as f32, h as f32))) + Some(Rect::new( + Point2D::new(x as f32, y as f32), + Size2D::new(w as f32, h as f32), + )) } fn parse_color(&self, string: &str) -> Result<RGBA, ()> { @@ -540,11 +541,13 @@ impl CanvasRenderingContext2D { let canvas_element = canvas.upcast::<Element>(); match canvas_element.style() { - Some(ref s) if canvas_element.has_css_layout_box() => Ok(s.get_color().color), - _ => Ok(RGBA::new(0, 0, 0, 255)) + Some(ref s) if canvas_element.has_css_layout_box() => { + Ok(s.get_color().color) + }, + _ => Ok(RGBA::new(0, 0, 0, 255)), } }, - _ => Err(()) + _ => Err(()), } } else { Err(()) @@ -556,7 +559,9 @@ impl CanvasRenderingContext2D { } pub fn send_canvas_2d_msg(&self, msg: Canvas2dMsg) { - self.ipc_renderer.send(CanvasMsg::Canvas2d(msg, self.get_canvas_id())).unwrap() + self.ipc_renderer + .send(CanvasMsg::Canvas2d(msg, self.get_canvas_id())) + .unwrap() } pub fn get_ipc_renderer(&self) -> IpcSender<CanvasMsg> { @@ -610,7 +615,9 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { // https://html.spec.whatwg.org/multipage/#dom-context-2d-save fn Save(&self) { - self.saved_states.borrow_mut().push(self.state.borrow().clone()); + self.saved_states + .borrow_mut() + .push(self.state.borrow().clone()); self.send_canvas_2d_msg(Canvas2dMsg::SaveContext); } @@ -643,10 +650,14 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { let (sin, cos) = (angle.sin(), angle.cos()); let transform = self.state.borrow().transform; - self.state.borrow_mut().transform = transform.pre_mul( - &Transform2D::row_major(cos as f32, sin as f32, - -sin as f32, cos as f32, - 0.0, 0.0)); + self.state.borrow_mut().transform = transform.pre_mul(&Transform2D::row_major( + cos as f32, + sin as f32, + -sin as f32, + cos as f32, + 0.0, + 0.0, + )); self.update_transform() } @@ -663,21 +674,32 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { // https://html.spec.whatwg.org/multipage/#dom-context-2d-transform fn Transform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) { - if !(a.is_finite() && b.is_finite() && c.is_finite() && - d.is_finite() && e.is_finite() && f.is_finite()) { + if !(a.is_finite() && + b.is_finite() && + c.is_finite() && + d.is_finite() && + e.is_finite() && + f.is_finite()) + { return; } let transform = self.state.borrow().transform; - self.state.borrow_mut().transform = transform.pre_mul( - &Transform2D::row_major(a as f32, b as f32, c as f32, d as f32, e as f32, f as f32)); + self.state.borrow_mut().transform = transform.pre_mul(&Transform2D::row_major( + a as f32, b as f32, c as f32, d as f32, e as f32, f as f32, + )); self.update_transform() } // https://html.spec.whatwg.org/multipage/#dom-context-2d-settransform fn SetTransform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) { - if !(a.is_finite() && b.is_finite() && c.is_finite() && - d.is_finite() && e.is_finite() && f.is_finite()) { + if !(a.is_finite() && + b.is_finite() && + c.is_finite() && + d.is_finite() && + e.is_finite() && + f.is_finite()) + { return; } @@ -784,7 +806,8 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { CanvasFillRule::Nonzero => FillRule::Nonzero, CanvasFillRule::Evenodd => FillRule::Evenodd, }; - let (sender, receiver) = profiled_ipc::channel::<bool>(self.global().time_profiler_chan().clone()).unwrap(); + let (sender, receiver) = + profiled_ipc::channel::<bool>(self.global().time_profiler_chan().clone()).unwrap(); self.send_canvas_2d_msg(Canvas2dMsg::IsPointInPath(x, y, fill_rule, sender)); receiver.recv().unwrap() } @@ -797,11 +820,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage - fn DrawImage(&self, - image: CanvasImageSource, - dx: f64, - dy: f64) - -> ErrorResult { + fn DrawImage(&self, image: CanvasImageSource, dx: f64, dy: f64) -> ErrorResult { if !(dx.is_finite() && dy.is_finite()) { return Ok(()); } @@ -810,13 +829,14 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage - fn DrawImage_(&self, - image: CanvasImageSource, - dx: f64, - dy: f64, - dw: f64, - dh: f64) - -> ErrorResult { + fn DrawImage_( + &self, + image: CanvasImageSource, + dx: f64, + dy: f64, + dw: f64, + dh: f64, + ) -> ErrorResult { if !(dx.is_finite() && dy.is_finite() && dw.is_finite() && dh.is_finite()) { return Ok(()); } @@ -825,31 +845,41 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage - fn DrawImage__(&self, - image: CanvasImageSource, - sx: f64, - sy: f64, - sw: f64, - sh: f64, - dx: f64, - dy: f64, - dw: f64, - dh: f64) - -> ErrorResult { - if !(sx.is_finite() && sy.is_finite() && sw.is_finite() && sh.is_finite() && - dx.is_finite() && dy.is_finite() && dw.is_finite() && dh.is_finite()) { + fn DrawImage__( + &self, + image: CanvasImageSource, + sx: f64, + sy: f64, + sw: f64, + sh: f64, + dx: f64, + dy: f64, + dw: f64, + dh: f64, + ) -> ErrorResult { + if !(sx.is_finite() && + sy.is_finite() && + sw.is_finite() && + sh.is_finite() && + dx.is_finite() && + dy.is_finite() && + dw.is_finite() && + dh.is_finite()) + { return Ok(()); } - self.draw_image(image, - sx, - sy, - Some(sw), - Some(sh), - dx, - dy, - Some(dw), - Some(dh)) + self.draw_image( + image, + sx, + sy, + Some(sw), + Some(sh), + dx, + dy, + Some(dw), + Some(dh), + ) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-moveto @@ -871,8 +901,10 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { // https://html.spec.whatwg.org/multipage/#dom-context-2d-rect fn Rect(&self, x: f64, y: f64, width: f64, height: f64) { if [x, y, width, height].iter().all(|val| val.is_finite()) { - let rect = Rect::new(Point2D::new(x as f32, y as f32), - Size2D::new(width as f32, height as f32)); + let rect = Rect::new( + Point2D::new(x as f32, y as f32), + Size2D::new(width as f32, height as f32), + ); self.send_canvas_2d_msg(Canvas2dMsg::Rect(rect)); } } @@ -882,23 +914,28 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { if !(cpx.is_finite() && cpy.is_finite() && x.is_finite() && y.is_finite()) { return; } - self.send_canvas_2d_msg(Canvas2dMsg::QuadraticCurveTo(Point2D::new(cpx as f32, - cpy as f32), - Point2D::new(x as f32, - y as f32))); + self.send_canvas_2d_msg(Canvas2dMsg::QuadraticCurveTo( + Point2D::new(cpx as f32, cpy as f32), + Point2D::new(x as f32, y as f32), + )); } // https://html.spec.whatwg.org/multipage/#dom-context-2d-beziercurveto fn BezierCurveTo(&self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, x: f64, y: f64) { - if !(cp1x.is_finite() && cp1y.is_finite() && cp2x.is_finite() && cp2y.is_finite() && - x.is_finite() && y.is_finite()) { + if !(cp1x.is_finite() && + cp1y.is_finite() && + cp2x.is_finite() && + cp2y.is_finite() && + x.is_finite() && + y.is_finite()) + { return; } - self.send_canvas_2d_msg(Canvas2dMsg::BezierCurveTo(Point2D::new(cp1x as f32, - cp1y as f32), - Point2D::new(cp2x as f32, - cp2y as f32), - Point2D::new(x as f32, y as f32))); + self.send_canvas_2d_msg(Canvas2dMsg::BezierCurveTo( + Point2D::new(cp1x as f32, cp1y as f32), + Point2D::new(cp2x as f32, cp2y as f32), + Point2D::new(x as f32, y as f32), + )); } // https://html.spec.whatwg.org/multipage/#dom-context-2d-arc @@ -911,11 +948,13 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { return Err(Error::IndexSize); } - self.send_canvas_2d_msg(Canvas2dMsg::Arc(Point2D::new(x as f32, y as f32), - r as f32, - start as f32, - end as f32, - ccw)); + self.send_canvas_2d_msg(Canvas2dMsg::Arc( + Point2D::new(x as f32, y as f32), + r as f32, + start as f32, + end as f32, + ccw, + )); Ok(()) } @@ -928,28 +967,45 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { return Err(Error::IndexSize); } - self.send_canvas_2d_msg(Canvas2dMsg::ArcTo(Point2D::new(cp1x as f32, cp1y as f32), - Point2D::new(cp2x as f32, cp2y as f32), - r as f32)); + self.send_canvas_2d_msg(Canvas2dMsg::ArcTo( + Point2D::new(cp1x as f32, cp1y as f32), + Point2D::new(cp2x as f32, cp2y as f32), + r as f32, + )); Ok(()) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-ellipse - fn Ellipse(&self, x: f64, y: f64, rx: f64, ry: f64, rotation: f64, start: f64, end: f64, ccw: bool) -> ErrorResult { - if !([x, y, rx, ry, rotation, start, end].iter().all(|x| x.is_finite())) { + fn Ellipse( + &self, + x: f64, + y: f64, + rx: f64, + ry: f64, + rotation: f64, + start: f64, + end: f64, + ccw: bool, + ) -> ErrorResult { + if !([x, y, rx, ry, rotation, start, end] + .iter() + .all(|x| x.is_finite())) + { return Ok(()); } if rx < 0.0 || ry < 0.0 { return Err(Error::IndexSize); } - self.send_canvas_2d_msg(Canvas2dMsg::Ellipse(Point2D::new(x as f32, y as f32), - rx as f32, - ry as f32, - rotation as f32, - start as f32, - end as f32, - ccw)); + self.send_canvas_2d_msg(Canvas2dMsg::Ellipse( + Point2D::new(x as f32, y as f32), + rx as f32, + ry as f32, + rotation as f32, + start as f32, + end as f32, + ccw, + )); Ok(()) } @@ -977,7 +1033,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { }, CanvasFillOrStrokeStyle::Pattern(ref pattern) => { StringOrCanvasGradientOrCanvasPattern::CanvasPattern(DomRoot::from_ref(&*pattern)) - } + }, } } @@ -987,23 +1043,28 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { StringOrCanvasGradientOrCanvasPattern::String(string) => { if let Ok(rgba) = self.parse_color(&string) { self.state.borrow_mut().stroke_style = CanvasFillOrStrokeStyle::Color(rgba); - self.send_canvas_2d_msg(Canvas2dMsg::SetStrokeStyle( - FillOrStrokeStyle::Color(rgba))); + self.send_canvas_2d_msg(Canvas2dMsg::SetStrokeStyle(FillOrStrokeStyle::Color( + rgba, + ))); } }, StringOrCanvasGradientOrCanvasPattern::CanvasGradient(gradient) => { self.state.borrow_mut().stroke_style = CanvasFillOrStrokeStyle::Gradient(Dom::from_ref(&*gradient)); - self.send_canvas_2d_msg(Canvas2dMsg::SetStrokeStyle(gradient.to_fill_or_stroke_style())); + self.send_canvas_2d_msg(Canvas2dMsg::SetStrokeStyle( + gradient.to_fill_or_stroke_style(), + )); }, StringOrCanvasGradientOrCanvasPattern::CanvasPattern(pattern) => { self.state.borrow_mut().stroke_style = CanvasFillOrStrokeStyle::Pattern(Dom::from_ref(&*pattern)); - self.send_canvas_2d_msg(Canvas2dMsg::SetStrokeStyle(pattern.to_fill_or_stroke_style())); + self.send_canvas_2d_msg(Canvas2dMsg::SetStrokeStyle( + pattern.to_fill_or_stroke_style(), + )); if !pattern.origin_is_clean() { self.set_origin_unclean(); } - } + }, } } @@ -1020,7 +1081,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { }, CanvasFillOrStrokeStyle::Pattern(ref pattern) => { StringOrCanvasGradientOrCanvasPattern::CanvasPattern(DomRoot::from_ref(&*pattern)) - } + }, } } @@ -1030,23 +1091,28 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { StringOrCanvasGradientOrCanvasPattern::String(string) => { if let Ok(rgba) = self.parse_color(&string) { self.state.borrow_mut().fill_style = CanvasFillOrStrokeStyle::Color(rgba); - self.send_canvas_2d_msg(Canvas2dMsg::SetFillStyle( - FillOrStrokeStyle::Color(rgba))) + self.send_canvas_2d_msg(Canvas2dMsg::SetFillStyle(FillOrStrokeStyle::Color( + rgba, + ))) } - } + }, StringOrCanvasGradientOrCanvasPattern::CanvasGradient(gradient) => { self.state.borrow_mut().fill_style = CanvasFillOrStrokeStyle::Gradient(Dom::from_ref(&*gradient)); - self.send_canvas_2d_msg(Canvas2dMsg::SetFillStyle(gradient.to_fill_or_stroke_style())); - } + self.send_canvas_2d_msg(Canvas2dMsg::SetFillStyle( + gradient.to_fill_or_stroke_style(), + )); + }, StringOrCanvasGradientOrCanvasPattern::CanvasPattern(pattern) => { self.state.borrow_mut().fill_style = CanvasFillOrStrokeStyle::Pattern(Dom::from_ref(&*pattern)); - self.send_canvas_2d_msg(Canvas2dMsg::SetFillStyle(pattern.to_fill_or_stroke_style())); + self.send_canvas_2d_msg(Canvas2dMsg::SetFillStyle( + pattern.to_fill_or_stroke_style(), + )); if !pattern.origin_is_clean() { self.set_origin_unclean(); } - } + }, } } @@ -1063,21 +1129,19 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { // https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata fn CreateImageData_(&self, imagedata: &ImageData) -> Fallible<DomRoot<ImageData>> { - ImageData::new(&self.global(), - imagedata.Width(), - imagedata.Height(), - None) + ImageData::new(&self.global(), imagedata.Width(), imagedata.Height(), None) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-getimagedata - fn GetImageData(&self, - sx: Finite<f64>, - sy: Finite<f64>, - sw: Finite<f64>, - sh: Finite<f64>) - -> Fallible<DomRoot<ImageData>> { + fn GetImageData( + &self, + sx: Finite<f64>, + sy: Finite<f64>, + sw: Finite<f64>, + sh: Finite<f64>, + ) -> Fallible<DomRoot<ImageData>> { if !self.origin_is_clean() { - return Err(Error::Security) + return Err(Error::Security); } let mut sx = *sx; @@ -1102,9 +1166,15 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { let sw = cmp::max(1, sw.to_u32().unwrap()); let (sender, receiver) = ipc::bytes_channel().unwrap(); - let dest_rect = Rect::new(Point2D::new(sx.to_i32().unwrap(), sy.to_i32().unwrap()), - Size2D::new(sw as i32, sh as i32)); - let canvas_size = self.canvas.as_ref().map(|c| c.get_size()).unwrap_or(Size2D::zero()); + let dest_rect = Rect::new( + Point2D::new(sx.to_i32().unwrap(), sy.to_i32().unwrap()), + Size2D::new(sw as i32, sh as i32), + ); + let canvas_size = self + .canvas + .as_ref() + .map(|c| c.get_size()) + .unwrap_or(Size2D::zero()); let canvas_size = Size2D::new(canvas_size.width as f64, canvas_size.height as f64); self.send_canvas_2d_msg(Canvas2dMsg::GetImageData(dest_rect, canvas_size, sender)); let mut data = receiver.recv().unwrap(); @@ -1122,97 +1192,110 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { // https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata fn PutImageData(&self, imagedata: &ImageData, dx: Finite<f64>, dy: Finite<f64>) { - self.PutImageData_(imagedata, - dx, - dy, - Finite::wrap(0f64), - Finite::wrap(0f64), - Finite::wrap(imagedata.Width() as f64), - Finite::wrap(imagedata.Height() as f64)) + self.PutImageData_( + imagedata, + dx, + dy, + Finite::wrap(0f64), + Finite::wrap(0f64), + Finite::wrap(imagedata.Width() as f64), + Finite::wrap(imagedata.Height() as f64), + ) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata - fn PutImageData_(&self, - imagedata: &ImageData, - dx: Finite<f64>, - dy: Finite<f64>, - dirty_x: Finite<f64>, - dirty_y: Finite<f64>, - dirty_width: Finite<f64>, - dirty_height: Finite<f64>) { + fn PutImageData_( + &self, + imagedata: &ImageData, + dx: Finite<f64>, + dy: Finite<f64>, + dirty_x: Finite<f64>, + dirty_y: Finite<f64>, + dirty_width: Finite<f64>, + dirty_height: Finite<f64>, + ) { let data = imagedata.get_data_array(); let offset = Vector2D::new(*dx, *dy); let image_data_size = Size2D::new(imagedata.Width() as f64, imagedata.Height() as f64); - let dirty_rect = Rect::new(Point2D::new(*dirty_x, *dirty_y), - Size2D::new(*dirty_width, *dirty_height)); - self.send_canvas_2d_msg(Canvas2dMsg::PutImageData(data.into(), - offset, - image_data_size, - dirty_rect)); + let dirty_rect = Rect::new( + Point2D::new(*dirty_x, *dirty_y), + Size2D::new(*dirty_width, *dirty_height), + ); + self.send_canvas_2d_msg(Canvas2dMsg::PutImageData( + data.into(), + offset, + image_data_size, + dirty_rect, + )); self.mark_as_dirty(); } // https://html.spec.whatwg.org/multipage/#dom-context-2d-createlineargradient - fn CreateLinearGradient(&self, - x0: Finite<f64>, - y0: Finite<f64>, - x1: Finite<f64>, - y1: Finite<f64>) - -> DomRoot<CanvasGradient> { - CanvasGradient::new(&self.global(), - CanvasGradientStyle::Linear(LinearGradientStyle::new(*x0, - *y0, - *x1, - *y1, - Vec::new()))) + fn CreateLinearGradient( + &self, + x0: Finite<f64>, + y0: Finite<f64>, + x1: Finite<f64>, + y1: Finite<f64>, + ) -> DomRoot<CanvasGradient> { + CanvasGradient::new( + &self.global(), + CanvasGradientStyle::Linear(LinearGradientStyle::new(*x0, *y0, *x1, *y1, Vec::new())), + ) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-createradialgradient - fn CreateRadialGradient(&self, - x0: Finite<f64>, - y0: Finite<f64>, - r0: Finite<f64>, - x1: Finite<f64>, - y1: Finite<f64>, - r1: Finite<f64>) - -> Fallible<DomRoot<CanvasGradient>> { + fn CreateRadialGradient( + &self, + x0: Finite<f64>, + y0: Finite<f64>, + r0: Finite<f64>, + x1: Finite<f64>, + y1: Finite<f64>, + r1: Finite<f64>, + ) -> Fallible<DomRoot<CanvasGradient>> { if *r0 < 0. || *r1 < 0. { return Err(Error::IndexSize); } - Ok(CanvasGradient::new(&self.global(), - CanvasGradientStyle::Radial(RadialGradientStyle::new(*x0, - *y0, - *r0, - *x1, - *y1, - *r1, - Vec::new())))) + Ok(CanvasGradient::new( + &self.global(), + CanvasGradientStyle::Radial(RadialGradientStyle::new( + *x0, + *y0, + *r0, + *x1, + *y1, + *r1, + Vec::new(), + )), + )) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-createpattern - fn CreatePattern(&self, - image: CanvasImageSource, - mut repetition: DOMString) - -> Fallible<DomRoot<CanvasPattern>> { + fn CreatePattern( + &self, + image: CanvasImageSource, + mut repetition: DOMString, + ) -> Fallible<DomRoot<CanvasPattern>> { let (image_data, image_size) = match image { CanvasImageSource::HTMLImageElement(ref image) => { // https://html.spec.whatwg.org/multipage/#img-error // If the image argument is an HTMLImageElement object that is in the broken state, // then throw an InvalidStateError exception - image.get_url() + image + .get_url() .and_then(|url| self.fetch_image_data(url)) .ok_or(Error::InvalidState)? }, CanvasImageSource::HTMLCanvasElement(ref canvas) => { canvas.fetch_all_data().ok_or(Error::InvalidState)? }, - CanvasImageSource::CSSStyleValue(ref value) => { - value.get_url(self.base_url.clone()) - .and_then(|url| self.fetch_image_data(url)) - .ok_or(Error::InvalidState)? - } + CanvasImageSource::CSSStyleValue(ref value) => value + .get_url(self.base_url.clone()) + .and_then(|url| self.fetch_image_data(url)) + .ok_or(Error::InvalidState)?, }; if repetition.is_empty() { @@ -1220,11 +1303,13 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { } if let Ok(rep) = RepetitionStyle::from_str(&repetition) { - Ok(CanvasPattern::new(&self.global(), - image_data, - image_size, - rep, - self.is_origin_clean(image))) + Ok(CanvasPattern::new( + &self.global(), + image_data, + image_size, + rep, + self.is_origin_clean(image), + )) } else { Err(Error::Syntax) } @@ -1362,7 +1447,10 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { impl Drop for CanvasRenderingContext2D { fn drop(&mut self) { - if let Err(err) = self.ipc_renderer.send(CanvasMsg::Close(self.get_canvas_id())) { + if let Err(err) = self + .ipc_renderer + .send(CanvasMsg::Close(self.get_canvas_id())) + { warn!("Could not close canvas: {}", err) } } @@ -1391,22 +1479,32 @@ fn is_rect_valid(rect: Rect<f64>) -> bool { // https://html.spec.whatwg.org/multipage/#serialisation-of-a-colour fn serialize<W>(color: &RGBA, dest: &mut W) -> fmt::Result - where W: fmt::Write +where + W: fmt::Write, { let red = color.red; let green = color.green; let blue = color.blue; if color.alpha == 255 { - write!(dest, - "#{:x}{:x}{:x}{:x}{:x}{:x}", - red >> 4, - red & 0xF, - green >> 4, - green & 0xF, - blue >> 4, - blue & 0xF) + write!( + dest, + "#{:x}{:x}{:x}{:x}{:x}{:x}", + red >> 4, + red & 0xF, + green >> 4, + green & 0xF, + blue >> 4, + blue & 0xF + ) } else { - write!(dest, "rgba({}, {}, {}, {})", red, green, blue, color.alpha_f32()) + write!( + dest, + "rgba({}, {}, {}, {})", + red, + green, + blue, + color.alpha_f32() + ) } } diff --git a/components/script/dom/channelmergernode.rs b/components/script/dom/channelmergernode.rs index 4140f21b9b4..33f00927909 100644 --- a/components/script/dom/channelmergernode.rs +++ b/components/script/dom/channelmergernode.rs @@ -26,16 +26,18 @@ impl ChannelMergerNode { context: &BaseAudioContext, options: &ChannelMergerOptions, ) -> Fallible<ChannelMergerNode> { - let node_options = options.parent - .unwrap_or(1, ChannelCountMode::Explicit, - ChannelInterpretation::Speakers); + let node_options = options.parent.unwrap_or( + 1, + ChannelCountMode::Explicit, + ChannelInterpretation::Speakers, + ); if node_options.count != 1 || node_options.mode != ChannelCountMode::Explicit { - return Err(Error::InvalidState) + return Err(Error::InvalidState); } if options.numberOfInputs < 1 || options.numberOfInputs > MAX_CHANNEL_COUNT { - return Err(Error::IndexSize) + return Err(Error::IndexSize); } let node = AudioNode::new_inherited( @@ -43,11 +45,9 @@ impl ChannelMergerNode { context, node_options, options.numberOfInputs, // inputs - 1, // outputs + 1, // outputs )?; - Ok(ChannelMergerNode { - node, - }) + Ok(ChannelMergerNode { node }) } #[allow(unrooted_must_root)] @@ -57,7 +57,11 @@ impl ChannelMergerNode { options: &ChannelMergerOptions, ) -> Fallible<DomRoot<ChannelMergerNode>> { let node = ChannelMergerNode::new_inherited(window, context, options)?; - Ok(reflect_dom_object(Box::new(node), window, ChannelMergerNodeBinding::Wrap)) + Ok(reflect_dom_object( + Box::new(node), + window, + ChannelMergerNodeBinding::Wrap, + )) } pub fn Constructor( diff --git a/components/script/dom/characterdata.rs b/components/script/dom/characterdata.rs index 2d6bfbb706f..4b6676ec955 100644 --- a/components/script/dom/characterdata.rs +++ b/components/script/dom/characterdata.rs @@ -45,7 +45,7 @@ impl CharacterData { match self.upcast::<Node>().type_id() { NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => { DomRoot::upcast(Comment::new(data, &document)) - } + }, NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => { let pi = self.downcast::<ProcessingInstruction>().unwrap(); DomRoot::upcast(ProcessingInstruction::new(pi.Target(), data, &document)) @@ -107,7 +107,8 @@ impl CharacterDataMethods for CharacterData { *self.data.borrow_mut() = data; self.content_changed(); let node = self.upcast::<Node>(); - node.ranges().replace_code_units(node, 0, old_length, new_length); + node.ranges() + .replace_code_units(node, 0, old_length, new_length); } // https://dom.spec.whatwg.org/#dom-characterdata-length @@ -130,7 +131,7 @@ impl CharacterDataMethods for CharacterData { substring = substring + "\u{FFFD}"; } remaining = s; - } + }, // Step 2. Err(()) => return Err(Error::IndexSize), } @@ -146,7 +147,7 @@ impl CharacterDataMethods for CharacterData { if astral.is_some() { substring = substring + "\u{FFFD}"; } - } + }, }; Ok(DOMString::from(substring)) } @@ -183,7 +184,7 @@ impl CharacterDataMethods for CharacterData { // since our DOMString is currently strict UTF-8. replacement_before = if astral.is_some() { "\u{FFFD}" } else { "" }; remaining = r; - } + }, // Step 2. Err(()) => return Err(Error::IndexSize), }; @@ -194,14 +195,14 @@ impl CharacterDataMethods for CharacterData { Err(()) => { replacement_after = ""; suffix = ""; - } + }, Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_after = if astral.is_some() { "\u{FFFD}" } else { "" }; suffix = s; - } + }, }; // Step 4: Mutation observers. self.queue_mutation_record(); @@ -209,10 +210,11 @@ impl CharacterDataMethods for CharacterData { // Step 5 to 7. new_data = String::with_capacity( prefix.len() + - replacement_before.len() + - arg.len() + - replacement_after.len() + - suffix.len()); + replacement_before.len() + + arg.len() + + replacement_after.len() + + suffix.len(), + ); new_data.push_str(prefix); new_data.push_str(replacement_before); new_data.push_str(&arg); @@ -223,8 +225,8 @@ impl CharacterDataMethods for CharacterData { self.content_changed(); // Steps 8-11. let node = self.upcast::<Node>(); - node.ranges().replace_code_units( - node, offset, count, arg.encode_utf16().count() as u32); + node.ranges() + .replace_code_units(node, offset, count, arg.encode_utf16().count() as u32); Ok(()) } @@ -251,12 +253,18 @@ impl CharacterDataMethods for CharacterData { // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling fn GetPreviousElementSibling(&self) -> Option<DomRoot<Element>> { - self.upcast::<Node>().preceding_siblings().filter_map(DomRoot::downcast).next() + self.upcast::<Node>() + .preceding_siblings() + .filter_map(DomRoot::downcast) + .next() } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling fn GetNextElementSibling(&self) -> Option<DomRoot<Element>> { - self.upcast::<Node>().following_siblings().filter_map(DomRoot::downcast).next() + self.upcast::<Node>() + .following_siblings() + .filter_map(DomRoot::downcast) + .next() } } @@ -305,13 +313,15 @@ fn split_at_utf16_code_unit_offset(s: &str, offset: u32) -> Result<(&str, Option if code_units == offset { if opts::get().replace_surrogates { debug_assert_eq!(c.len_utf8(), 4); - return Ok((&s[..i], Some(c), &s[i + c.len_utf8()..])) + return Ok((&s[..i], Some(c), &s[i + c.len_utf8()..])); } - panic!("\n\n\ - Would split a surrogate pair in CharacterData API.\n\ - If you see this in real content, please comment with the URL\n\ - on https://github.com/servo/servo/issues/6873\n\ - \n"); + panic!( + "\n\n\ + Would split a surrogate pair in CharacterData API.\n\ + If you see this in real content, please comment with the URL\n\ + on https://github.com/servo/servo/issues/6873\n\ + \n" + ); } code_units += 1; } diff --git a/components/script/dom/client.rs b/components/script/dom/client.rs index 7c68daecdb3..ff63979c4ef 100644 --- a/components/script/dom/client.rs +++ b/components/script/dom/client.rs @@ -21,7 +21,7 @@ pub struct Client { url: ServoUrl, frame_type: FrameType, #[ignore_malloc_size_of = "Defined in uuid"] - id: Uuid + id: Uuid, } impl Client { @@ -31,14 +31,16 @@ impl Client { active_worker: Default::default(), url: url, frame_type: FrameType::None, - id: Uuid::new_v4() + id: Uuid::new_v4(), } } pub fn new(window: &Window) -> DomRoot<Client> { - reflect_dom_object(Box::new(Client::new_inherited(window.get_url())), - window, - Wrap) + reflect_dom_object( + Box::new(Client::new_inherited(window.get_url())), + window, + Wrap, + ) } pub fn creation_url(&self) -> ServoUrl { diff --git a/components/script/dom/closeevent.rs b/components/script/dom/closeevent.rs index 1675d8b27e3..0c353b68188 100644 --- a/components/script/dom/closeevent.rs +++ b/components/script/dom/closeevent.rs @@ -34,45 +34,48 @@ impl CloseEvent { } pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<CloseEvent> { - reflect_dom_object(Box::new(CloseEvent::new_inherited(false, 0, DOMString::new())), - global, - CloseEventBinding::Wrap) + reflect_dom_object( + Box::new(CloseEvent::new_inherited(false, 0, DOMString::new())), + global, + CloseEventBinding::Wrap, + ) } - pub fn new(global: &GlobalScope, - type_: Atom, - bubbles: EventBubbles, - cancelable: EventCancelable, - wasClean: bool, - code: u16, - reason: DOMString) - -> DomRoot<CloseEvent> { + pub fn new( + global: &GlobalScope, + type_: Atom, + bubbles: EventBubbles, + cancelable: EventCancelable, + wasClean: bool, + code: u16, + reason: DOMString, + ) -> DomRoot<CloseEvent> { let event = Box::new(CloseEvent::new_inherited(wasClean, code, reason)); let ev = reflect_dom_object(event, global, CloseEventBinding::Wrap); { let event = ev.upcast::<Event>(); - event.init_event(type_, - bool::from(bubbles), - bool::from(cancelable)); + event.init_event(type_, bool::from(bubbles), bool::from(cancelable)); } ev } - pub fn Constructor(global: &GlobalScope, - type_: DOMString, - init: &CloseEventBinding::CloseEventInit) - -> Fallible<DomRoot<CloseEvent>> { + pub fn Constructor( + global: &GlobalScope, + type_: DOMString, + init: &CloseEventBinding::CloseEventInit, + ) -> Fallible<DomRoot<CloseEvent>> { let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::from(init.parent.cancelable); - Ok(CloseEvent::new(global, - Atom::from(type_), - bubbles, - cancelable, - init.wasClean, - init.code, - init.reason.clone())) + Ok(CloseEvent::new( + global, + Atom::from(type_), + bubbles, + cancelable, + init.wasClean, + init.code, + init.reason.clone(), + )) } - } impl CloseEventMethods for CloseEvent { diff --git a/components/script/dom/comment.rs b/components/script/dom/comment.rs index 3eb6175e20c..9901a834a41 100644 --- a/components/script/dom/comment.rs +++ b/components/script/dom/comment.rs @@ -27,9 +27,11 @@ impl Comment { } pub fn new(text: DOMString, document: &Document) -> DomRoot<Comment> { - Node::reflect_node(Box::new(Comment::new_inherited(text, document)), - document, - CommentBinding::Wrap) + Node::reflect_node( + Box::new(Comment::new_inherited(text, document)), + document, + CommentBinding::Wrap, + ) } pub fn Constructor(window: &Window, data: DOMString) -> Fallible<DomRoot<Comment>> { diff --git a/components/script/dom/compositionevent.rs b/components/script/dom/compositionevent.rs index dc93427dbed..191572b51ab 100644 --- a/components/script/dom/compositionevent.rs +++ b/components/script/dom/compositionevent.rs @@ -19,34 +19,42 @@ pub struct CompositionEvent { } impl CompositionEvent { - pub fn new(window: &Window, - type_: DOMString, - can_bubble: bool, - cancelable: bool, - view: Option<&Window>, - detail: i32, - data: DOMString) -> DomRoot<CompositionEvent> { - let ev = reflect_dom_object(Box::new(CompositionEvent { - uievent: UIEvent::new_inherited(), - data: data, - }), - window, - CompositionEventBinding::Wrap); - ev.uievent.InitUIEvent(type_, can_bubble, cancelable, view, detail); + pub fn new( + window: &Window, + type_: DOMString, + can_bubble: bool, + cancelable: bool, + view: Option<&Window>, + detail: i32, + data: DOMString, + ) -> DomRoot<CompositionEvent> { + let ev = reflect_dom_object( + Box::new(CompositionEvent { + uievent: UIEvent::new_inherited(), + data: data, + }), + window, + CompositionEventBinding::Wrap, + ); + ev.uievent + .InitUIEvent(type_, can_bubble, cancelable, view, detail); ev } - pub fn Constructor(window: &Window, - type_: DOMString, - init: &CompositionEventBinding::CompositionEventInit) - -> Fallible<DomRoot<CompositionEvent>> { - let event = CompositionEvent::new(window, - type_, - init.parent.parent.bubbles, - init.parent.parent.cancelable, - init.parent.view.r(), - init.parent.detail, - init.data.clone()); + pub fn Constructor( + window: &Window, + type_: DOMString, + init: &CompositionEventBinding::CompositionEventInit, + ) -> Fallible<DomRoot<CompositionEvent>> { + let event = CompositionEvent::new( + window, + type_, + init.parent.parent.bubbles, + init.parent.parent.cancelable, + init.parent.view.r(), + init.parent.detail, + init.data.clone(), + ); Ok(event) } } diff --git a/components/script/dom/console.rs b/components/script/dom/console.rs index 7aa99c2fab6..410477a79d3 100644 --- a/components/script/dom/console.rs +++ b/components/script/dom/console.rs @@ -16,13 +16,14 @@ impl Console { fn send_to_devtools(global: &GlobalScope, level: LogLevel, message: DOMString) { if let Some(chan) = global.devtools_chan() { let console_message = prepare_message(level, message); - let worker_id = global.downcast::<WorkerGlobalScope>().map(|worker| { - worker.get_worker_id() - }); + let worker_id = global + .downcast::<WorkerGlobalScope>() + .map(|worker| worker.get_worker_id()); let devtools_message = ScriptToDevtoolsControlMsg::ConsoleAPI( global.pipeline_id(), console_message, - worker_id); + worker_id, + ); chan.send(devtools_message).unwrap(); } } @@ -33,7 +34,10 @@ impl Console { // we're finished with stdout. Since the stderr lock is reentrant, there is // no risk of deadlock if the callback ends up trying to write to stderr for // any reason. -fn with_stderr_lock<F>(f: F) where F: FnOnce() { +fn with_stderr_lock<F>(f: F) +where + F: FnOnce(), +{ let stderr = io::stderr(); let _handle = stderr.lock(); f() @@ -116,9 +120,7 @@ impl Console { pub fn TimeEnd(global: &GlobalScope, label: DOMString) { with_stderr_lock(move || { if let Ok(delta) = global.time_end(&label) { - let message = DOMString::from( - format!("{}: {}ms", label, delta) - ); + let message = DOMString::from(format!("{}: {}ms", label, delta)); println!("{}", message); Self::send_to_devtools(global, LogLevel::Log, message); }; diff --git a/components/script/dom/create.rs b/components/script/dom/create.rs index 64116663a84..94fe6bd1457 100644 --- a/components/script/dom/create.rs +++ b/components/script/dom/create.rs @@ -84,10 +84,11 @@ use js::jsapi::JSAutoCompartment; use script_thread::ScriptThread; use servo_config::prefs::PREFS; -fn create_svg_element(name: QualName, - prefix: Option<Prefix>, - document: &Document) - -> DomRoot<Element> { +fn create_svg_element( + name: QualName, + prefix: Option<Prefix>, + document: &Document, +) -> DomRoot<Element> { assert_eq!(name.ns, ns!(svg)); macro_rules! make( @@ -106,20 +107,21 @@ fn create_svg_element(name: QualName, } match name.local { - local_name!("svg") => make!(SVGSVGElement), - _ => Element::new(name.local, name.ns, prefix, document), + local_name!("svg") => make!(SVGSVGElement), + _ => Element::new(name.local, name.ns, prefix, document), } } // https://dom.spec.whatwg.org/#concept-create-element #[allow(unsafe_code)] -fn create_html_element(name: QualName, - prefix: Option<Prefix>, - is: Option<LocalName>, - document: &Document, - creator: ElementCreator, - mode: CustomElementCreationMode) - -> DomRoot<Element> { +fn create_html_element( + name: QualName, + prefix: Option<Prefix>, + is: Option<LocalName>, + document: &Document, + creator: ElementCreator, + mode: CustomElementCreationMode, +) -> DomRoot<Element> { assert_eq!(name.ns, ns!(html)); // Step 4 @@ -129,8 +131,11 @@ fn create_html_element(name: QualName, if definition.is_autonomous() { match mode { CustomElementCreationMode::Asynchronous => { - let result = DomRoot::upcast::<Element>( - HTMLElement::new(name.local.clone(), prefix.clone(), document)); + let result = DomRoot::upcast::<Element>(HTMLElement::new( + name.local.clone(), + prefix.clone(), + document, + )); result.set_custom_element_state(CustomElementState::Undefined); ScriptThread::enqueue_upgrade_reaction(&*result, definition); return result; @@ -144,19 +149,24 @@ fn create_html_element(name: QualName, }, Err(error) => { // Step 6. Recovering from exception. - let global = GlobalScope::current().unwrap_or_else(|| document.global()); + let global = + GlobalScope::current().unwrap_or_else(|| document.global()); let cx = global.get_cx(); // Step 6.1.1 unsafe { - let _ac = JSAutoCompartment::new(cx, global.reflector().get_jsobject().get()); + let _ac = JSAutoCompartment::new( + cx, + global.reflector().get_jsobject().get(), + ); throw_dom_exception(cx, &global, error); report_pending_exception(cx, true); } // Step 6.1.2 - let element = DomRoot::upcast::<Element>( - HTMLUnknownElement::new(local_name, prefix, document)); + let element = DomRoot::upcast::<Element>(HTMLUnknownElement::new( + local_name, prefix, document, + )); element.set_custom_element_state(CustomElementState::Failed); element }, @@ -170,11 +180,11 @@ fn create_html_element(name: QualName, element.set_custom_element_state(CustomElementState::Undefined); match mode { // Step 5.3 - CustomElementCreationMode::Synchronous => - upgrade_element(definition, &*element), + CustomElementCreationMode::Synchronous => upgrade_element(definition, &*element), // Step 5.4 - CustomElementCreationMode::Asynchronous => - ScriptThread::enqueue_upgrade_reaction(&*element, definition), + CustomElementCreationMode::Asynchronous => { + ScriptThread::enqueue_upgrade_reaction(&*element, definition) + }, } return element; } @@ -214,162 +224,163 @@ pub fn create_native_html_element( // Perhaps we should build a perfect hash from those IDs instead. // https://html.spec.whatwg.org/multipage/#elements-in-the-dom match name.local { - local_name!("a") => make!(HTMLAnchorElement), - local_name!("abbr") => make!(HTMLElement), - local_name!("acronym") => make!(HTMLElement), - local_name!("address") => make!(HTMLElement), - local_name!("area") => make!(HTMLAreaElement), - local_name!("article") => make!(HTMLElement), - local_name!("aside") => make!(HTMLElement), - local_name!("audio") => make!(HTMLAudioElement), - local_name!("b") => make!(HTMLElement), - local_name!("base") => make!(HTMLBaseElement), - local_name!("bdi") => make!(HTMLElement), - local_name!("bdo") => make!(HTMLElement), + local_name!("a") => make!(HTMLAnchorElement), + local_name!("abbr") => make!(HTMLElement), + local_name!("acronym") => make!(HTMLElement), + local_name!("address") => make!(HTMLElement), + local_name!("area") => make!(HTMLAreaElement), + local_name!("article") => make!(HTMLElement), + local_name!("aside") => make!(HTMLElement), + local_name!("audio") => make!(HTMLAudioElement), + local_name!("b") => make!(HTMLElement), + local_name!("base") => make!(HTMLBaseElement), + local_name!("bdi") => make!(HTMLElement), + local_name!("bdo") => make!(HTMLElement), // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:bgsound - local_name!("bgsound") => make!(HTMLUnknownElement), - local_name!("big") => make!(HTMLElement), + local_name!("bgsound") => make!(HTMLUnknownElement), + local_name!("big") => make!(HTMLElement), // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:blink - local_name!("blink") => make!(HTMLUnknownElement), + local_name!("blink") => make!(HTMLUnknownElement), // https://html.spec.whatwg.org/multipage/#the-blockquote-element local_name!("blockquote") => make!(HTMLQuoteElement), - local_name!("body") => make!(HTMLBodyElement), - local_name!("br") => make!(HTMLBRElement), - local_name!("button") => make!(HTMLButtonElement), - local_name!("canvas") => make!(HTMLCanvasElement), - local_name!("caption") => make!(HTMLTableCaptionElement), - local_name!("center") => make!(HTMLElement), - local_name!("cite") => make!(HTMLElement), - local_name!("code") => make!(HTMLElement), - local_name!("col") => make!(HTMLTableColElement), - local_name!("colgroup") => make!(HTMLTableColElement), - local_name!("data") => make!(HTMLDataElement), - local_name!("datalist") => make!(HTMLDataListElement), - local_name!("dd") => make!(HTMLElement), - local_name!("del") => make!(HTMLModElement), - local_name!("details") => make!(HTMLDetailsElement), - local_name!("dfn") => make!(HTMLElement), - local_name!("dialog") => make!(HTMLDialogElement), - local_name!("dir") => make!(HTMLDirectoryElement), - local_name!("div") => make!(HTMLDivElement), - local_name!("dl") => make!(HTMLDListElement), - local_name!("dt") => make!(HTMLElement), - local_name!("em") => make!(HTMLElement), - local_name!("embed") => make!(HTMLEmbedElement), - local_name!("fieldset") => make!(HTMLFieldSetElement), + local_name!("body") => make!(HTMLBodyElement), + local_name!("br") => make!(HTMLBRElement), + local_name!("button") => make!(HTMLButtonElement), + local_name!("canvas") => make!(HTMLCanvasElement), + local_name!("caption") => make!(HTMLTableCaptionElement), + local_name!("center") => make!(HTMLElement), + local_name!("cite") => make!(HTMLElement), + local_name!("code") => make!(HTMLElement), + local_name!("col") => make!(HTMLTableColElement), + local_name!("colgroup") => make!(HTMLTableColElement), + local_name!("data") => make!(HTMLDataElement), + local_name!("datalist") => make!(HTMLDataListElement), + local_name!("dd") => make!(HTMLElement), + local_name!("del") => make!(HTMLModElement), + local_name!("details") => make!(HTMLDetailsElement), + local_name!("dfn") => make!(HTMLElement), + local_name!("dialog") => make!(HTMLDialogElement), + local_name!("dir") => make!(HTMLDirectoryElement), + local_name!("div") => make!(HTMLDivElement), + local_name!("dl") => make!(HTMLDListElement), + local_name!("dt") => make!(HTMLElement), + local_name!("em") => make!(HTMLElement), + local_name!("embed") => make!(HTMLEmbedElement), + local_name!("fieldset") => make!(HTMLFieldSetElement), local_name!("figcaption") => make!(HTMLElement), - local_name!("figure") => make!(HTMLElement), - local_name!("font") => make!(HTMLFontElement), - local_name!("footer") => make!(HTMLElement), - local_name!("form") => make!(HTMLFormElement), - local_name!("frame") => make!(HTMLFrameElement), - local_name!("frameset") => make!(HTMLFrameSetElement), - local_name!("h1") => make!(HTMLHeadingElement, HeadingLevel::Heading1), - local_name!("h2") => make!(HTMLHeadingElement, HeadingLevel::Heading2), - local_name!("h3") => make!(HTMLHeadingElement, HeadingLevel::Heading3), - local_name!("h4") => make!(HTMLHeadingElement, HeadingLevel::Heading4), - local_name!("h5") => make!(HTMLHeadingElement, HeadingLevel::Heading5), - local_name!("h6") => make!(HTMLHeadingElement, HeadingLevel::Heading6), - local_name!("head") => make!(HTMLHeadElement), - local_name!("header") => make!(HTMLElement), - local_name!("hgroup") => make!(HTMLElement), - local_name!("hr") => make!(HTMLHRElement), - local_name!("html") => make!(HTMLHtmlElement), - local_name!("i") => make!(HTMLElement), - local_name!("iframe") => make!(HTMLIFrameElement), - local_name!("img") => make!(HTMLImageElement), - local_name!("input") => make!(HTMLInputElement), - local_name!("ins") => make!(HTMLModElement), + local_name!("figure") => make!(HTMLElement), + local_name!("font") => make!(HTMLFontElement), + local_name!("footer") => make!(HTMLElement), + local_name!("form") => make!(HTMLFormElement), + local_name!("frame") => make!(HTMLFrameElement), + local_name!("frameset") => make!(HTMLFrameSetElement), + local_name!("h1") => make!(HTMLHeadingElement, HeadingLevel::Heading1), + local_name!("h2") => make!(HTMLHeadingElement, HeadingLevel::Heading2), + local_name!("h3") => make!(HTMLHeadingElement, HeadingLevel::Heading3), + local_name!("h4") => make!(HTMLHeadingElement, HeadingLevel::Heading4), + local_name!("h5") => make!(HTMLHeadingElement, HeadingLevel::Heading5), + local_name!("h6") => make!(HTMLHeadingElement, HeadingLevel::Heading6), + local_name!("head") => make!(HTMLHeadElement), + local_name!("header") => make!(HTMLElement), + local_name!("hgroup") => make!(HTMLElement), + local_name!("hr") => make!(HTMLHRElement), + local_name!("html") => make!(HTMLHtmlElement), + local_name!("i") => make!(HTMLElement), + local_name!("iframe") => make!(HTMLIFrameElement), + local_name!("img") => make!(HTMLImageElement), + local_name!("input") => make!(HTMLInputElement), + local_name!("ins") => make!(HTMLModElement), // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:isindex-2 - local_name!("isindex") => make!(HTMLUnknownElement), - local_name!("kbd") => make!(HTMLElement), - local_name!("label") => make!(HTMLLabelElement), - local_name!("legend") => make!(HTMLLegendElement), - local_name!("li") => make!(HTMLLIElement), - local_name!("link") => make!(HTMLLinkElement, creator), + local_name!("isindex") => make!(HTMLUnknownElement), + local_name!("kbd") => make!(HTMLElement), + local_name!("label") => make!(HTMLLabelElement), + local_name!("legend") => make!(HTMLLegendElement), + local_name!("li") => make!(HTMLLIElement), + local_name!("link") => make!(HTMLLinkElement, creator), // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:listing - local_name!("listing") => make!(HTMLPreElement), - local_name!("main") => make!(HTMLElement), - local_name!("map") => make!(HTMLMapElement), - local_name!("mark") => make!(HTMLElement), - local_name!("marquee") => make!(HTMLElement), - local_name!("meta") => make!(HTMLMetaElement), - local_name!("meter") => make!(HTMLMeterElement), + local_name!("listing") => make!(HTMLPreElement), + local_name!("main") => make!(HTMLElement), + local_name!("map") => make!(HTMLMapElement), + local_name!("mark") => make!(HTMLElement), + local_name!("marquee") => make!(HTMLElement), + local_name!("meta") => make!(HTMLMetaElement), + local_name!("meter") => make!(HTMLMeterElement), // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:multicol - local_name!("multicol") => make!(HTMLUnknownElement), - local_name!("nav") => make!(HTMLElement), + local_name!("multicol") => make!(HTMLUnknownElement), + local_name!("nav") => make!(HTMLElement), // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:nextid - local_name!("nextid") => make!(HTMLUnknownElement), - local_name!("nobr") => make!(HTMLElement), - local_name!("noframes") => make!(HTMLElement), - local_name!("noscript") => make!(HTMLElement), - local_name!("object") => make!(HTMLObjectElement), - local_name!("ol") => make!(HTMLOListElement), - local_name!("optgroup") => make!(HTMLOptGroupElement), - local_name!("option") => make!(HTMLOptionElement), - local_name!("output") => make!(HTMLOutputElement), - local_name!("p") => make!(HTMLParagraphElement), - local_name!("param") => make!(HTMLParamElement), - local_name!("picture") => make!(HTMLPictureElement), - local_name!("plaintext") => make!(HTMLPreElement), - local_name!("pre") => make!(HTMLPreElement), - local_name!("progress") => make!(HTMLProgressElement), - local_name!("q") => make!(HTMLQuoteElement), - local_name!("rp") => make!(HTMLElement), - local_name!("rt") => make!(HTMLElement), - local_name!("ruby") => make!(HTMLElement), - local_name!("s") => make!(HTMLElement), - local_name!("samp") => make!(HTMLElement), - local_name!("script") => make!(HTMLScriptElement, creator), - local_name!("section") => make!(HTMLElement), - local_name!("select") => make!(HTMLSelectElement), - local_name!("small") => make!(HTMLElement), - local_name!("source") => make!(HTMLSourceElement), + local_name!("nextid") => make!(HTMLUnknownElement), + local_name!("nobr") => make!(HTMLElement), + local_name!("noframes") => make!(HTMLElement), + local_name!("noscript") => make!(HTMLElement), + local_name!("object") => make!(HTMLObjectElement), + local_name!("ol") => make!(HTMLOListElement), + local_name!("optgroup") => make!(HTMLOptGroupElement), + local_name!("option") => make!(HTMLOptionElement), + local_name!("output") => make!(HTMLOutputElement), + local_name!("p") => make!(HTMLParagraphElement), + local_name!("param") => make!(HTMLParamElement), + local_name!("picture") => make!(HTMLPictureElement), + local_name!("plaintext") => make!(HTMLPreElement), + local_name!("pre") => make!(HTMLPreElement), + local_name!("progress") => make!(HTMLProgressElement), + local_name!("q") => make!(HTMLQuoteElement), + local_name!("rp") => make!(HTMLElement), + local_name!("rt") => make!(HTMLElement), + local_name!("ruby") => make!(HTMLElement), + local_name!("s") => make!(HTMLElement), + local_name!("samp") => make!(HTMLElement), + local_name!("script") => make!(HTMLScriptElement, creator), + local_name!("section") => make!(HTMLElement), + local_name!("select") => make!(HTMLSelectElement), + local_name!("small") => make!(HTMLElement), + local_name!("source") => make!(HTMLSourceElement), // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:spacer - local_name!("spacer") => make!(HTMLUnknownElement), - local_name!("span") => make!(HTMLSpanElement), - local_name!("strike") => make!(HTMLElement), - local_name!("strong") => make!(HTMLElement), - local_name!("style") => make!(HTMLStyleElement, creator), - local_name!("sub") => make!(HTMLElement), - local_name!("summary") => make!(HTMLElement), - local_name!("sup") => make!(HTMLElement), - local_name!("table") => make!(HTMLTableElement), - local_name!("tbody") => make!(HTMLTableSectionElement), - local_name!("td") => make!(HTMLTableDataCellElement), - local_name!("template") => make!(HTMLTemplateElement), - local_name!("textarea") => make!(HTMLTextAreaElement), + local_name!("spacer") => make!(HTMLUnknownElement), + local_name!("span") => make!(HTMLSpanElement), + local_name!("strike") => make!(HTMLElement), + local_name!("strong") => make!(HTMLElement), + local_name!("style") => make!(HTMLStyleElement, creator), + local_name!("sub") => make!(HTMLElement), + local_name!("summary") => make!(HTMLElement), + local_name!("sup") => make!(HTMLElement), + local_name!("table") => make!(HTMLTableElement), + local_name!("tbody") => make!(HTMLTableSectionElement), + local_name!("td") => make!(HTMLTableDataCellElement), + local_name!("template") => make!(HTMLTemplateElement), + local_name!("textarea") => make!(HTMLTextAreaElement), // https://html.spec.whatwg.org/multipage/#the-tfoot-element:concept-element-dom - local_name!("tfoot") => make!(HTMLTableSectionElement), - local_name!("th") => make!(HTMLTableHeaderCellElement), + local_name!("tfoot") => make!(HTMLTableSectionElement), + local_name!("th") => make!(HTMLTableHeaderCellElement), // https://html.spec.whatwg.org/multipage/#the-thead-element:concept-element-dom - local_name!("thead") => make!(HTMLTableSectionElement), - local_name!("time") => make!(HTMLTimeElement), - local_name!("title") => make!(HTMLTitleElement), - local_name!("tr") => make!(HTMLTableRowElement), - local_name!("tt") => make!(HTMLElement), - local_name!("track") => make!(HTMLTrackElement), - local_name!("u") => make!(HTMLElement), - local_name!("ul") => make!(HTMLUListElement), - local_name!("var") => make!(HTMLElement), - local_name!("video") => make!(HTMLVideoElement), - local_name!("wbr") => make!(HTMLElement), - local_name!("xmp") => make!(HTMLPreElement), + local_name!("thead") => make!(HTMLTableSectionElement), + local_name!("time") => make!(HTMLTimeElement), + local_name!("title") => make!(HTMLTitleElement), + local_name!("tr") => make!(HTMLTableRowElement), + local_name!("tt") => make!(HTMLElement), + local_name!("track") => make!(HTMLTrackElement), + local_name!("u") => make!(HTMLElement), + local_name!("ul") => make!(HTMLUListElement), + local_name!("var") => make!(HTMLElement), + local_name!("video") => make!(HTMLVideoElement), + local_name!("wbr") => make!(HTMLElement), + local_name!("xmp") => make!(HTMLPreElement), _ if is_valid_custom_element_name(&*name.local) => make!(HTMLElement), - _ => make!(HTMLUnknownElement), + _ => make!(HTMLUnknownElement), } } -pub fn create_element(name: QualName, - is: Option<LocalName>, - document: &Document, - creator: ElementCreator, - mode: CustomElementCreationMode) - -> DomRoot<Element> { +pub fn create_element( + name: QualName, + is: Option<LocalName>, + document: &Document, + creator: ElementCreator, + mode: CustomElementCreationMode, +) -> DomRoot<Element> { let prefix = name.prefix.clone(); match name.ns { - ns!(html) => create_html_element(name, prefix, is, document, creator, mode), - ns!(svg) => create_svg_element(name, prefix, document), - _ => Element::new(name.local, name.ns, prefix, document) + ns!(html) => create_html_element(name, prefix, is, document, creator, mode), + ns!(svg) => create_svg_element(name, prefix, document), + _ => Element::new(name.local, name.ns, prefix, document), } } diff --git a/components/script/dom/crypto.rs b/components/script/dom/crypto.rs index 2ee87a1719b..cc17c8a00f3 100644 --- a/components/script/dom/crypto.rs +++ b/components/script/dom/crypto.rs @@ -36,17 +36,22 @@ impl Crypto { } pub fn new(global: &GlobalScope) -> DomRoot<Crypto> { - reflect_dom_object(Box::new(Crypto::new_inherited()), global, CryptoBinding::Wrap) + reflect_dom_object( + Box::new(Crypto::new_inherited()), + global, + CryptoBinding::Wrap, + ) } } impl CryptoMethods for Crypto { #[allow(unsafe_code)] // https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#Crypto-method-getRandomValues - unsafe fn GetRandomValues(&self, - _cx: *mut JSContext, - mut input: CustomAutoRooterGuard<ArrayBufferView>) - -> Fallible<NonNull<JSObject>> { + unsafe fn GetRandomValues( + &self, + _cx: *mut JSContext, + mut input: CustomAutoRooterGuard<ArrayBufferView>, + ) -> Fallible<NonNull<JSObject>> { let array_type = input.get_array_type(); if !is_integer_buffer(array_type) { diff --git a/components/script/dom/cssconditionrule.rs b/components/script/dom/cssconditionrule.rs index 5d07722c8f9..beef32f8a42 100644 --- a/components/script/dom/cssconditionrule.rs +++ b/components/script/dom/cssconditionrule.rs @@ -20,8 +20,10 @@ pub struct CSSConditionRule { } impl CSSConditionRule { - pub fn new_inherited(parent_stylesheet: &CSSStyleSheet, - rules: Arc<Locked<StyleCssRules>>) -> CSSConditionRule { + pub fn new_inherited( + parent_stylesheet: &CSSStyleSheet, + rules: Arc<Locked<StyleCssRules>>, + ) -> CSSConditionRule { CSSConditionRule { cssgroupingrule: CSSGroupingRule::new_inherited(parent_stylesheet, rules), } diff --git a/components/script/dom/cssfontfacerule.rs b/components/script/dom/cssfontfacerule.rs index 8f2970abc39..5865ec76008 100644 --- a/components/script/dom/cssfontfacerule.rs +++ b/components/script/dom/cssfontfacerule.rs @@ -22,8 +22,10 @@ pub struct CSSFontFaceRule { } impl CSSFontFaceRule { - fn new_inherited(parent_stylesheet: &CSSStyleSheet, fontfacerule: Arc<Locked<FontFaceRule>>) - -> CSSFontFaceRule { + fn new_inherited( + parent_stylesheet: &CSSStyleSheet, + fontfacerule: Arc<Locked<FontFaceRule>>, + ) -> CSSFontFaceRule { CSSFontFaceRule { cssrule: CSSRule::new_inherited(parent_stylesheet), fontfacerule: fontfacerule, @@ -31,11 +33,19 @@ impl CSSFontFaceRule { } #[allow(unrooted_must_root)] - pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, - fontfacerule: Arc<Locked<FontFaceRule>>) -> DomRoot<CSSFontFaceRule> { - reflect_dom_object(Box::new(CSSFontFaceRule::new_inherited(parent_stylesheet, fontfacerule)), - window, - CSSFontFaceRuleBinding::Wrap) + pub fn new( + window: &Window, + parent_stylesheet: &CSSStyleSheet, + fontfacerule: Arc<Locked<FontFaceRule>>, + ) -> DomRoot<CSSFontFaceRule> { + reflect_dom_object( + Box::new(CSSFontFaceRule::new_inherited( + parent_stylesheet, + fontfacerule, + )), + window, + CSSFontFaceRuleBinding::Wrap, + ) } } @@ -47,6 +57,9 @@ impl SpecificCSSRule for CSSFontFaceRule { fn get_css(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); - self.fontfacerule.read_with(&guard).to_css_string(&guard).into() + self.fontfacerule + .read_with(&guard) + .to_css_string(&guard) + .into() } } diff --git a/components/script/dom/cssgroupingrule.rs b/components/script/dom/cssgroupingrule.rs index 21c744118ea..9324035b0b0 100644 --- a/components/script/dom/cssgroupingrule.rs +++ b/components/script/dom/cssgroupingrule.rs @@ -25,8 +25,10 @@ pub struct CSSGroupingRule { } impl CSSGroupingRule { - pub fn new_inherited(parent_stylesheet: &CSSStyleSheet, - rules: Arc<Locked<StyleCssRules>>) -> CSSGroupingRule { + pub fn new_inherited( + parent_stylesheet: &CSSStyleSheet, + rules: Arc<Locked<StyleCssRules>>, + ) -> CSSGroupingRule { CSSGroupingRule { cssrule: CSSRule::new_inherited(parent_stylesheet), rules: rules, @@ -36,9 +38,13 @@ impl CSSGroupingRule { fn rulelist(&self) -> DomRoot<CSSRuleList> { let parent_stylesheet = self.upcast::<CSSRule>().parent_stylesheet(); - self.rulelist.or_init(|| CSSRuleList::new(self.global().as_window(), - parent_stylesheet, - RulesSource::Rules(self.rules.clone()))) + self.rulelist.or_init(|| { + CSSRuleList::new( + self.global().as_window(), + parent_stylesheet, + RulesSource::Rules(self.rules.clone()), + ) + }) } pub fn parent_stylesheet(&self) -> &CSSStyleSheet { diff --git a/components/script/dom/cssimportrule.rs b/components/script/dom/cssimportrule.rs index 989917700ac..c8675c0457b 100644 --- a/components/script/dom/cssimportrule.rs +++ b/components/script/dom/cssimportrule.rs @@ -22,9 +22,10 @@ pub struct CSSImportRule { } impl CSSImportRule { - fn new_inherited(parent_stylesheet: &CSSStyleSheet, - import_rule: Arc<Locked<ImportRule>>) - -> Self { + fn new_inherited( + parent_stylesheet: &CSSStyleSheet, + import_rule: Arc<Locked<ImportRule>>, + ) -> Self { CSSImportRule { cssrule: CSSRule::new_inherited(parent_stylesheet), import_rule: import_rule, @@ -32,12 +33,16 @@ impl CSSImportRule { } #[allow(unrooted_must_root)] - pub fn new(window: &Window, - parent_stylesheet: &CSSStyleSheet, - import_rule: Arc<Locked<ImportRule>>) -> DomRoot<Self> { - reflect_dom_object(Box::new(Self::new_inherited(parent_stylesheet, import_rule)), - window, - CSSImportRuleBinding::Wrap) + pub fn new( + window: &Window, + parent_stylesheet: &CSSStyleSheet, + import_rule: Arc<Locked<ImportRule>>, + ) -> DomRoot<Self> { + reflect_dom_object( + Box::new(Self::new_inherited(parent_stylesheet, import_rule)), + window, + CSSImportRuleBinding::Wrap, + ) } } @@ -49,6 +54,9 @@ impl SpecificCSSRule for CSSImportRule { fn get_css(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); - self.import_rule.read_with(&guard).to_css_string(&guard).into() + self.import_rule + .read_with(&guard) + .to_css_string(&guard) + .into() } } diff --git a/components/script/dom/csskeyframerule.rs b/components/script/dom/csskeyframerule.rs index 63ec6e1d016..7d579447491 100644 --- a/components/script/dom/csskeyframerule.rs +++ b/components/script/dom/csskeyframerule.rs @@ -25,8 +25,10 @@ pub struct CSSKeyframeRule { } impl CSSKeyframeRule { - fn new_inherited(parent_stylesheet: &CSSStyleSheet, keyframerule: Arc<Locked<Keyframe>>) - -> CSSKeyframeRule { + fn new_inherited( + parent_stylesheet: &CSSStyleSheet, + keyframerule: Arc<Locked<Keyframe>>, + ) -> CSSKeyframeRule { CSSKeyframeRule { cssrule: CSSRule::new_inherited(parent_stylesheet), keyframerule: keyframerule, @@ -35,11 +37,19 @@ impl CSSKeyframeRule { } #[allow(unrooted_must_root)] - pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, - keyframerule: Arc<Locked<Keyframe>>) -> DomRoot<CSSKeyframeRule> { - reflect_dom_object(Box::new(CSSKeyframeRule::new_inherited(parent_stylesheet, keyframerule)), - window, - CSSKeyframeRuleBinding::Wrap) + pub fn new( + window: &Window, + parent_stylesheet: &CSSStyleSheet, + keyframerule: Arc<Locked<Keyframe>>, + ) -> DomRoot<CSSKeyframeRule> { + reflect_dom_object( + Box::new(CSSKeyframeRule::new_inherited( + parent_stylesheet, + keyframerule, + )), + window, + CSSKeyframeRuleBinding::Wrap, + ) } } @@ -69,6 +79,9 @@ impl SpecificCSSRule for CSSKeyframeRule { fn get_css(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); - self.keyframerule.read_with(&guard).to_css_string(&guard).into() + self.keyframerule + .read_with(&guard) + .to_css_string(&guard) + .into() } } diff --git a/components/script/dom/csskeyframesrule.rs b/components/script/dom/csskeyframesrule.rs index 7f1c212057d..4c8902c6edd 100644 --- a/components/script/dom/csskeyframesrule.rs +++ b/components/script/dom/csskeyframesrule.rs @@ -30,8 +30,10 @@ pub struct CSSKeyframesRule { } impl CSSKeyframesRule { - fn new_inherited(parent_stylesheet: &CSSStyleSheet, keyframesrule: Arc<Locked<KeyframesRule>>) - -> CSSKeyframesRule { + fn new_inherited( + parent_stylesheet: &CSSStyleSheet, + keyframesrule: Arc<Locked<KeyframesRule>>, + ) -> CSSKeyframesRule { CSSKeyframesRule { cssrule: CSSRule::new_inherited(parent_stylesheet), keyframesrule: keyframesrule, @@ -40,19 +42,29 @@ impl CSSKeyframesRule { } #[allow(unrooted_must_root)] - pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, - keyframesrule: Arc<Locked<KeyframesRule>>) -> DomRoot<CSSKeyframesRule> { - reflect_dom_object(Box::new(CSSKeyframesRule::new_inherited(parent_stylesheet, keyframesrule)), - window, - CSSKeyframesRuleBinding::Wrap) + pub fn new( + window: &Window, + parent_stylesheet: &CSSStyleSheet, + keyframesrule: Arc<Locked<KeyframesRule>>, + ) -> DomRoot<CSSKeyframesRule> { + reflect_dom_object( + Box::new(CSSKeyframesRule::new_inherited( + parent_stylesheet, + keyframesrule, + )), + window, + CSSKeyframesRuleBinding::Wrap, + ) } fn rulelist(&self) -> DomRoot<CSSRuleList> { self.rulelist.or_init(|| { let parent_stylesheet = &self.upcast::<CSSRule>().parent_stylesheet(); - CSSRuleList::new(self.global().as_window(), - parent_stylesheet, - RulesSource::Keyframes(self.keyframesrule.clone())) + CSSRuleList::new( + self.global().as_window(), + parent_stylesheet, + RulesSource::Keyframes(self.keyframesrule.clone()), + ) }) } @@ -64,10 +76,11 @@ impl CSSKeyframesRule { let guard = self.cssrule.shared_lock().read(); // This finds the *last* element matching a selector // because that's the rule that applies. Thus, rposition - self.keyframesrule.read_with(&guard) - .keyframes.iter().rposition(|frame| { - frame.read_with(&guard).selector == sel - }) + self.keyframesrule + .read_with(&guard) + .keyframes + .iter() + .rposition(|frame| frame.read_with(&guard).selector == sel) } else { None } @@ -86,12 +99,15 @@ impl CSSKeyframesRuleMethods for CSSKeyframesRule { let rule = Keyframe::parse( &rule, &style_stylesheet.contents, - &style_stylesheet.shared_lock + &style_stylesheet.shared_lock, ); if let Ok(rule) = rule { let mut guard = self.cssrule.shared_lock().write(); - self.keyframesrule.write_with(&mut guard).keyframes.push(rule); + self.keyframesrule + .write_with(&mut guard) + .keyframes + .push(rule); self.rulelist().append_lazy_dom_rule(); } } @@ -105,9 +121,9 @@ impl CSSKeyframesRuleMethods for CSSKeyframesRule { // https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-findrule fn FindRule(&self, selector: DOMString) -> Option<DomRoot<CSSKeyframeRule>> { - self.find_rule(&selector).and_then(|idx| { - self.rulelist().item(idx as u32) - }).and_then(DomRoot::downcast) + self.find_rule(&selector) + .and_then(|idx| self.rulelist().item(idx as u32)) + .and_then(DomRoot::downcast) } // https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-name @@ -136,7 +152,10 @@ impl SpecificCSSRule for CSSKeyframesRule { fn get_css(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); - self.keyframesrule.read_with(&guard).to_css_string(&guard).into() + self.keyframesrule + .read_with(&guard) + .to_css_string(&guard) + .into() } fn deparent_children(&self) { diff --git a/components/script/dom/cssmediarule.rs b/components/script/dom/cssmediarule.rs index ccc803e4b42..9c8bc87d89b 100644 --- a/components/script/dom/cssmediarule.rs +++ b/components/script/dom/cssmediarule.rs @@ -31,8 +31,10 @@ pub struct CSSMediaRule { } impl CSSMediaRule { - fn new_inherited(parent_stylesheet: &CSSStyleSheet, mediarule: Arc<Locked<MediaRule>>) - -> CSSMediaRule { + fn new_inherited( + parent_stylesheet: &CSSStyleSheet, + mediarule: Arc<Locked<MediaRule>>, + ) -> CSSMediaRule { let guard = parent_stylesheet.shared_lock().read(); let list = mediarule.read_with(&guard).rules.clone(); CSSMediaRule { @@ -43,19 +45,26 @@ impl CSSMediaRule { } #[allow(unrooted_must_root)] - pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, - mediarule: Arc<Locked<MediaRule>>) -> DomRoot<CSSMediaRule> { - reflect_dom_object(Box::new(CSSMediaRule::new_inherited(parent_stylesheet, mediarule)), - window, - CSSMediaRuleBinding::Wrap) + pub fn new( + window: &Window, + parent_stylesheet: &CSSStyleSheet, + mediarule: Arc<Locked<MediaRule>>, + ) -> DomRoot<CSSMediaRule> { + reflect_dom_object( + Box::new(CSSMediaRule::new_inherited(parent_stylesheet, mediarule)), + window, + CSSMediaRuleBinding::Wrap, + ) } fn medialist(&self) -> DomRoot<MediaList> { self.medialist.or_init(|| { let guard = self.cssconditionrule.shared_lock().read(); - MediaList::new(self.global().as_window(), - self.cssconditionrule.parent_stylesheet(), - self.mediarule.read_with(&guard).media_queries.clone()) + MediaList::new( + self.global().as_window(), + self.cssconditionrule.parent_stylesheet(), + self.mediarule.read_with(&guard).media_queries.clone(), + ) }) } @@ -106,7 +115,10 @@ impl SpecificCSSRule for CSSMediaRule { fn get_css(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); - self.mediarule.read_with(&guard).to_css_string(&guard).into() + self.mediarule + .read_with(&guard) + .to_css_string(&guard) + .into() } } diff --git a/components/script/dom/cssnamespacerule.rs b/components/script/dom/cssnamespacerule.rs index f585f420732..b0340fecfeb 100644 --- a/components/script/dom/cssnamespacerule.rs +++ b/components/script/dom/cssnamespacerule.rs @@ -23,8 +23,10 @@ pub struct CSSNamespaceRule { } impl CSSNamespaceRule { - fn new_inherited(parent_stylesheet: &CSSStyleSheet, namespacerule: Arc<Locked<NamespaceRule>>) - -> CSSNamespaceRule { + fn new_inherited( + parent_stylesheet: &CSSStyleSheet, + namespacerule: Arc<Locked<NamespaceRule>>, + ) -> CSSNamespaceRule { CSSNamespaceRule { cssrule: CSSRule::new_inherited(parent_stylesheet), namespacerule: namespacerule, @@ -32,11 +34,19 @@ impl CSSNamespaceRule { } #[allow(unrooted_must_root)] - pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, - namespacerule: Arc<Locked<NamespaceRule>>) -> DomRoot<CSSNamespaceRule> { - reflect_dom_object(Box::new(CSSNamespaceRule::new_inherited(parent_stylesheet, namespacerule)), - window, - CSSNamespaceRuleBinding::Wrap) + pub fn new( + window: &Window, + parent_stylesheet: &CSSStyleSheet, + namespacerule: Arc<Locked<NamespaceRule>>, + ) -> DomRoot<CSSNamespaceRule> { + reflect_dom_object( + Box::new(CSSNamespaceRule::new_inherited( + parent_stylesheet, + namespacerule, + )), + window, + CSSNamespaceRuleBinding::Wrap, + ) } } @@ -44,8 +54,11 @@ impl CSSNamespaceRuleMethods for CSSNamespaceRule { // https://drafts.csswg.org/cssom/#dom-cssnamespacerule-prefix fn Prefix(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); - self.namespacerule.read_with(&guard).prefix - .as_ref().map(|s| s.to_string().into()) + self.namespacerule + .read_with(&guard) + .prefix + .as_ref() + .map(|s| s.to_string().into()) .unwrap_or(DOMString::new()) } @@ -64,6 +77,9 @@ impl SpecificCSSRule for CSSNamespaceRule { fn get_css(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); - self.namespacerule.read_with(&guard).to_css_string(&guard).into() + self.namespacerule + .read_with(&guard) + .to_css_string(&guard) + .into() } } diff --git a/components/script/dom/cssrule.rs b/components/script/dom/cssrule.rs index da867be8df0..71f8ab5844c 100644 --- a/components/script/dom/cssrule.rs +++ b/components/script/dom/cssrule.rs @@ -23,7 +23,6 @@ use std::cell::Cell; use style::shared_lock::SharedRwLock; use style::stylesheets::CssRule as StyleCssRule; - #[dom_struct] pub struct CSSRule { reflector_: Reflector, @@ -71,20 +70,39 @@ impl CSSRule { // Given a StyleCssRule, create a new instance of a derived class of // CSSRule based on which rule it is - pub fn new_specific(window: &Window, parent_stylesheet: &CSSStyleSheet, - rule: StyleCssRule) -> DomRoot<CSSRule> { + pub fn new_specific( + window: &Window, + parent_stylesheet: &CSSStyleSheet, + rule: StyleCssRule, + ) -> DomRoot<CSSRule> { // be sure to update the match in as_specific when this is updated match rule { - StyleCssRule::Import(s) => DomRoot::upcast(CSSImportRule::new(window, parent_stylesheet, s)), - StyleCssRule::Style(s) => DomRoot::upcast(CSSStyleRule::new(window, parent_stylesheet, s)), - StyleCssRule::FontFace(s) => DomRoot::upcast(CSSFontFaceRule::new(window, parent_stylesheet, s)), + StyleCssRule::Import(s) => { + DomRoot::upcast(CSSImportRule::new(window, parent_stylesheet, s)) + }, + StyleCssRule::Style(s) => { + DomRoot::upcast(CSSStyleRule::new(window, parent_stylesheet, s)) + }, + StyleCssRule::FontFace(s) => { + DomRoot::upcast(CSSFontFaceRule::new(window, parent_stylesheet, s)) + }, StyleCssRule::FontFeatureValues(_) => unimplemented!(), StyleCssRule::CounterStyle(_) => unimplemented!(), - StyleCssRule::Keyframes(s) => DomRoot::upcast(CSSKeyframesRule::new(window, parent_stylesheet, s)), - StyleCssRule::Media(s) => DomRoot::upcast(CSSMediaRule::new(window, parent_stylesheet, s)), - StyleCssRule::Namespace(s) => DomRoot::upcast(CSSNamespaceRule::new(window, parent_stylesheet, s)), - StyleCssRule::Viewport(s) => DomRoot::upcast(CSSViewportRule::new(window, parent_stylesheet, s)), - StyleCssRule::Supports(s) => DomRoot::upcast(CSSSupportsRule::new(window, parent_stylesheet, s)), + StyleCssRule::Keyframes(s) => { + DomRoot::upcast(CSSKeyframesRule::new(window, parent_stylesheet, s)) + }, + StyleCssRule::Media(s) => { + DomRoot::upcast(CSSMediaRule::new(window, parent_stylesheet, s)) + }, + StyleCssRule::Namespace(s) => { + DomRoot::upcast(CSSNamespaceRule::new(window, parent_stylesheet, s)) + }, + StyleCssRule::Viewport(s) => { + DomRoot::upcast(CSSViewportRule::new(window, parent_stylesheet, s)) + }, + StyleCssRule::Supports(s) => { + DomRoot::upcast(CSSSupportsRule::new(window, parent_stylesheet, s)) + }, StyleCssRule::Page(_) => unreachable!(), StyleCssRule::Document(_) => unimplemented!(), // TODO } diff --git a/components/script/dom/cssrulelist.rs b/components/script/dom/cssrulelist.rs index baa685d5a72..f6668763e59 100644 --- a/components/script/dom/cssrulelist.rs +++ b/components/script/dom/cssrulelist.rs @@ -39,7 +39,7 @@ pub struct CSSRuleList { parent_stylesheet: Dom<CSSStyleSheet>, #[ignore_malloc_size_of = "Arc"] rules: RulesSource, - dom_rules: DomRefCell<Vec<MutNullableDom<CSSRule>>> + dom_rules: DomRefCell<Vec<MutNullableDom<CSSRule>>>, } pub enum RulesSource { @@ -52,12 +52,18 @@ impl CSSRuleList { pub fn new_inherited(parent_stylesheet: &CSSStyleSheet, rules: RulesSource) -> CSSRuleList { let guard = parent_stylesheet.shared_lock().read(); let dom_rules = match rules { - RulesSource::Rules(ref rules) => { - rules.read_with(&guard).0.iter().map(|_| MutNullableDom::new(None)).collect() - } - RulesSource::Keyframes(ref rules) => { - rules.read_with(&guard).keyframes.iter().map(|_| MutNullableDom::new(None)).collect() - } + RulesSource::Rules(ref rules) => rules + .read_with(&guard) + .0 + .iter() + .map(|_| MutNullableDom::new(None)) + .collect(), + RulesSource::Keyframes(ref rules) => rules + .read_with(&guard) + .keyframes + .iter() + .map(|_| MutNullableDom::new(None)) + .collect(), }; CSSRuleList { @@ -69,11 +75,16 @@ impl CSSRuleList { } #[allow(unrooted_must_root)] - pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, - rules: RulesSource) -> DomRoot<CSSRuleList> { - reflect_dom_object(Box::new(CSSRuleList::new_inherited(parent_stylesheet, rules)), - window, - CSSRuleListBinding::Wrap) + pub fn new( + window: &Window, + parent_stylesheet: &CSSStyleSheet, + rules: RulesSource, + ) -> DomRoot<CSSRuleList> { + reflect_dom_object( + Box::new(CSSRuleList::new_inherited(parent_stylesheet, rules)), + window, + CSSRuleListBinding::Wrap, + ) } /// Should only be called for CssRules-backed rules. Use append_lazy_rule @@ -91,18 +102,21 @@ impl CSSRuleList { let parent_stylesheet = self.parent_stylesheet.style_stylesheet(); let new_rule = css_rules.with_raw_offset_arc(|arc| { - arc.insert_rule(&parent_stylesheet.shared_lock, - rule, - &parent_stylesheet.contents, - index, - nested, - None) + arc.insert_rule( + &parent_stylesheet.shared_lock, + rule, + &parent_stylesheet.contents, + index, + nested, + None, + ) })?; - let parent_stylesheet = &*self.parent_stylesheet; let dom_rule = CSSRule::new_specific(&window, parent_stylesheet, new_rule); - self.dom_rules.borrow_mut().insert(index, MutNullableDom::new(Some(&*dom_rule))); + self.dom_rules + .borrow_mut() + .insert(index, MutNullableDom::new(Some(&*dom_rule))); Ok(idx) } @@ -118,7 +132,7 @@ impl CSSRuleList { dom_rules[index].get().map(|r| r.detach()); dom_rules.remove(index); Ok(()) - } + }, RulesSource::Keyframes(ref kf) => { // https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-deleterule let mut dom_rules = self.dom_rules.borrow_mut(); @@ -126,7 +140,7 @@ impl CSSRuleList { dom_rules.remove(index); kf.write_with(&mut guard).keyframes.remove(index); Ok(()) - } + }, } } @@ -143,20 +157,17 @@ impl CSSRuleList { let parent_stylesheet = &self.parent_stylesheet; let guard = parent_stylesheet.shared_lock().read(); match self.rules { - RulesSource::Rules(ref rules) => { - CSSRule::new_specific(self.global().as_window(), - parent_stylesheet, - rules.read_with(&guard).0[idx as usize].clone()) - } - RulesSource::Keyframes(ref rules) => { - DomRoot::upcast(CSSKeyframeRule::new(self.global().as_window(), - parent_stylesheet, - rules.read_with(&guard) - .keyframes[idx as usize] - .clone())) - } + RulesSource::Rules(ref rules) => CSSRule::new_specific( + self.global().as_window(), + parent_stylesheet, + rules.read_with(&guard).0[idx as usize].clone(), + ), + RulesSource::Keyframes(ref rules) => DomRoot::upcast(CSSKeyframeRule::new( + self.global().as_window(), + parent_stylesheet, + rules.read_with(&guard).keyframes[idx as usize].clone(), + )), } - }) }) } @@ -190,4 +201,3 @@ impl CSSRuleListMethods for CSSRuleList { self.Item(index) } } - diff --git a/components/script/dom/cssstyledeclaration.rs b/components/script/dom/cssstyledeclaration.rs index 25beffd9549..795e401a5d3 100644 --- a/components/script/dom/cssstyledeclaration.rs +++ b/components/script/dom/cssstyledeclaration.rs @@ -36,16 +36,18 @@ pub struct CSSStyleDeclaration { #[must_root] pub enum CSSStyleOwner { Element(Dom<Element>), - CSSRule(Dom<CSSRule>, - #[ignore_malloc_size_of = "Arc"] - Arc<Locked<PropertyDeclarationBlock>>), + CSSRule( + Dom<CSSRule>, + #[ignore_malloc_size_of = "Arc"] Arc<Locked<PropertyDeclarationBlock>>, + ), } impl CSSStyleOwner { // Mutate the declaration block associated to this style owner, and // optionally indicate if it has changed (assumed to be true). fn mutate_associated_block<F, R>(&self, f: F) -> R - where F: FnOnce(&mut PropertyDeclarationBlock, &mut bool) -> R, + where + F: FnOnce(&mut PropertyDeclarationBlock, &mut bool) -> R, { // TODO(emilio): This has some duplication just to avoid dummy clones. // @@ -87,9 +89,10 @@ impl CSSStyleOwner { let guard = shared_lock.read(); let mut serialization = String::new(); pdb.read_with(&guard).to_css(&mut serialization).unwrap(); - el.set_attribute(&local_name!("style"), - AttrValue::Declaration(serialization, - pdb)); + el.set_attribute( + &local_name!("style"), + AttrValue::Declaration(serialization, pdb), + ); } } else { // Remember to put it back. @@ -97,7 +100,7 @@ impl CSSStyleOwner { } result - } + }, CSSStyleOwner::CSSRule(ref rule, ref pdb) => { let result = { let mut guard = rule.shared_lock().write(); @@ -106,34 +109,36 @@ impl CSSStyleOwner { if changed { // If this is changed, see also // CSSStyleRule::SetSelectorText, which does the same thing. - rule.global().as_window().Document().invalidate_stylesheets(); + rule.global() + .as_window() + .Document() + .invalidate_stylesheets(); } result - } + }, } } fn with_block<F, R>(&self, f: F) -> R - where F: FnOnce(&PropertyDeclarationBlock) -> R, + where + F: FnOnce(&PropertyDeclarationBlock) -> R, { match *self { - CSSStyleOwner::Element(ref el) => { - match *el.style_attribute().borrow() { - Some(ref pdb) => { - let document = document_from_node(&**el); - let guard = document.style_shared_lock().read(); - f(pdb.read_with(&guard)) - } - None => { - let pdb = PropertyDeclarationBlock::new(); - f(&pdb) - } - } - } + CSSStyleOwner::Element(ref el) => match *el.style_attribute().borrow() { + Some(ref pdb) => { + let document = document_from_node(&**el); + let guard = document.style_shared_lock().read(); + f(pdb.read_with(&guard)) + }, + None => { + let pdb = PropertyDeclarationBlock::new(); + f(&pdb) + }, + }, CSSStyleOwner::CSSRule(ref rule, ref pdb) => { let guard = rule.shared_lock().read(); f(pdb.read_with(&guard)) - } + }, } } @@ -147,9 +152,12 @@ impl CSSStyleOwner { fn base_url(&self) -> ServoUrl { match *self { CSSStyleOwner::Element(ref el) => window_from_node(&**el).Document().base_url(), - CSSStyleOwner::CSSRule(ref rule, _) => { - (*rule.parent_stylesheet().style_stylesheet().contents.url_data.read()).clone() - } + CSSStyleOwner::CSSRule(ref rule, _) => (*rule + .parent_stylesheet() + .style_stylesheet() + .contents + .url_data + .read()).clone(), } } } @@ -181,10 +189,7 @@ macro_rules! css_properties( ); ); -fn remove_property( - decls: &mut PropertyDeclarationBlock, - id: &PropertyId, -) -> bool { +fn remove_property(decls: &mut PropertyDeclarationBlock, id: &PropertyId) -> bool { let first_declaration = decls.first_declaration_to_remove(id); let first_declaration = match first_declaration { Some(i) => i, @@ -196,10 +201,11 @@ fn remove_property( impl CSSStyleDeclaration { #[allow(unrooted_must_root)] - pub fn new_inherited(owner: CSSStyleOwner, - pseudo: Option<PseudoElement>, - modification_access: CSSModificationAccess) - -> CSSStyleDeclaration { + pub fn new_inherited( + owner: CSSStyleOwner, + pseudo: Option<PseudoElement>, + modification_access: CSSModificationAccess, + ) -> CSSStyleDeclaration { CSSStyleDeclaration { reflector_: Reflector::new(), owner: owner, @@ -209,22 +215,28 @@ impl CSSStyleDeclaration { } #[allow(unrooted_must_root)] - pub fn new(global: &Window, - owner: CSSStyleOwner, - pseudo: Option<PseudoElement>, - modification_access: CSSModificationAccess) - -> DomRoot<CSSStyleDeclaration> { + pub fn new( + global: &Window, + owner: CSSStyleOwner, + pseudo: Option<PseudoElement>, + modification_access: CSSModificationAccess, + ) -> DomRoot<CSSStyleDeclaration> { reflect_dom_object( - Box::new(CSSStyleDeclaration::new_inherited(owner, pseudo, modification_access)), + Box::new(CSSStyleDeclaration::new_inherited( + owner, + pseudo, + modification_access, + )), global, - CSSStyleDeclarationBinding::Wrap + CSSStyleDeclarationBinding::Wrap, ) } fn get_computed_style(&self, property: PropertyId) -> DOMString { match self.owner { - CSSStyleOwner::CSSRule(..) => - panic!("get_computed_style called on CSSStyleDeclaration with a CSSRule owner"), + CSSStyleOwner::CSSRule(..) => { + panic!("get_computed_style called on CSSStyleDeclaration with a CSSRule owner") + }, CSSStyleOwner::Element(ref el) => { let node = el.upcast::<Node>(); if !node.is_in_doc() { @@ -234,7 +246,7 @@ impl CSSStyleDeclaration { } let addr = node.to_trusted_node_address(); window_from_node(node).resolved_style_query(addr, self.pseudo.clone(), property) - } + }, } } @@ -277,7 +289,7 @@ impl CSSStyleDeclaration { _ => { *changed = false; return Ok(()); - } + }, }; // Step 5 @@ -300,12 +312,11 @@ impl CSSStyleDeclaration { Err(_) => { *changed = false; return Ok(()); - } + }, } let mut updates = Default::default(); - *changed = - pdb.prepare_for_update(&declarations, importance, &mut updates); + *changed = pdb.prepare_for_update(&declarations, importance, &mut updates); if !*changed { return Ok(()); @@ -323,9 +334,7 @@ impl CSSStyleDeclaration { impl CSSStyleDeclarationMethods for CSSStyleDeclaration { // https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-length fn Length(&self) -> u32 { - self.owner.with_block(|pdb| { - pdb.declarations().len() as u32 - }) + self.owner.with_block(|pdb| pdb.declarations().len() as u32) } // https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-item @@ -360,11 +369,12 @@ impl CSSStyleDeclarationMethods for CSSStyleDeclaration { } // https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-setproperty - fn SetProperty(&self, - property: DOMString, - value: DOMString, - priority: DOMString) - -> ErrorResult { + fn SetProperty( + &self, + property: DOMString, + value: DOMString, + priority: DOMString, + ) -> ErrorResult { // Step 3 let id = match PropertyId::parse_enabled_for_all_content(&property) { Ok(id) => id, @@ -444,10 +454,12 @@ impl CSSStyleDeclarationMethods for CSSStyleDeclaration { let quirks_mode = window.Document().quirks_mode(); self.owner.mutate_associated_block(|pdb, _changed| { // Step 3 - *pdb = parse_style_attribute(&value, - &self.owner.base_url(), - window.css_error_reporter(), - quirks_mode); + *pdb = parse_style_attribute( + &value, + &self.owner.base_url(), + window.css_error_reporter(), + quirks_mode, + ); }); Ok(()) diff --git a/components/script/dom/cssstylerule.rs b/components/script/dom/cssstylerule.rs index 0e9f001dc05..788b72927b5 100644 --- a/components/script/dom/cssstylerule.rs +++ b/components/script/dom/cssstylerule.rs @@ -31,8 +31,10 @@ pub struct CSSStyleRule { } impl CSSStyleRule { - fn new_inherited(parent_stylesheet: &CSSStyleSheet, stylerule: Arc<Locked<StyleRule>>) - -> CSSStyleRule { + fn new_inherited( + parent_stylesheet: &CSSStyleSheet, + stylerule: Arc<Locked<StyleRule>>, + ) -> CSSStyleRule { CSSStyleRule { cssrule: CSSRule::new_inherited(parent_stylesheet), stylerule: stylerule, @@ -41,11 +43,16 @@ impl CSSStyleRule { } #[allow(unrooted_must_root)] - pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, - stylerule: Arc<Locked<StyleRule>>) -> DomRoot<CSSStyleRule> { - reflect_dom_object(Box::new(CSSStyleRule::new_inherited(parent_stylesheet, stylerule)), - window, - CSSStyleRuleBinding::Wrap) + pub fn new( + window: &Window, + parent_stylesheet: &CSSStyleSheet, + stylerule: Arc<Locked<StyleRule>>, + ) -> DomRoot<CSSStyleRule> { + reflect_dom_object( + Box::new(CSSStyleRule::new_inherited(parent_stylesheet, stylerule)), + window, + CSSStyleRuleBinding::Wrap, + ) } } @@ -57,7 +64,10 @@ impl SpecificCSSRule for CSSStyleRule { fn get_css(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); - self.stylerule.read_with(&guard).to_css_string(&guard).into() + self.stylerule + .read_with(&guard) + .to_css_string(&guard) + .into() } } @@ -70,10 +80,10 @@ impl CSSStyleRuleMethods for CSSStyleRule { self.global().as_window(), CSSStyleOwner::CSSRule( Dom::from_ref(self.upcast()), - self.stylerule.read_with(&guard).block.clone() + self.stylerule.read_with(&guard).block.clone(), ), None, - CSSModificationAccess::ReadWrite + CSSModificationAccess::ReadWrite, ) }) } @@ -89,7 +99,13 @@ impl CSSStyleRuleMethods for CSSStyleRule { fn SetSelectorText(&self, value: DOMString) { // It's not clear from the spec if we should use the stylesheet's namespaces. // https://github.com/w3c/csswg-drafts/issues/1511 - let namespaces = self.cssrule.parent_stylesheet().style_stylesheet().contents.namespaces.read(); + let namespaces = self + .cssrule + .parent_stylesheet() + .style_stylesheet() + .contents + .namespaces + .read(); let parser = SelectorParser { stylesheet_origin: Origin::Author, namespaces: &namespaces, @@ -104,7 +120,10 @@ impl CSSStyleRuleMethods for CSSStyleRule { mem::swap(&mut stylerule.selectors, &mut s); // It seems like we will want to avoid having to invalidate all // stylesheets eventually! - self.global().as_window().Document().invalidate_stylesheets(); + self.global() + .as_window() + .Document() + .invalidate_stylesheets(); } } } diff --git a/components/script/dom/cssstylesheet.rs b/components/script/dom/cssstylesheet.rs index d393b1f3ff7..def0f26bc77 100644 --- a/components/script/dom/cssstylesheet.rs +++ b/components/script/dom/cssstylesheet.rs @@ -30,11 +30,13 @@ pub struct CSSStyleSheet { } impl CSSStyleSheet { - fn new_inherited(owner: &Element, - type_: DOMString, - href: Option<DOMString>, - title: Option<DOMString>, - stylesheet: Arc<StyleStyleSheet>) -> CSSStyleSheet { + fn new_inherited( + owner: &Element, + type_: DOMString, + href: Option<DOMString>, + title: Option<DOMString>, + stylesheet: Arc<StyleStyleSheet>, + ) -> CSSStyleSheet { CSSStyleSheet { stylesheet: StyleSheet::new_inherited(type_, href, title), owner: Dom::from_ref(owner), @@ -45,25 +47,27 @@ impl CSSStyleSheet { } #[allow(unrooted_must_root)] - pub fn new(window: &Window, - owner: &Element, - type_: DOMString, - href: Option<DOMString>, - title: Option<DOMString>, - stylesheet: Arc<StyleStyleSheet>) -> DomRoot<CSSStyleSheet> { - reflect_dom_object(Box::new(CSSStyleSheet::new_inherited(owner, type_, href, title, stylesheet)), - window, - CSSStyleSheetBinding::Wrap) + pub fn new( + window: &Window, + owner: &Element, + type_: DOMString, + href: Option<DOMString>, + title: Option<DOMString>, + stylesheet: Arc<StyleStyleSheet>, + ) -> DomRoot<CSSStyleSheet> { + reflect_dom_object( + Box::new(CSSStyleSheet::new_inherited( + owner, type_, href, title, stylesheet, + )), + window, + CSSStyleSheetBinding::Wrap, + ) } fn rulelist(&self) -> DomRoot<CSSRuleList> { self.rulelist.or_init(|| { let rules = self.style_stylesheet.contents.rules.clone(); - CSSRuleList::new( - self.global().as_window(), - self, - RulesSource::Rules(rules) - ) + CSSRuleList::new(self.global().as_window(), self, RulesSource::Rules(rules)) }) } @@ -73,7 +77,10 @@ impl CSSStyleSheet { pub fn set_disabled(&self, disabled: bool) { if self.style_stylesheet.set_disabled(disabled) { - self.global().as_window().Document().invalidate_stylesheets(); + self.global() + .as_window() + .Document() + .invalidate_stylesheets(); } } @@ -104,7 +111,8 @@ impl CSSStyleSheetMethods for CSSStyleSheet { if !self.origin_clean.get() { return Err(Error::Security); } - self.rulelist().insert_rule(&rule, index, /* nested */ false) + self.rulelist() + .insert_rule(&rule, index, /* nested */ false) } // https://drafts.csswg.org/cssom/#dom-cssstylesheet-deleterule @@ -115,4 +123,3 @@ impl CSSStyleSheetMethods for CSSStyleSheet { self.rulelist().remove_rule(index) } } - diff --git a/components/script/dom/cssstylevalue.rs b/components/script/dom/cssstylevalue.rs index e440a428cd2..2ecdbbe357f 100644 --- a/components/script/dom/cssstylevalue.rs +++ b/components/script/dom/cssstylevalue.rs @@ -48,7 +48,9 @@ impl CSSStyleValue { pub fn get_url(&self, base_url: ServoUrl) -> Option<ServoUrl> { let mut input = ParserInput::new(&*self.value); let mut parser = Parser::new(&mut input); - parser.expect_url().ok() + parser + .expect_url() + .ok() .and_then(|string| base_url.join(&*string).ok()) } } diff --git a/components/script/dom/csssupportsrule.rs b/components/script/dom/csssupportsrule.rs index 8b66fbe76cf..136a742e0e7 100644 --- a/components/script/dom/csssupportsrule.rs +++ b/components/script/dom/csssupportsrule.rs @@ -28,8 +28,10 @@ pub struct CSSSupportsRule { } impl CSSSupportsRule { - fn new_inherited(parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>) - -> CSSSupportsRule { + fn new_inherited( + parent_stylesheet: &CSSStyleSheet, + supportsrule: Arc<Locked<SupportsRule>>, + ) -> CSSSupportsRule { let guard = parent_stylesheet.shared_lock().read(); let list = supportsrule.read_with(&guard).rules.clone(); CSSSupportsRule { @@ -39,11 +41,19 @@ impl CSSSupportsRule { } #[allow(unrooted_must_root)] - pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, - supportsrule: Arc<Locked<SupportsRule>>) -> DomRoot<CSSSupportsRule> { - reflect_dom_object(Box::new(CSSSupportsRule::new_inherited(parent_stylesheet, supportsrule)), - window, - CSSSupportsRuleBinding::Wrap) + pub fn new( + window: &Window, + parent_stylesheet: &CSSStyleSheet, + supportsrule: Arc<Locked<SupportsRule>>, + ) -> DomRoot<CSSSupportsRule> { + reflect_dom_object( + Box::new(CSSSupportsRule::new_inherited( + parent_stylesheet, + supportsrule, + )), + window, + CSSSupportsRuleBinding::Wrap, + ) } /// <https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface> @@ -88,6 +98,9 @@ impl SpecificCSSRule for CSSSupportsRule { fn get_css(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); - self.supportsrule.read_with(&guard).to_css_string(&guard).into() + self.supportsrule + .read_with(&guard) + .to_css_string(&guard) + .into() } } diff --git a/components/script/dom/cssviewportrule.rs b/components/script/dom/cssviewportrule.rs index 89e523cdc39..8f0dbaa8c15 100644 --- a/components/script/dom/cssviewportrule.rs +++ b/components/script/dom/cssviewportrule.rs @@ -22,7 +22,10 @@ pub struct CSSViewportRule { } impl CSSViewportRule { - fn new_inherited(parent_stylesheet: &CSSStyleSheet, viewportrule: Arc<Locked<ViewportRule>>) -> CSSViewportRule { + fn new_inherited( + parent_stylesheet: &CSSStyleSheet, + viewportrule: Arc<Locked<ViewportRule>>, + ) -> CSSViewportRule { CSSViewportRule { cssrule: CSSRule::new_inherited(parent_stylesheet), viewportrule: viewportrule, @@ -30,11 +33,19 @@ impl CSSViewportRule { } #[allow(unrooted_must_root)] - pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, - viewportrule: Arc<Locked<ViewportRule>>) -> DomRoot<CSSViewportRule> { - reflect_dom_object(Box::new(CSSViewportRule::new_inherited(parent_stylesheet, viewportrule)), - window, - CSSViewportRuleBinding::Wrap) + pub fn new( + window: &Window, + parent_stylesheet: &CSSStyleSheet, + viewportrule: Arc<Locked<ViewportRule>>, + ) -> DomRoot<CSSViewportRule> { + reflect_dom_object( + Box::new(CSSViewportRule::new_inherited( + parent_stylesheet, + viewportrule, + )), + window, + CSSViewportRuleBinding::Wrap, + ) } } @@ -46,6 +57,9 @@ impl SpecificCSSRule for CSSViewportRule { fn get_css(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); - self.viewportrule.read_with(&guard).to_css_string(&guard).into() + self.viewportrule + .read_with(&guard) + .to_css_string(&guard) + .into() } } diff --git a/components/script/dom/customelementregistry.rs b/components/script/dom/customelementregistry.rs index b4a07750f7a..7239a99b0c0 100644 --- a/components/script/dom/customelementregistry.rs +++ b/components/script/dom/customelementregistry.rs @@ -71,9 +71,11 @@ impl CustomElementRegistry { } pub fn new(window: &Window) -> DomRoot<CustomElementRegistry> { - reflect_dom_object(Box::new(CustomElementRegistry::new_inherited(window)), - window, - CustomElementRegistryBinding::Wrap) + reflect_dom_object( + Box::new(CustomElementRegistry::new_inherited(window)), + window, + CustomElementRegistryBinding::Wrap, + ) } /// Cleans up any active promises @@ -83,40 +85,57 @@ impl CustomElementRegistry { } /// <https://html.spec.whatwg.org/multipage/#look-up-a-custom-element-definition> - pub fn lookup_definition(&self, - local_name: &LocalName, - is: Option<&LocalName>) - -> Option<Rc<CustomElementDefinition>> { - self.definitions.borrow().values().find(|definition| { - // Step 4-5 - definition.local_name == *local_name && - (definition.name == *local_name || Some(&definition.name) == is) - }).cloned() + pub fn lookup_definition( + &self, + local_name: &LocalName, + is: Option<&LocalName>, + ) -> Option<Rc<CustomElementDefinition>> { + self.definitions + .borrow() + .values() + .find(|definition| { + // Step 4-5 + definition.local_name == *local_name && + (definition.name == *local_name || Some(&definition.name) == is) + }).cloned() } - pub fn lookup_definition_by_constructor(&self, constructor: HandleObject) -> Option<Rc<CustomElementDefinition>> { - self.definitions.borrow().values().find(|definition| { - definition.constructor.callback() == constructor.get() - }).cloned() + pub fn lookup_definition_by_constructor( + &self, + constructor: HandleObject, + ) -> Option<Rc<CustomElementDefinition>> { + self.definitions + .borrow() + .values() + .find(|definition| definition.constructor.callback() == constructor.get()) + .cloned() } /// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define> /// Steps 10.1, 10.2 #[allow(unsafe_code)] - fn check_prototype(&self, constructor: HandleObject, prototype: MutableHandleValue) -> ErrorResult { + fn check_prototype( + &self, + constructor: HandleObject, + prototype: MutableHandleValue, + ) -> ErrorResult { let global_scope = self.window.upcast::<GlobalScope>(); unsafe { // Step 10.1 - if !JS_GetProperty(global_scope.get_cx(), - constructor, - b"prototype\0".as_ptr() as *const _, - prototype) { + if !JS_GetProperty( + global_scope.get_cx(), + constructor, + b"prototype\0".as_ptr() as *const _, + prototype, + ) { return Err(Error::JSFailed); } // Step 10.2 if !prototype.is_object() { - return Err(Error::Type("constructor.prototype is not an object".to_owned())); + return Err(Error::Type( + "constructor.prototype is not an object".to_owned(), + )); } } Ok(()) @@ -143,10 +162,14 @@ impl CustomElementRegistry { fn get_observed_attributes(&self, constructor: HandleObject) -> Fallible<Vec<DOMString>> { let cx = self.window.get_cx(); rooted!(in(cx) let mut observed_attributes = UndefinedValue()); - if unsafe { !JS_GetProperty(cx, - constructor, - b"observedAttributes\0".as_ptr() as *const _, - observed_attributes.handle_mut()) } { + if unsafe { + !JS_GetProperty( + cx, + constructor, + b"observedAttributes\0".as_ptr() as *const _, + observed_attributes.handle_mut(), + ) + } { return Err(Error::JSFailed); } @@ -155,7 +178,11 @@ impl CustomElementRegistry { } let conversion = unsafe { - FromJSValConvertible::from_jsval(cx, observed_attributes.handle(), StringificationBehavior::Default) + FromJSValConvertible::from_jsval( + cx, + observed_attributes.handle(), + StringificationBehavior::Default, + ) }; match conversion { Ok(ConversionResult::Success(attributes)) => Ok(attributes), @@ -176,7 +203,12 @@ unsafe fn get_callback( rooted!(in(cx) let mut callback = UndefinedValue()); // Step 10.4.1 - if !JS_GetProperty(cx, prototype, name.as_ptr() as *const _, callback.handle_mut()) { + if !JS_GetProperty( + cx, + prototype, + name.as_ptr() as *const _, + callback.handle_mut(), + ) { return Err(Error::JSFailed); } @@ -195,9 +227,10 @@ impl CustomElementRegistryMethods for CustomElementRegistry { #[allow(unsafe_code, unrooted_must_root)] /// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define> fn Define( - &self, name: DOMString, + &self, + name: DOMString, constructor_: Rc<CustomElementConstructor>, - options: &ElementDefinitionOptions + options: &ElementDefinitionOptions, ) -> ErrorResult { let cx = self.window.get_cx(); rooted!(in(cx) let constructor = constructor_.callback()); @@ -213,12 +246,14 @@ impl CustomElementRegistryMethods for CustomElementRegistry { } if unsafe { !IsConstructor(unwrapped_constructor.get()) } { - return Err(Error::Type("Second argument of CustomElementRegistry.define is not a constructor".to_owned())); + return Err(Error::Type( + "Second argument of CustomElementRegistry.define is not a constructor".to_owned(), + )); } // Step 2 if !is_valid_custom_element_name(&name) { - return Err(Error::Syntax) + return Err(Error::Syntax); } // Step 3 @@ -227,7 +262,12 @@ impl CustomElementRegistryMethods for CustomElementRegistry { } // Step 4 - if self.definitions.borrow().iter().any(|(_, ref def)| def.constructor == constructor_) { + if self + .definitions + .borrow() + .iter() + .any(|(_, ref def)| def.constructor == constructor_) + { return Err(Error::NotSupported); } @@ -238,12 +278,12 @@ impl CustomElementRegistryMethods for CustomElementRegistry { let local_name = if let Some(ref extended_name) = *extends { // Step 7.1 if is_valid_custom_element_name(extended_name) { - return Err(Error::NotSupported) + return Err(Error::NotSupported); } // Step 7.2 if !is_extendable_element_interface(extended_name) { - return Err(Error::NotSupported) + return Err(Error::NotSupported); } LocalName::from(&**extended_name) @@ -300,20 +340,28 @@ impl CustomElementRegistryMethods for CustomElementRegistry { self.element_definition_is_running.set(false); // Step 11 - let definition = Rc::new(CustomElementDefinition::new(name.clone(), - local_name.clone(), - constructor_, - observed_attributes, - callbacks)); + let definition = Rc::new(CustomElementDefinition::new( + name.clone(), + local_name.clone(), + constructor_, + observed_attributes, + callbacks, + )); // Step 12 - self.definitions.borrow_mut().insert(name.clone(), definition.clone()); + self.definitions + .borrow_mut() + .insert(name.clone(), definition.clone()); // Step 13 let document = self.window.Document(); // Steps 14-15 - for candidate in document.upcast::<Node>().traverse_preorder().filter_map(DomRoot::downcast::<Element>) { + for candidate in document + .upcast::<Node>() + .traverse_preorder() + .filter_map(DomRoot::downcast::<Element>) + { let is = candidate.get_is(); if *candidate.local_name() == local_name && *candidate.namespace() == ns!(html) && @@ -336,7 +384,9 @@ impl CustomElementRegistryMethods for CustomElementRegistry { match self.definitions.borrow().get(&LocalName::from(&*name)) { Some(definition) => { rooted!(in(cx) let mut constructor = UndefinedValue()); - definition.constructor.to_jsval(cx, constructor.handle_mut()); + definition + .constructor + .to_jsval(cx, constructor.handle_mut()); constructor.get() }, None => UndefinedValue(), @@ -353,14 +403,14 @@ impl CustomElementRegistryMethods for CustomElementRegistry { if !is_valid_custom_element_name(&name) { let promise = Promise::new(global_scope); promise.reject_native(&DOMException::new(global_scope, DOMErrorName::SyntaxError)); - return promise + return promise; } // Step 2 if self.definitions.borrow().contains_key(&name) { let promise = Promise::new(global_scope); promise.resolve_native(&UndefinedValue()); - return promise + return promise; } // Step 3 @@ -417,12 +467,13 @@ pub struct CustomElementDefinition { } impl CustomElementDefinition { - fn new(name: LocalName, - local_name: LocalName, - constructor: Rc<CustomElementConstructor>, - observed_attributes: Vec<DOMString>, - callbacks: LifecycleCallbacks) - -> CustomElementDefinition { + fn new( + name: LocalName, + local_name: LocalName, + constructor: Rc<CustomElementConstructor>, + observed_attributes: Vec<DOMString>, + callbacks: LifecycleCallbacks, + ) -> CustomElementDefinition { CustomElementDefinition { name: name, local_name: local_name, @@ -440,7 +491,11 @@ impl CustomElementDefinition { /// https://dom.spec.whatwg.org/#concept-create-element Step 6.1 #[allow(unsafe_code)] - pub fn create_element(&self, document: &Document, prefix: Option<Prefix>) -> Fallible<DomRoot<Element>> { + pub fn create_element( + &self, + document: &Document, + prefix: Option<Prefix>, + ) -> Fallible<DomRoot<Element>> { let window = document.window(); let cx = window.get_cx(); // Step 2 @@ -456,16 +511,22 @@ impl CustomElementDefinition { } rooted!(in(cx) let element_val = ObjectValue(element.get())); - let element: DomRoot<Element> = match unsafe { DomRoot::from_jsval(cx, element_val.handle(), ()) } { - Ok(ConversionResult::Success(element)) => element, - Ok(ConversionResult::Failure(..)) => - return Err(Error::Type("Constructor did not return a DOM node".to_owned())), - _ => return Err(Error::JSFailed), - }; + let element: DomRoot<Element> = + match unsafe { DomRoot::from_jsval(cx, element_val.handle(), ()) } { + Ok(ConversionResult::Success(element)) => element, + Ok(ConversionResult::Failure(..)) => { + return Err(Error::Type( + "Constructor did not return a DOM node".to_owned(), + )) + }, + _ => return Err(Error::JSFailed), + }; // Step 3 if !element.is::<HTMLElement>() { - return Err(Error::Type("Constructor did not return a DOM node".to_owned())); + return Err(Error::Type( + "Constructor did not return a DOM node".to_owned(), + )); } // Steps 4-9 @@ -503,17 +564,27 @@ pub fn upgrade_element(definition: Rc<CustomElementDefinition>, element: &Elemen let local_name = attr.local_name().clone(); let value = DOMString::from(&**attr.value()); let namespace = attr.namespace().clone(); - ScriptThread::enqueue_callback_reaction(element, - CallbackReaction::AttributeChanged(local_name, None, Some(value), namespace), Some(definition.clone())); + ScriptThread::enqueue_callback_reaction( + element, + CallbackReaction::AttributeChanged(local_name, None, Some(value), namespace), + Some(definition.clone()), + ); } // Step 4 if element.is_connected() { - ScriptThread::enqueue_callback_reaction(element, CallbackReaction::Connected, Some(definition.clone())); + ScriptThread::enqueue_callback_reaction( + element, + CallbackReaction::Connected, + Some(definition.clone()), + ); } // Step 5 - definition.construction_stack.borrow_mut().push(ConstructionStackEntry::Element(DomRoot::from_ref(element))); + definition + .construction_stack + .borrow_mut() + .push(ConstructionStackEntry::Element(DomRoot::from_ref(element))); // Step 7 let result = run_upgrade_constructor(&definition.constructor, element); @@ -548,25 +619,44 @@ pub fn upgrade_element(definition: Rc<CustomElementDefinition>, element: &Elemen /// <https://html.spec.whatwg.org/multipage/#concept-upgrade-an-element> /// Steps 7.1-7.2 #[allow(unsafe_code)] -fn run_upgrade_constructor(constructor: &Rc<CustomElementConstructor>, element: &Element) -> ErrorResult { +fn run_upgrade_constructor( + constructor: &Rc<CustomElementConstructor>, + element: &Element, +) -> ErrorResult { let window = window_from_node(element); let cx = window.get_cx(); rooted!(in(cx) let constructor_val = ObjectValue(constructor.callback())); rooted!(in(cx) let mut element_val = UndefinedValue()); - unsafe { element.to_jsval(cx, element_val.handle_mut()); } + unsafe { + element.to_jsval(cx, element_val.handle_mut()); + } rooted!(in(cx) let mut construct_result = ptr::null_mut::<JSObject>()); { // Go into the constructor's compartment let _ac = JSAutoCompartment::new(cx, constructor.callback()); let args = HandleValueArray::new(); // Step 7.1 - if unsafe { !Construct1(cx, constructor_val.handle(), &args, construct_result.handle_mut()) } { + if unsafe { + !Construct1( + cx, + constructor_val.handle(), + &args, + construct_result.handle_mut(), + ) + } { return Err(Error::JSFailed); } // Step 7.2 let mut same = false; rooted!(in(cx) let construct_result_val = ObjectValue(construct_result.get())); - if unsafe { !JS_SameValue(cx, construct_result_val.handle(), element_val.handle(), &mut same) } { + if unsafe { + !JS_SameValue( + cx, + construct_result_val.handle(), + element_val.handle(), + &mut same, + ) + } { return Err(Error::JSFailed); } if !same { @@ -583,7 +673,9 @@ pub fn try_upgrade_element(element: &Element) { let namespace = element.namespace(); let local_name = element.local_name(); let is = element.get_is(); - if let Some(definition) = document.lookup_custom_element_definition(namespace, local_name, is.as_ref()) { + if let Some(definition) = + document.lookup_custom_element_definition(namespace, local_name, is.as_ref()) + { // Step 2 ScriptThread::enqueue_upgrade_reaction(element, definition); } @@ -592,14 +684,10 @@ pub fn try_upgrade_element(element: &Element) { #[derive(JSTraceable, MallocSizeOf)] #[must_root] pub enum CustomElementReaction { - Upgrade( - #[ignore_malloc_size_of = "Rc"] - Rc<CustomElementDefinition> - ), + Upgrade(#[ignore_malloc_size_of = "Rc"] Rc<CustomElementDefinition>), Callback( - #[ignore_malloc_size_of = "Rc"] - Rc<Function>, - Box<[Heap<JSVal>]> + #[ignore_malloc_size_of = "Rc"] Rc<Function>, + Box<[Heap<JSVal>]>, ), } @@ -609,12 +697,17 @@ impl CustomElementReaction { pub fn invoke(&self, element: &Element) { // Step 2.1 match *self { - CustomElementReaction::Upgrade(ref definition) => upgrade_element(definition.clone(), element), + CustomElementReaction::Upgrade(ref definition) => { + upgrade_element(definition.clone(), element) + }, CustomElementReaction::Callback(ref callback, ref arguments) => { // We're rooted, so it's safe to hand out a handle to objects in Heap - let arguments = arguments.iter().map(|arg| unsafe { HandleValue::from_raw(arg.handle()) }).collect(); + let arguments = arguments + .iter() + .map(|arg| unsafe { HandleValue::from_raw(arg.handle()) }) + .collect(); let _ = callback.Call_(&*element, arguments, ExceptionHandling::Report); - } + }, } } } @@ -675,7 +768,8 @@ impl CustomElementReactionStack { self.backup_queue.invoke_reactions(); // Step 4.2 - self.processing_backup_element_queue.set(BackupElementQueueFlag::NotProcessing); + self.processing_backup_element_queue + .set(BackupElementQueueFlag::NotProcessing); } /// <https://html.spec.whatwg.org/multipage/#enqueue-an-element-on-the-appropriate-element-queue> @@ -693,7 +787,8 @@ impl CustomElementReactionStack { } // Step 1.3 - self.processing_backup_element_queue.set(BackupElementQueueFlag::Processing); + self.processing_backup_element_queue + .set(BackupElementQueueFlag::Processing); // Step 4 ScriptThread::enqueue_microtask(Microtask::CustomElementReaction); @@ -702,10 +797,12 @@ impl CustomElementReactionStack { /// <https://html.spec.whatwg.org/multipage/#enqueue-a-custom-element-callback-reaction> #[allow(unsafe_code)] - pub fn enqueue_callback_reaction(&self, - element: &Element, - reaction: CallbackReaction, - definition: Option<Rc<CustomElementDefinition>>) { + pub fn enqueue_callback_reaction( + &self, + element: &Element, + reaction: CallbackReaction, + definition: Option<Rc<CustomElementDefinition>>, + ) { // Step 1 let definition = match definition.or_else(|| element.get_custom_element_definition()) { Some(definition) => definition, @@ -714,8 +811,13 @@ impl CustomElementReactionStack { // Step 2 let (callback, args) = match reaction { - CallbackReaction::Connected => (definition.callbacks.connected_callback.clone(), Vec::new()), - CallbackReaction::Disconnected => (definition.callbacks.disconnected_callback.clone(), Vec::new()), + CallbackReaction::Connected => { + (definition.callbacks.connected_callback.clone(), Vec::new()) + }, + CallbackReaction::Disconnected => ( + definition.callbacks.disconnected_callback.clone(), + Vec::new(), + ), CallbackReaction::Adopted(ref old_doc, ref new_doc) => { let args = vec![Heap::default(), Heap::default()]; args[0].set(ObjectValue(old_doc.reflector().get_jsobject().get())); @@ -724,7 +826,11 @@ impl CustomElementReactionStack { }, CallbackReaction::AttributeChanged(local_name, old_val, val, namespace) => { // Step 4 - if !definition.observed_attributes.iter().any(|attr| *attr == *local_name) { + if !definition + .observed_attributes + .iter() + .any(|attr| *attr == *local_name) + { return; } @@ -732,31 +838,47 @@ impl CustomElementReactionStack { let local_name = DOMString::from(&*local_name); rooted!(in(cx) let mut name_value = UndefinedValue()); - unsafe { local_name.to_jsval(cx, name_value.handle_mut()); } + unsafe { + local_name.to_jsval(cx, name_value.handle_mut()); + } rooted!(in(cx) let mut old_value = NullValue()); if let Some(old_val) = old_val { - unsafe { old_val.to_jsval(cx, old_value.handle_mut()); } + unsafe { + old_val.to_jsval(cx, old_value.handle_mut()); + } } rooted!(in(cx) let mut value = NullValue()); if let Some(val) = val { - unsafe { val.to_jsval(cx, value.handle_mut()); } + unsafe { + val.to_jsval(cx, value.handle_mut()); + } } rooted!(in(cx) let mut namespace_value = NullValue()); if namespace != ns!() { let namespace = DOMString::from(&*namespace); - unsafe { namespace.to_jsval(cx, namespace_value.handle_mut()); } + unsafe { + namespace.to_jsval(cx, namespace_value.handle_mut()); + } } - let args = vec![Heap::default(), Heap::default(), Heap::default(), Heap::default()]; + let args = vec![ + Heap::default(), + Heap::default(), + Heap::default(), + Heap::default(), + ]; args[0].set(name_value.get()); args[1].set(old_value.get()); args[2].set(value.get()); args[3].set(namespace_value.get()); - (definition.callbacks.attribute_changed_callback.clone(), args) + ( + definition.callbacks.attribute_changed_callback.clone(), + args, + ) }, }; @@ -774,7 +896,11 @@ impl CustomElementReactionStack { } /// <https://html.spec.whatwg.org/multipage/#enqueue-a-custom-element-upgrade-reaction> - pub fn enqueue_upgrade_reaction(&self, element: &Element, definition: Rc<CustomElementDefinition>) { + pub fn enqueue_upgrade_reaction( + &self, + element: &Element, + definition: Rc<CustomElementDefinition>, + ) { // Step 1 element.push_upgrade_reaction(definition); // Step 2 @@ -806,7 +932,12 @@ impl ElementQueue { } fn next_element(&self) -> Option<DomRoot<Element>> { - self.queue.borrow_mut().pop_front().as_ref().map(Dom::deref).map(DomRoot::from_ref) + self.queue + .borrow_mut() + .pop_front() + .as_ref() + .map(Dom::deref) + .map(DomRoot::from_ref) } fn append_element(&self, element: &Element) { @@ -859,145 +990,148 @@ pub fn is_valid_custom_element_name(name: &str) -> bool { /// Check if this character is a PCENChar /// <https://html.spec.whatwg.org/multipage/#prod-pcenchar> fn is_potential_custom_element_char(c: char) -> bool { - c == '-' || c == '.' || c == '_' || c == '\u{B7}' || - (c >= '0' && c <= '9') || - (c >= 'a' && c <= 'z') || - (c >= '\u{C0}' && c <= '\u{D6}') || - (c >= '\u{D8}' && c <= '\u{F6}') || - (c >= '\u{F8}' && c <= '\u{37D}') || - (c >= '\u{37F}' && c <= '\u{1FFF}') || - (c >= '\u{200C}' && c <= '\u{200D}') || - (c >= '\u{203F}' && c <= '\u{2040}') || - (c >= '\u{2070}' && c <= '\u{2FEF}') || - (c >= '\u{3001}' && c <= '\u{D7FF}') || - (c >= '\u{F900}' && c <= '\u{FDCF}') || - (c >= '\u{FDF0}' && c <= '\u{FFFD}') || - (c >= '\u{10000}' && c <= '\u{EFFFF}') + c == '-' || + c == '.' || + c == '_' || + c == '\u{B7}' || + (c >= '0' && c <= '9') || + (c >= 'a' && c <= 'z') || + (c >= '\u{C0}' && c <= '\u{D6}') || + (c >= '\u{D8}' && c <= '\u{F6}') || + (c >= '\u{F8}' && c <= '\u{37D}') || + (c >= '\u{37F}' && c <= '\u{1FFF}') || + (c >= '\u{200C}' && c <= '\u{200D}') || + (c >= '\u{203F}' && c <= '\u{2040}') || + (c >= '\u{2070}' && c <= '\u{2FEF}') || + (c >= '\u{3001}' && c <= '\u{D7FF}') || + (c >= '\u{F900}' && c <= '\u{FDCF}') || + (c >= '\u{FDF0}' && c <= '\u{FFFD}') || + (c >= '\u{10000}' && c <= '\u{EFFFF}') } fn is_extendable_element_interface(element: &str) -> bool { element == "a" || - element == "abbr" || - element == "acronym" || - element == "address" || - element == "area" || - element == "article" || - element == "aside" || - element == "audio" || - element == "b" || - element == "base" || - element == "bdi" || - element == "bdo" || - element == "big" || - element == "blockquote" || - element == "body" || - element == "br" || - element == "button" || - element == "canvas" || - element == "caption" || - element == "center" || - element == "cite" || - element == "code" || - element == "col" || - element == "colgroup" || - element == "data" || - element == "datalist" || - element == "dd" || - element == "del" || - element == "details" || - element == "dfn" || - element == "dialog" || - element == "dir" || - element == "div" || - element == "dl" || - element == "dt" || - element == "em" || - element == "embed" || - element == "fieldset" || - element == "figcaption" || - element == "figure" || - element == "font" || - element == "footer" || - element == "form" || - element == "frame" || - element == "frameset" || - element == "h1" || - element == "h2" || - element == "h3" || - element == "h4" || - element == "h5" || - element == "h6" || - element == "head" || - element == "header" || - element == "hgroup" || - element == "hr" || - element == "html" || - element == "i" || - element == "iframe" || - element == "img" || - element == "input" || - element == "ins" || - element == "kbd" || - element == "label" || - element == "legend" || - element == "li" || - element == "link" || - element == "listing" || - element == "main" || - element == "map" || - element == "mark" || - element == "marquee" || - element == "meta" || - element == "meter" || - element == "nav" || - element == "nobr" || - element == "noframes" || - element == "noscript" || - element == "object" || - element == "ol" || - element == "optgroup" || - element == "option" || - element == "output" || - element == "p" || - element == "param" || - element == "plaintext" || - element == "pre" || - element == "progress" || - element == "q" || - element == "rp" || - element == "rt" || - element == "ruby" || - element == "s" || - element == "samp" || - element == "script" || - element == "section" || - element == "select" || - element == "small" || - element == "source" || - element == "span" || - element == "strike" || - element == "strong" || - element == "style" || - element == "sub" || - element == "summary" || - element == "sup" || - element == "table" || - element == "tbody" || - element == "td" || - element == "template" || - element == "textarea" || - element == "tfoot" || - element == "th" || - element == "thead" || - element == "time" || - element == "title" || - element == "tr" || - element == "tt" || - element == "track" || - element == "u" || - element == "ul" || - element == "var" || - element == "video" || - element == "wbr" || - element == "xmp" + element == "abbr" || + element == "acronym" || + element == "address" || + element == "area" || + element == "article" || + element == "aside" || + element == "audio" || + element == "b" || + element == "base" || + element == "bdi" || + element == "bdo" || + element == "big" || + element == "blockquote" || + element == "body" || + element == "br" || + element == "button" || + element == "canvas" || + element == "caption" || + element == "center" || + element == "cite" || + element == "code" || + element == "col" || + element == "colgroup" || + element == "data" || + element == "datalist" || + element == "dd" || + element == "del" || + element == "details" || + element == "dfn" || + element == "dialog" || + element == "dir" || + element == "div" || + element == "dl" || + element == "dt" || + element == "em" || + element == "embed" || + element == "fieldset" || + element == "figcaption" || + element == "figure" || + element == "font" || + element == "footer" || + element == "form" || + element == "frame" || + element == "frameset" || + element == "h1" || + element == "h2" || + element == "h3" || + element == "h4" || + element == "h5" || + element == "h6" || + element == "head" || + element == "header" || + element == "hgroup" || + element == "hr" || + element == "html" || + element == "i" || + element == "iframe" || + element == "img" || + element == "input" || + element == "ins" || + element == "kbd" || + element == "label" || + element == "legend" || + element == "li" || + element == "link" || + element == "listing" || + element == "main" || + element == "map" || + element == "mark" || + element == "marquee" || + element == "meta" || + element == "meter" || + element == "nav" || + element == "nobr" || + element == "noframes" || + element == "noscript" || + element == "object" || + element == "ol" || + element == "optgroup" || + element == "option" || + element == "output" || + element == "p" || + element == "param" || + element == "plaintext" || + element == "pre" || + element == "progress" || + element == "q" || + element == "rp" || + element == "rt" || + element == "ruby" || + element == "s" || + element == "samp" || + element == "script" || + element == "section" || + element == "select" || + element == "small" || + element == "source" || + element == "span" || + element == "strike" || + element == "strong" || + element == "style" || + element == "sub" || + element == "summary" || + element == "sup" || + element == "table" || + element == "tbody" || + element == "td" || + element == "template" || + element == "textarea" || + element == "tfoot" || + element == "th" || + element == "thead" || + element == "time" || + element == "title" || + element == "tr" || + element == "tt" || + element == "track" || + element == "u" || + element == "ul" || + element == "var" || + element == "video" || + element == "wbr" || + element == "xmp" } diff --git a/components/script/dom/customevent.rs b/components/script/dom/customevent.rs index f932e1a96ae..b054d1a0dcb 100644 --- a/components/script/dom/customevent.rs +++ b/components/script/dom/customevent.rs @@ -36,38 +36,46 @@ impl CustomEvent { } pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<CustomEvent> { - reflect_dom_object(Box::new(CustomEvent::new_inherited()), - global, - CustomEventBinding::Wrap) + reflect_dom_object( + Box::new(CustomEvent::new_inherited()), + global, + CustomEventBinding::Wrap, + ) } - pub fn new(global: &GlobalScope, - type_: Atom, - bubbles: bool, - cancelable: bool, - detail: HandleValue) - -> DomRoot<CustomEvent> { + pub fn new( + global: &GlobalScope, + type_: Atom, + bubbles: bool, + cancelable: bool, + detail: HandleValue, + ) -> DomRoot<CustomEvent> { let ev = CustomEvent::new_uninitialized(global); ev.init_custom_event(type_, bubbles, cancelable, detail); ev } #[allow(unsafe_code)] - pub fn Constructor(global: &GlobalScope, - type_: DOMString, - init: RootedTraceableBox<CustomEventBinding::CustomEventInit>) - -> Fallible<DomRoot<CustomEvent>> { - Ok(CustomEvent::new(global, - Atom::from(type_), - init.parent.bubbles, - init.parent.cancelable, - init.detail.handle())) + pub fn Constructor( + global: &GlobalScope, + type_: DOMString, + init: RootedTraceableBox<CustomEventBinding::CustomEventInit>, + ) -> Fallible<DomRoot<CustomEvent>> { + Ok(CustomEvent::new( + global, + Atom::from(type_), + init.parent.bubbles, + init.parent.cancelable, + init.detail.handle(), + )) } - fn init_custom_event(&self, - type_: Atom, - can_bubble: bool, - cancelable: bool, - detail: HandleValue) { + fn init_custom_event( + &self, + type_: Atom, + can_bubble: bool, + cancelable: bool, + detail: HandleValue, + ) { let event = self.upcast::<Event>(); if event.dispatching() { return; @@ -87,12 +95,14 @@ impl CustomEventMethods for CustomEvent { #[allow(unsafe_code)] // https://dom.spec.whatwg.org/#dom-customevent-initcustomevent - unsafe fn InitCustomEvent(&self, - _cx: *mut JSContext, - type_: DOMString, - can_bubble: bool, - cancelable: bool, - detail: HandleValue) { + unsafe fn InitCustomEvent( + &self, + _cx: *mut JSContext, + type_: DOMString, + can_bubble: bool, + cancelable: bool, + detail: HandleValue, + ) { self.init_custom_event(Atom::from(type_), can_bubble, cancelable, detail) } diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index 791190e0fd2..dac95aeb4c5 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -57,9 +57,10 @@ pub struct AutoWorkerReset<'a> { } impl<'a> AutoWorkerReset<'a> { - fn new(workerscope: &'a DedicatedWorkerGlobalScope, - worker: TrustedWorkerAddress) - -> AutoWorkerReset<'a> { + fn new( + workerscope: &'a DedicatedWorkerGlobalScope, + worker: TrustedWorkerAddress, + ) -> AutoWorkerReset<'a> { AutoWorkerReset { workerscope: workerscope, old_worker: replace(&mut *workerscope.worker.borrow_mut(), Some(worker)), @@ -83,7 +84,7 @@ pub enum DedicatedWorkerScriptMsg { pub enum MixedMessage { FromWorker(DedicatedWorkerScriptMsg), FromScheduler((TrustedWorkerAddress, TimerEvent)), - FromDevtools(DevtoolScriptControlMsg) + FromDevtools(DevtoolScriptControlMsg), } impl QueuedTaskConversion for DedicatedWorkerScriptMsg { @@ -97,14 +98,18 @@ impl QueuedTaskConversion for DedicatedWorkerScriptMsg { _ => return None, }; match script_msg { - CommonScriptMsg::Task(_category, _boxed, _pipeline_id, source_name) => Some(&source_name), + CommonScriptMsg::Task(_category, _boxed, _pipeline_id, source_name) => { + Some(&source_name) + }, _ => return None, } } fn into_queued_task(self) -> Option<QueuedTask> { let (worker, common_worker_msg) = match self { - DedicatedWorkerScriptMsg::CommonWorker(worker, common_worker_msg) => (worker, common_worker_msg), + DedicatedWorkerScriptMsg::CommonWorker(worker, common_worker_msg) => { + (worker, common_worker_msg) + }, _ => return None, }; let script_msg = match common_worker_msg { @@ -112,8 +117,9 @@ impl QueuedTaskConversion for DedicatedWorkerScriptMsg { _ => return None, }; let (category, boxed, pipeline_id, task_source) = match script_msg { - CommonScriptMsg::Task(category, boxed, pipeline_id, task_source) => - (category, boxed, pipeline_id, task_source), + CommonScriptMsg::Task(category, boxed, pipeline_id, task_source) => { + (category, boxed, pipeline_id, task_source) + }, _ => return None, }; Some((Some(worker), category, boxed, pipeline_id, task_source)) @@ -121,12 +127,7 @@ impl QueuedTaskConversion for DedicatedWorkerScriptMsg { fn from_queued_task(queued_task: QueuedTask) -> Self { let (worker, category, boxed, pipeline_id, task_source) = queued_task; - let script_msg = CommonScriptMsg::Task( - category, - boxed, - pipeline_id, - task_source - ); + let script_msg = CommonScriptMsg::Task(category, boxed, pipeline_id, task_source); DedicatedWorkerScriptMsg::CommonWorker(worker.unwrap(), WorkerScriptMsg::Common(script_msg)) } @@ -197,24 +198,27 @@ impl WorkerEventLoopMethods for DedicatedWorkerGlobalScope { } impl DedicatedWorkerGlobalScope { - fn new_inherited(init: WorkerGlobalScopeInit, - worker_url: ServoUrl, - from_devtools_receiver: Receiver<DevtoolScriptControlMsg>, - runtime: Runtime, - parent_sender: Box<ScriptChan + Send>, - own_sender: Sender<DedicatedWorkerScriptMsg>, - receiver: Receiver<DedicatedWorkerScriptMsg>, - timer_event_chan: IpcSender<TimerEvent>, - timer_event_port: Receiver<(TrustedWorkerAddress, TimerEvent)>, - closing: Arc<AtomicBool>) - -> DedicatedWorkerGlobalScope { + fn new_inherited( + init: WorkerGlobalScopeInit, + worker_url: ServoUrl, + from_devtools_receiver: Receiver<DevtoolScriptControlMsg>, + runtime: Runtime, + parent_sender: Box<ScriptChan + Send>, + own_sender: Sender<DedicatedWorkerScriptMsg>, + receiver: Receiver<DedicatedWorkerScriptMsg>, + timer_event_chan: IpcSender<TimerEvent>, + timer_event_port: Receiver<(TrustedWorkerAddress, TimerEvent)>, + closing: Arc<AtomicBool>, + ) -> DedicatedWorkerGlobalScope { DedicatedWorkerGlobalScope { - workerglobalscope: WorkerGlobalScope::new_inherited(init, - worker_url, - runtime, - from_devtools_receiver, - timer_event_chan, - Some(closing)), + workerglobalscope: WorkerGlobalScope::new_inherited( + init, + worker_url, + runtime, + from_devtools_receiver, + timer_event_chan, + Some(closing), + ), task_queue: TaskQueue::new(receiver, own_sender.clone()), own_sender: own_sender, timer_event_port: timer_event_port, @@ -224,17 +228,18 @@ impl DedicatedWorkerGlobalScope { } #[allow(unsafe_code)] - pub fn new(init: WorkerGlobalScopeInit, - worker_url: ServoUrl, - from_devtools_receiver: Receiver<DevtoolScriptControlMsg>, - runtime: Runtime, - parent_sender: Box<ScriptChan + Send>, - own_sender: Sender<DedicatedWorkerScriptMsg>, - receiver: Receiver<DedicatedWorkerScriptMsg>, - timer_event_chan: IpcSender<TimerEvent>, - timer_event_port: Receiver<(TrustedWorkerAddress, TimerEvent)>, - closing: Arc<AtomicBool>) - -> DomRoot<DedicatedWorkerGlobalScope> { + pub fn new( + init: WorkerGlobalScopeInit, + worker_url: ServoUrl, + from_devtools_receiver: Receiver<DevtoolScriptControlMsg>, + runtime: Runtime, + parent_sender: Box<ScriptChan + Send>, + own_sender: Sender<DedicatedWorkerScriptMsg>, + receiver: Receiver<DedicatedWorkerScriptMsg>, + timer_event_chan: IpcSender<TimerEvent>, + timer_event_port: Receiver<(TrustedWorkerAddress, TimerEvent)>, + closing: Arc<AtomicBool>, + ) -> DomRoot<DedicatedWorkerGlobalScope> { let cx = runtime.cx(); let scope = Box::new(DedicatedWorkerGlobalScope::new_inherited( init, @@ -246,115 +251,147 @@ impl DedicatedWorkerGlobalScope { receiver, timer_event_chan, timer_event_port, - closing + closing, )); - unsafe { - DedicatedWorkerGlobalScopeBinding::Wrap(cx, scope) - } + unsafe { DedicatedWorkerGlobalScopeBinding::Wrap(cx, scope) } } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#run-a-worker - pub fn run_worker_scope(init: WorkerGlobalScopeInit, - worker_url: ServoUrl, - from_devtools_receiver: IpcReceiver<DevtoolScriptControlMsg>, - worker: TrustedWorkerAddress, - parent_sender: Box<ScriptChan + Send>, - own_sender: Sender<DedicatedWorkerScriptMsg>, - receiver: Receiver<DedicatedWorkerScriptMsg>, - worker_load_origin: WorkerScriptLoadOrigin, - closing: Arc<AtomicBool>) { + pub fn run_worker_scope( + init: WorkerGlobalScopeInit, + worker_url: ServoUrl, + from_devtools_receiver: IpcReceiver<DevtoolScriptControlMsg>, + worker: TrustedWorkerAddress, + parent_sender: Box<ScriptChan + Send>, + own_sender: Sender<DedicatedWorkerScriptMsg>, + receiver: Receiver<DedicatedWorkerScriptMsg>, + worker_load_origin: WorkerScriptLoadOrigin, + closing: Arc<AtomicBool>, + ) { let serialized_worker_url = worker_url.to_string(); let name = format!("WebWorker for {}", serialized_worker_url); let top_level_browsing_context_id = TopLevelBrowsingContextId::installed(); - let origin = GlobalScope::current().expect("No current global object").origin().immutable().clone(); - - thread::Builder::new().name(name).spawn(move || { - thread_state::initialize(ThreadState::SCRIPT | ThreadState::IN_WORKER); + let origin = GlobalScope::current() + .expect("No current global object") + .origin() + .immutable() + .clone(); + + thread::Builder::new() + .name(name) + .spawn(move || { + thread_state::initialize(ThreadState::SCRIPT | ThreadState::IN_WORKER); + + if let Some(top_level_browsing_context_id) = top_level_browsing_context_id { + TopLevelBrowsingContextId::install(top_level_browsing_context_id); + } - if let Some(top_level_browsing_context_id) = top_level_browsing_context_id { - TopLevelBrowsingContextId::install(top_level_browsing_context_id); - } + let roots = RootCollection::new(); + let _stack_roots = ThreadLocalStackRoots::new(&roots); + + let WorkerScriptLoadOrigin { + referrer_url, + referrer_policy, + pipeline_id, + } = worker_load_origin; + + let request = RequestInit { + url: worker_url.clone(), + destination: Destination::Worker, + credentials_mode: CredentialsMode::Include, + use_url_credentials: true, + pipeline_id: pipeline_id, + referrer_url: referrer_url, + referrer_policy: referrer_policy, + origin, + ..RequestInit::default() + }; + + let (metadata, bytes) = + match load_whole_resource(request, &init.resource_threads.sender()) { + Err(_) => { + println!("error loading script {}", serialized_worker_url); + parent_sender + .send(CommonScriptMsg::Task( + WorkerEvent, + Box::new(SimpleWorkerErrorHandler::new(worker)), + pipeline_id, + TaskSourceName::DOMManipulation, + )).unwrap(); + return; + }, + Ok((metadata, bytes)) => (metadata, bytes), + }; + let url = metadata.final_url; + let source = String::from_utf8_lossy(&bytes); + + let runtime = unsafe { new_rt_and_cx() }; + + let (devtools_mpsc_chan, devtools_mpsc_port) = channel(); + route_ipc_receiver_to_new_servo_sender(from_devtools_receiver, devtools_mpsc_chan); + + let (timer_tx, timer_rx) = channel(); + let (timer_ipc_chan, timer_ipc_port) = ipc::channel().unwrap(); + let worker_for_route = worker.clone(); + ROUTER.add_route( + timer_ipc_port.to_opaque(), + Box::new(move |message| { + let event = message.to().unwrap(); + timer_tx.send((worker_for_route.clone(), event)).unwrap(); + }), + ); + + let global = DedicatedWorkerGlobalScope::new( + init, + url, + devtools_mpsc_port, + runtime, + parent_sender.clone(), + own_sender, + receiver, + timer_ipc_chan, + timer_rx, + closing, + ); + // FIXME(njn): workers currently don't have a unique ID suitable for using in reporter + // registration (#6631), so we instead use a random number and cross our fingers. + let scope = global.upcast::<WorkerGlobalScope>(); + + unsafe { + // Handle interrupt requests + JS_AddInterruptCallback(scope.get_cx(), Some(interrupt_callback)); + } - let roots = RootCollection::new(); - let _stack_roots = ThreadLocalStackRoots::new(&roots); - - let WorkerScriptLoadOrigin { referrer_url, referrer_policy, pipeline_id } = worker_load_origin; - - let request = RequestInit { - url: worker_url.clone(), - destination: Destination::Worker, - credentials_mode: CredentialsMode::Include, - use_url_credentials: true, - pipeline_id: pipeline_id, - referrer_url: referrer_url, - referrer_policy: referrer_policy, - origin, - .. RequestInit::default() - }; - - let (metadata, bytes) = match load_whole_resource(request, - &init.resource_threads.sender()) { - Err(_) => { - println!("error loading script {}", serialized_worker_url); - parent_sender.send(CommonScriptMsg::Task( - WorkerEvent, - Box::new(SimpleWorkerErrorHandler::new(worker)), - pipeline_id, - TaskSourceName::DOMManipulation, - )).unwrap(); + if scope.is_closing() { return; } - Ok((metadata, bytes)) => (metadata, bytes) - }; - let url = metadata.final_url; - let source = String::from_utf8_lossy(&bytes); - - let runtime = unsafe { new_rt_and_cx() }; - - let (devtools_mpsc_chan, devtools_mpsc_port) = channel(); - route_ipc_receiver_to_new_servo_sender(from_devtools_receiver, devtools_mpsc_chan); - - let (timer_tx, timer_rx) = channel(); - let (timer_ipc_chan, timer_ipc_port) = ipc::channel().unwrap(); - let worker_for_route = worker.clone(); - ROUTER.add_route(timer_ipc_port.to_opaque(), Box::new(move |message| { - let event = message.to().unwrap(); - timer_tx.send((worker_for_route.clone(), event)).unwrap(); - })); - - let global = DedicatedWorkerGlobalScope::new( - init, url, devtools_mpsc_port, runtime, - parent_sender.clone(), own_sender, receiver, - timer_ipc_chan, timer_rx, closing); - // FIXME(njn): workers currently don't have a unique ID suitable for using in reporter - // registration (#6631), so we instead use a random number and cross our fingers. - let scope = global.upcast::<WorkerGlobalScope>(); - - unsafe { - // Handle interrupt requests - JS_AddInterruptCallback(scope.get_cx(), Some(interrupt_callback)); - } - - if scope.is_closing() { - return; - } - { - let _ar = AutoWorkerReset::new(&global, worker.clone()); - scope.execute_script(DOMString::from(source)); - } - - let reporter_name = format!("dedicated-worker-reporter-{}", random::<u64>()); - scope.upcast::<GlobalScope>().mem_profiler_chan().run_with_memory_reporting(|| { - // Step 29, Run the responsible event loop specified by inside settings until it is destroyed. - // The worker processing model remains on this step until the event loop is destroyed, - // which happens after the closing flag is set to true. - while !scope.is_closing() { - run_worker_event_loop(&*global, Some(&worker)); + { + let _ar = AutoWorkerReset::new(&global, worker.clone()); + scope.execute_script(DOMString::from(source)); } - }, reporter_name, parent_sender, CommonScriptMsg::CollectReports); - }).expect("Thread spawning failed"); + + let reporter_name = format!("dedicated-worker-reporter-{}", random::<u64>()); + scope + .upcast::<GlobalScope>() + .mem_profiler_chan() + .run_with_memory_reporting( + || { + // Step 29, Run the responsible event loop specified + // by inside settings until it is destroyed. + // The worker processing model remains on this step + // until the event loop is destroyed, + // which happens after the closing flag is set to true. + while !scope.is_closing() { + run_worker_event_loop(&*global, Some(&worker)); + } + }, + reporter_name, + parent_sender, + CommonScriptMsg::CollectReports, + ); + }).expect("Thread spawning failed"); } pub fn script_chan(&self) -> Box<ScriptChan + Send> { @@ -378,8 +415,8 @@ impl DedicatedWorkerGlobalScope { WorkerScriptMsg::DOMMessage(data) => { let scope = self.upcast::<WorkerGlobalScope>(); let target = self.upcast(); - let _ac = JSAutoCompartment::new(scope.get_cx(), - scope.reflector().get_jsobject().get()); + let _ac = + JSAutoCompartment::new(scope.get_cx(), scope.reflector().get_jsobject().get()); rooted!(in(scope.get_cx()) let mut message = UndefinedValue()); data.read(scope.upcast(), message.handle_mut()); MessageEvent::dispatch_jsval(target, scope.upcast(), message.handle(), None); @@ -392,33 +429,33 @@ impl DedicatedWorkerGlobalScope { fn handle_mixed_message(&self, msg: MixedMessage) { match msg { - MixedMessage::FromDevtools(msg) => { - match msg { - DevtoolScriptControlMsg::EvaluateJS(_pipe_id, string, sender) => - devtools::handle_evaluate_js(self.upcast(), string, sender), - DevtoolScriptControlMsg::GetCachedMessages(pipe_id, message_types, sender) => - devtools::handle_get_cached_messages(pipe_id, message_types, sender), - DevtoolScriptControlMsg::WantsLiveNotifications(_pipe_id, bool_val) => - devtools::handle_wants_live_notifications(self.upcast(), bool_val), - _ => debug!("got an unusable devtools control message inside the worker!"), - } + MixedMessage::FromDevtools(msg) => match msg { + DevtoolScriptControlMsg::EvaluateJS(_pipe_id, string, sender) => { + devtools::handle_evaluate_js(self.upcast(), string, sender) + }, + DevtoolScriptControlMsg::GetCachedMessages(pipe_id, message_types, sender) => { + devtools::handle_get_cached_messages(pipe_id, message_types, sender) + }, + DevtoolScriptControlMsg::WantsLiveNotifications(_pipe_id, bool_val) => { + devtools::handle_wants_live_notifications(self.upcast(), bool_val) + }, + _ => debug!("got an unusable devtools control message inside the worker!"), }, - MixedMessage::FromScheduler((linked_worker, timer_event)) => { - match timer_event { - TimerEvent(TimerSource::FromWorker, id) => { - let _ar = AutoWorkerReset::new(self, linked_worker); - let scope = self.upcast::<WorkerGlobalScope>(); - scope.handle_fire_timer(id); - }, - TimerEvent(_, _) => { - panic!("A worker received a TimerEvent from a window.") - } - } - } - MixedMessage::FromWorker(DedicatedWorkerScriptMsg::CommonWorker(linked_worker, msg)) => { + MixedMessage::FromScheduler((linked_worker, timer_event)) => match timer_event { + TimerEvent(TimerSource::FromWorker, id) => { + let _ar = AutoWorkerReset::new(self, linked_worker); + let scope = self.upcast::<WorkerGlobalScope>(); + scope.handle_fire_timer(id); + }, + TimerEvent(_, _) => panic!("A worker received a TimerEvent from a window."), + }, + MixedMessage::FromWorker(DedicatedWorkerScriptMsg::CommonWorker( + linked_worker, + msg, + )) => { let _ar = AutoWorkerReset::new(self, linked_worker); self.handle_script_event(msg); - } + }, MixedMessage::FromWorker(DedicatedWorkerScriptMsg::WakeUp) => {}, } } @@ -452,20 +489,20 @@ impl DedicatedWorkerGlobalScope { global.report_an_error(error_info, HandleValue::null()); } })); - self.parent_sender.send(CommonScriptMsg::Task( - WorkerEvent, - task, - Some(pipeline_id), - TaskSourceName::DOMManipulation, + self.parent_sender + .send(CommonScriptMsg::Task( + WorkerEvent, + task, + Some(pipeline_id), + TaskSourceName::DOMManipulation, )).unwrap(); } } #[allow(unsafe_code)] unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool { - let worker = - DomRoot::downcast::<WorkerGlobalScope>(GlobalScope::from_context(cx)) - .expect("global is not a worker scope"); + let worker = DomRoot::downcast::<WorkerGlobalScope>(GlobalScope::from_context(cx)) + .expect("global is not a worker scope"); assert!(worker.is::<DedicatedWorkerGlobalScope>()); // A false response causes the script to terminate @@ -483,12 +520,13 @@ impl DedicatedWorkerGlobalScopeMethods for DedicatedWorkerGlobalScope { Worker::handle_message(worker, data); })); // TODO: Change this task source to a new `unshipped-port-message-queue` task source - self.parent_sender.send(CommonScriptMsg::Task( - WorkerEvent, - task, - Some(pipeline_id), - TaskSourceName::DOMManipulation, - )).unwrap(); + self.parent_sender + .send(CommonScriptMsg::Task( + WorkerEvent, + task, + Some(pipeline_id), + TaskSourceName::DOMManipulation, + )).unwrap(); Ok(()) } diff --git a/components/script/dom/dissimilaroriginlocation.rs b/components/script/dom/dissimilaroriginlocation.rs index 5c98e20bf5e..0f8fe5bd394 100644 --- a/components/script/dom/dissimilaroriginlocation.rs +++ b/components/script/dom/dissimilaroriginlocation.rs @@ -40,9 +40,11 @@ impl DissimilarOriginLocation { } pub fn new(window: &DissimilarOriginWindow) -> DomRoot<DissimilarOriginLocation> { - reflect_dom_object(Box::new(DissimilarOriginLocation::new_inherited(window)), - window, - DissimilarOriginLocationBinding::Wrap) + reflect_dom_object( + Box::new(DissimilarOriginLocation::new_inherited(window)), + window, + DissimilarOriginLocationBinding::Wrap, + ) } #[allow(dead_code)] diff --git a/components/script/dom/dissimilaroriginwindow.rs b/components/script/dom/dissimilaroriginwindow.rs index 68b4ca894cf..40897b2bf52 100644 --- a/components/script/dom/dissimilaroriginwindow.rs +++ b/components/script/dom/dissimilaroriginwindow.rs @@ -46,10 +46,7 @@ pub struct DissimilarOriginWindow { impl DissimilarOriginWindow { #[allow(unsafe_code)] - pub fn new( - global_to_clone_from: &GlobalScope, - window_proxy: &WindowProxy, - ) -> DomRoot<Self> { + pub fn new(global_to_clone_from: &GlobalScope, window_proxy: &WindowProxy) -> DomRoot<Self> { let cx = global_to_clone_from.get_cx(); // Any timer events fired on this window are ignored. let (timer_event_chan, _) = ipc::channel().unwrap(); @@ -142,7 +139,12 @@ impl DissimilarOriginWindowMethods for DissimilarOriginWindow { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-window-postmessage - unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue, origin: DOMString) -> ErrorResult { + unsafe fn PostMessage( + &self, + cx: *mut JSContext, + message: HandleValue, + origin: DOMString, + ) -> ErrorResult { // Step 3-5. let origin = match &origin[..] { "*" => None, @@ -153,7 +155,7 @@ impl DissimilarOriginWindowMethods for DissimilarOriginWindow { url => match ServoUrl::parse(&url) { Ok(url) => Some(url.origin()), Err(_) => return Err(Error::Syntax), - } + }, }; // Step 1-2, 6-8. @@ -190,7 +192,8 @@ impl DissimilarOriginWindowMethods for DissimilarOriginWindow { // https://html.spec.whatwg.org/multipage/#dom-location fn Location(&self) -> DomRoot<DissimilarOriginLocation> { - self.location.or_init(|| DissimilarOriginLocation::new(self)) + self.location + .or_init(|| DissimilarOriginLocation::new(self)) } } @@ -200,9 +203,11 @@ impl DissimilarOriginWindow { None => return warn!("postMessage called with no incumbent global"), Some(incumbent) => incumbent, }; - let msg = ScriptMsg::PostMessage(self.window_proxy.browsing_context_id(), - origin, - data.move_to_arraybuffer()); + let msg = ScriptMsg::PostMessage( + self.window_proxy.browsing_context_id(), + origin, + data.move_to_arraybuffer(), + ); let _ = incumbent.script_to_constellation_chan().send(msg); } } diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index a463ec8c4e2..d68f085af83 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -417,7 +417,7 @@ struct LinksFilter; impl CollectionFilter for LinksFilter { fn filter(&self, elem: &Element, _root: &Node) -> bool { (elem.is::<HTMLAnchorElement>() || elem.is::<HTMLAreaElement>()) && - elem.has_attribute(&local_name!("href")) + elem.has_attribute(&local_name!("href")) } } @@ -457,7 +457,9 @@ impl Document { } #[inline] - pub fn has_browsing_context(&self) -> bool { self.has_browsing_context } + pub fn has_browsing_context(&self) -> bool { + self.has_browsing_context + } /// <https://html.spec.whatwg.org/multipage/#concept-document-bc> #[inline] @@ -500,14 +502,17 @@ impl Document { if activity == DocumentActivity::FullyActive { self.title_changed(); self.dirty_all_nodes(); - self.window().reflow(ReflowGoal::Full, ReflowReason::CachedPageNeededReflow); + self.window() + .reflow(ReflowGoal::Full, ReflowReason::CachedPageNeededReflow); self.window().resume(); // html.spec.whatwg.org/multipage/#history-traversal // Step 4.6 if self.ready_state.get() == DocumentReadyState::Complete { let document = Trusted::new(self); - self.window.dom_manipulation_task_source().queue( - task!(fire_pageshow_event: move || { + self.window + .dom_manipulation_task_source() + .queue( + task!(fire_pageshow_event: move || { let document = document.root(); let window = document.window(); // Step 4.6.1 @@ -532,8 +537,8 @@ impl Document { &event, ); }), - self.window.upcast(), - ).unwrap(); + self.window.upcast(), + ).unwrap(); } } else { self.window().suspend(); @@ -580,11 +585,10 @@ impl Document { // FIXME: This should check the dirty bit on the document, // not the document element. Needs some layout changes to make // that workable. - self.stylesheets.borrow().has_changed() || - self.GetDocumentElement().map_or(false, |root| { + self.stylesheets.borrow().has_changed() || self.GetDocumentElement().map_or(false, |root| { root.upcast::<Node>().has_dirty_descendants() || - !self.pending_restyles.borrow().is_empty() || - self.needs_paint() + !self.pending_restyles.borrow().is_empty() || + self.needs_paint() }) } @@ -596,10 +600,15 @@ impl Document { /// Refresh the cached first base element in the DOM. /// <https://github.com/w3c/web-platform-tests/issues/2122> pub fn refresh_base_element(&self) { - let base = self.upcast::<Node>() - .traverse_preorder() - .filter_map(DomRoot::downcast::<HTMLBaseElement>) - .find(|element| element.upcast::<Element>().has_attribute(&local_name!("href"))); + let base = self + .upcast::<Node>() + .traverse_preorder() + .filter_map(DomRoot::downcast::<HTMLBaseElement>) + .find(|element| { + element + .upcast::<Element>() + .has_attribute(&local_name!("href")) + }); self.base_element.set(base.r()); } @@ -627,7 +636,10 @@ impl Document { self.quirks_mode.set(mode); if mode == QuirksMode::Quirks { - self.window.layout_chan().send(Msg::SetQuirksMode(mode)).unwrap(); + self.window + .layout_chan() + .send(Msg::SetQuirksMode(mode)) + .unwrap(); } } @@ -657,7 +669,8 @@ impl Document { } self.reflow_timeout.set(None); - self.window.reflow(ReflowGoal::Full, ReflowReason::RefreshTick); + self.window + .reflow(ReflowGoal::Full, ReflowReason::RefreshTick); } } @@ -675,10 +688,10 @@ impl Document { /// Remove any existing association between the provided id and any elements in this document. pub fn unregister_named_element(&self, to_unregister: &Element, id: Atom) { - debug!("Removing named element from document {:p}: {:p} id={}", - self, - to_unregister, - id); + debug!( + "Removing named element from document {:p}: {:p} id={}", + self, to_unregister, id + ); // Limit the scope of the borrow because id_map might be borrowed again by // GetElementById through the following sequence of calls // reset_form_owner_for_listeners -> reset_form_owner -> GetElementById @@ -687,12 +700,13 @@ impl Document { let is_empty = match id_map.get_mut(&id) { None => false, Some(elements) => { - let position = elements.iter() - .position(|element| &**element == to_unregister) - .expect("This element should be in registered."); + let position = elements + .iter() + .position(|element| &**element == to_unregister) + .expect("This element should be in registered."); elements.remove(position); elements.is_empty() - } + }, }; if is_empty { id_map.remove(&id); @@ -703,16 +717,17 @@ impl Document { /// Associate an element present in this document with the provided id. pub fn register_named_element(&self, element: &Element, id: Atom) { - debug!("Adding named element to document {:p}: {:p} id={}", - self, - element, - id); + debug!( + "Adding named element to document {:p}: {:p} id={}", + self, element, id + ); assert!(element.upcast::<Node>().is_in_doc()); assert!(!id.is_empty()); - let root = self.GetDocumentElement() - .expect("The element is in the document, so there must be a document \ - element."); + let root = self.GetDocumentElement().expect( + "The element is in the document, so there must be a document \ + element.", + ); // Limit the scope of the borrow because id_map might be borrowed again by // GetElementById through the following sequence of calls @@ -732,10 +747,16 @@ impl Document { set.insert(Dom::from_ref(listener)); } - pub fn unregister_form_id_listener<T: ?Sized + FormControl>(&self, id: DOMString, listener: &T) { + pub fn unregister_form_id_listener<T: ?Sized + FormControl>( + &self, + id: DOMString, + listener: &T, + ) { let mut map = self.form_id_listener_map.borrow_mut(); if let Occupied(mut entry) = map.entry(Atom::from(id)) { - entry.get_mut().remove(&Dom::from_ref(listener.to_element())); + entry + .get_mut() + .remove(&Dom::from_ref(listener.to_element())); if entry.get().is_empty() { entry.remove(); } @@ -765,37 +786,46 @@ impl Document { // Step 1 self.set_target_element(target.r()); - let point = target.r().map(|element| { - // FIXME(#8275, pcwalton): This is pretty bogus when multiple layers are involved. - // Really what needs to happen is that this needs to go through layout to ask which - // layer the element belongs to, and have it send the scroll message to the - // compositor. - let rect = element.upcast::<Node>().bounding_content_box_or_zero(); - - // In order to align with element edges, we snap to unscaled pixel boundaries, since - // the paint thread currently does the same for drawing elements. This is important - // for pages that require pixel perfect scroll positioning for proper display - // (like Acid2). Since we don't have the device pixel ratio here, this might not be - // accurate, but should work as long as the ratio is a whole number. Once #8275 is - // fixed this should actually take into account the real device pixel ratio. - (rect.origin.x.to_nearest_px() as f32, rect.origin.y.to_nearest_px() as f32) - }).or_else(|| if fragment.is_empty() || fragment.eq_ignore_ascii_case("top") { - // FIXME(stshine): this should be the origin of the stacking context space, - // which may differ under the influence of writing mode. - Some((0.0, 0.0)) - } else { - None - }); + let point = target + .r() + .map(|element| { + // FIXME(#8275, pcwalton): This is pretty bogus when multiple layers are involved. + // Really what needs to happen is that this needs to go through layout to ask which + // layer the element belongs to, and have it send the scroll message to the + // compositor. + let rect = element.upcast::<Node>().bounding_content_box_or_zero(); + + // In order to align with element edges, we snap to unscaled pixel boundaries, since + // the paint thread currently does the same for drawing elements. This is important + // for pages that require pixel perfect scroll positioning for proper display + // (like Acid2). Since we don't have the device pixel ratio here, this might not be + // accurate, but should work as long as the ratio is a whole number. Once #8275 is + // fixed this should actually take into account the real device pixel ratio. + ( + rect.origin.x.to_nearest_px() as f32, + rect.origin.y.to_nearest_px() as f32, + ) + }).or_else(|| { + if fragment.is_empty() || fragment.eq_ignore_ascii_case("top") { + // FIXME(stshine): this should be the origin of the stacking context space, + // which may differ under the influence of writing mode. + Some((0.0, 0.0)) + } else { + None + } + }); if let Some((x, y)) = point { // Step 3 let global_scope = self.window.upcast::<GlobalScope>(); self.window.update_viewport_for_scroll(x, y); - self.window.perform_a_scroll(x, - y, - global_scope.pipeline_id().root_scroll_id(), - ScrollBehavior::Instant, - target.r()); + self.window.perform_a_scroll( + x, + y, + global_scope.pipeline_id().root_scroll_id(), + ScrollBehavior::Instant, + target.r(), + ); } } @@ -806,10 +836,11 @@ impl Document { .map_or(false, |attr| &**attr.value() == name) }; let doc_node = self.upcast::<Node>(); - doc_node.traverse_preorder() - .filter_map(DomRoot::downcast) - .find(|node| check_anchor(&node)) - .map(DomRoot::upcast) + doc_node + .traverse_preorder() + .filter_map(DomRoot::downcast) + .find(|node| check_anchor(&node)) + .map(DomRoot::upcast) } // https://html.spec.whatwg.org/multipage/#current-document-readiness @@ -826,7 +857,8 @@ impl Document { self.ready_state.set(state); - self.upcast::<EventTarget>().fire_event(atom!("readystatechange")); + self.upcast::<EventTarget>() + .fire_event(atom!("readystatechange")); } /// Return whether scripting is enabled or not @@ -857,7 +889,7 @@ impl Document { /// transaction, or none if no elements requested it. pub fn commit_focus_transaction(&self, focus_type: FocusType) { if self.focused == self.possibly_focused.get().r() { - return + return; } if let Some(ref elem) = self.focused.get() { let node = elem.upcast::<Node>(); @@ -927,7 +959,7 @@ impl Document { client_point: Point2D<f32>, mouse_event_type: MouseEventType, node_address: Option<UntrustedNodeAddress>, - point_in_node: Option<Point2D<f32>> + point_in_node: Option<Point2D<f32>>, ) { let mouse_event_type_string = match mouse_event_type { MouseEventType::Click => "click".to_owned(), @@ -1012,7 +1044,8 @@ impl Document { self.maybe_fire_dblclick(client_point, node); } - self.window.reflow(ReflowGoal::Full, ReflowReason::MouseEvent); + self.window + .reflow(ReflowGoal::Full, ReflowReason::MouseEvent); } fn maybe_fire_dblclick(&self, click_pos: Point2D<f32>, target: &Node) { @@ -1022,16 +1055,24 @@ impl Document { let opt = self.last_click_info.borrow_mut().take(); if let Some((last_time, last_pos)) = opt { - let DBL_CLICK_TIMEOUT = Duration::from_millis(PREFS.get("dom.document.dblclick_timeout").as_u64() - .unwrap_or(300)); - let DBL_CLICK_DIST_THRESHOLD = PREFS.get("dom.document.dblclick_dist").as_u64().unwrap_or(1); + let DBL_CLICK_TIMEOUT = Duration::from_millis( + PREFS + .get("dom.document.dblclick_timeout") + .as_u64() + .unwrap_or(300), + ); + let DBL_CLICK_DIST_THRESHOLD = PREFS + .get("dom.document.dblclick_dist") + .as_u64() + .unwrap_or(1); // Calculate distance between this click and the previous click. let line = click_pos - last_pos; let dist = (line.dot(line) as f64).sqrt(); if now.duration_since(last_time) < DBL_CLICK_TIMEOUT && - dist < DBL_CLICK_DIST_THRESHOLD as f64 { + dist < DBL_CLICK_DIST_THRESHOLD as f64 + { // A double click has occurred if this click is within a certain time and dist. of previous click. let click_count = 2; let client_x = click_pos.x as i32; @@ -1054,7 +1095,7 @@ impl Document { false, 0i16, None, - None + None, ); event.upcast::<Event>().fire(target.upcast()); @@ -1068,7 +1109,12 @@ impl Document { *self.last_click_info.borrow_mut() = Some((now, click_pos)); } - pub fn fire_mouse_event(&self, client_point: Point2D<f32>, target: &EventTarget, event_name: FireMouseEventType) { + pub fn fire_mouse_event( + &self, + client_point: Point2D<f32>, + target: &EventTarget, + event_name: FireMouseEventType, + ) { let client_x = client_point.x.to_i32().unwrap_or(0); let client_y = client_point.y.to_i32().unwrap_or(0); @@ -1089,7 +1135,7 @@ impl Document { false, 0i16, None, - None + None, ); let event = mouse_event.upcast::<Event>(); event.fire(target); @@ -1101,7 +1147,7 @@ impl Document { js_runtime: *mut JSRuntime, client_point: Option<Point2D<f32>>, prev_mouse_over_target: &MutNullableDom<Element>, - node_address: Option<UntrustedNodeAddress> + node_address: Option<UntrustedNodeAddress>, ) { let client_point = match client_point { None => { @@ -1109,7 +1155,7 @@ impl Document { // FIXME: dispatch mouseout here. We have no point. prev_mouse_over_target.set(None); return; - } + }, Some(client_point) => client_point, }; @@ -1135,11 +1181,13 @@ impl Document { return; } - let old_target_is_ancestor_of_new_target = match (prev_mouse_over_target.get(), maybe_new_target.as_ref()) { - (Some(old_target), Some(new_target)) - => old_target.upcast::<Node>().is_ancestor_of(new_target.upcast::<Node>()), - _ => false, - }; + let old_target_is_ancestor_of_new_target = + match (prev_mouse_over_target.get(), maybe_new_target.as_ref()) { + (Some(old_target), Some(new_target)) => old_target + .upcast::<Node>() + .is_ancestor_of(new_target.upcast::<Node>()), + _ => false, + }; // Here we know the target has changed, so we must update the state, // dispatch mouseout to the previous one, mouseover to the new one, @@ -1147,9 +1195,11 @@ impl Document { // If the old target is an ancestor of the new target, this can be skipped // completely, since the node's hover state will be reseted below. if !old_target_is_ancestor_of_new_target { - for element in old_target.upcast::<Node>() - .inclusive_ancestors() - .filter_map(DomRoot::downcast::<Element>) { + for element in old_target + .upcast::<Node>() + .inclusive_ancestors() + .filter_map(DomRoot::downcast::<Element>) + { element.set_hover_state(false); element.set_active_state(false); } @@ -1163,9 +1213,11 @@ impl Document { } if let Some(ref new_target) = maybe_new_target { - for element in new_target.upcast::<Node>() - .inclusive_ancestors() - .filter_map(DomRoot::downcast::<Element>) { + for element in new_target + .upcast::<Node>() + .inclusive_ancestors() + .filter_map(DomRoot::downcast::<Element>) + { if element.hover_state() { break; } @@ -1181,7 +1233,8 @@ impl Document { // Store the current mouse over target for next frame. prev_mouse_over_target.set(maybe_new_target.r()); - self.window.reflow(ReflowGoal::Full, ReflowReason::MouseEvent); + self.window + .reflow(ReflowGoal::Full, ReflowReason::MouseEvent); } #[allow(unsafe_code)] @@ -1191,7 +1244,7 @@ impl Document { event_type: TouchEventType, touch_id: TouchId, point: Point2D<f32>, - node_address: Option<UntrustedNodeAddress> + node_address: Option<UntrustedNodeAddress>, ) -> TouchEventResult { let TouchId(identifier) = touch_id; @@ -1221,40 +1274,43 @@ impl Document { let page_x = Finite::wrap(point.x as f64 + window.PageXOffset() as f64); let page_y = Finite::wrap(point.y as f64 + window.PageYOffset() as f64); - let touch = Touch::new(window, - identifier, - &target, - client_x, - client_y, // TODO: Get real screen coordinates? - client_x, - client_y, - page_x, - page_y); + let touch = Touch::new( + window, identifier, &target, client_x, + client_y, // TODO: Get real screen coordinates? + client_x, client_y, page_x, page_y, + ); match event_type { TouchEventType::Down => { // Add a new touch point - self.active_touch_points.borrow_mut().push(Dom::from_ref(&*touch)); - } + self.active_touch_points + .borrow_mut() + .push(Dom::from_ref(&*touch)); + }, TouchEventType::Move => { // Replace an existing touch point let mut active_touch_points = self.active_touch_points.borrow_mut(); - match active_touch_points.iter_mut().find(|t| t.Identifier() == identifier) { + match active_touch_points + .iter_mut() + .find(|t| t.Identifier() == identifier) + { Some(t) => *t = Dom::from_ref(&*touch), None => warn!("Got a touchmove event for a non-active touch point"), } - } - TouchEventType::Up | - TouchEventType::Cancel => { + }, + TouchEventType::Up | TouchEventType::Cancel => { // Remove an existing touch point let mut active_touch_points = self.active_touch_points.borrow_mut(); - match active_touch_points.iter().position(|t| t.Identifier() == identifier) { + match active_touch_points + .iter() + .position(|t| t.Identifier() == identifier) + { Some(i) => { active_touch_points.swap_remove(i); - } + }, None => warn!("Got a touchend event for a non-active touch point"), } - } + }, } rooted_vec!(let mut target_touches); @@ -1292,11 +1348,13 @@ impl Document { } /// The entry point for all key processing for web content - pub fn dispatch_key_event(&self, - ch: Option<char>, - key: Key, - state: KeyState, - modifiers: KeyModifiers) { + pub fn dispatch_key_event( + &self, + ch: Option<char>, + key: Key, + state: KeyState, + modifiers: KeyModifiers, + ) { let focused = self.get_focused_element(); let body = self.GetBody(); @@ -1313,59 +1371,67 @@ impl Document { let is_composing = false; let is_repeating = state == KeyState::Repeated; - let ev_type = DOMString::from(match state { - KeyState::Pressed | KeyState::Repeated => "keydown", - KeyState::Released => "keyup", - } - .to_owned()); + let ev_type = DOMString::from( + match state { + KeyState::Pressed | KeyState::Repeated => "keydown", + KeyState::Released => "keyup", + }.to_owned(), + ); let props = KeyboardEvent::key_properties(ch, key, modifiers); - let keyevent = KeyboardEvent::new(&self.window, - ev_type, - true, - true, - Some(&self.window), - 0, - ch, - Some(key), - DOMString::from(props.key_string.clone()), - DOMString::from(props.code), - props.location, - is_repeating, - is_composing, - ctrl, - alt, - shift, - meta, - None, - props.key_code); + let keyevent = KeyboardEvent::new( + &self.window, + ev_type, + true, + true, + Some(&self.window), + 0, + ch, + Some(key), + DOMString::from(props.key_string.clone()), + DOMString::from(props.code), + props.location, + is_repeating, + is_composing, + ctrl, + alt, + shift, + meta, + None, + props.key_code, + ); let event = keyevent.upcast::<Event>(); event.fire(target); let mut cancel_state = event.get_cancel_state(); // https://w3c.github.io/uievents/#keys-cancelable-keys - if state != KeyState::Released && props.is_printable() && cancel_state != EventDefault::Prevented { + if state != KeyState::Released && + props.is_printable() && + cancel_state != EventDefault::Prevented + { // https://w3c.github.io/uievents/#keypress-event-order - let event = KeyboardEvent::new(&self.window, - DOMString::from("keypress"), - true, - true, - Some(&self.window), - 0, - ch, - Some(key), - DOMString::from(props.key_string), - DOMString::from(props.code), - props.location, - is_repeating, - is_composing, - ctrl, - alt, - shift, - meta, - props.char_code, - 0); + let event = KeyboardEvent::new( + &self.window, + DOMString::from("keypress"), + true, + true, + Some(&self.window), + 0, + ch, + Some(key), + DOMString::from(props.key_string), + DOMString::from(props.code), + props.location, + is_repeating, + is_composing, + ctrl, + alt, + shift, + meta, + props.char_code, + 0, + ); let ev = event.upcast::<Event>(); ev.fire(target); cancel_state = ev.get_cancel_state(); @@ -1384,14 +1450,16 @@ impl Document { Key::Space if state == KeyState::Released => { let maybe_elem = target.downcast::<Element>(); if let Some(el) = maybe_elem { - synthetic_click_activation(el, - false, - false, - false, - false, - ActivationSource::NotFromClick) + synthetic_click_activation( + el, + false, + false, + false, + false, + ActivationSource::NotFromClick, + ) } - } + }, Key::Enter if state == KeyState::Released => { let maybe_elem = target.downcast::<Element>(); if let Some(el) = maybe_elem { @@ -1399,7 +1467,7 @@ impl Document { a.implicit_submission(ctrl, alt, shift, meta); } } - } + }, _ => (), } } @@ -1408,9 +1476,10 @@ impl Document { } // https://dom.spec.whatwg.org/#converting-nodes-into-a-node - pub fn node_from_nodes_and_strings(&self, - mut nodes: Vec<NodeOrString>) - -> Fallible<DomRoot<Node>> { + pub fn node_from_nodes_and_strings( + &self, + mut nodes: Vec<NodeOrString>, + ) -> Fallible<DomRoot<Node>> { if nodes.len() == 1 { Ok(match nodes.pop().unwrap() { NodeOrString::Node(node) => node, @@ -1428,7 +1497,7 @@ impl Document { // No try!() here because appending a text node // should not fail. fragment.AppendChild(&node).unwrap(); - } + }, } } Ok(fragment) @@ -1436,16 +1505,20 @@ impl Document { } pub fn get_body_attribute(&self, local_name: &LocalName) -> DOMString { - match self.GetBody().and_then(DomRoot::downcast::<HTMLBodyElement>) { - Some(ref body) => { - body.upcast::<Element>().get_string_attribute(local_name) - }, + match self + .GetBody() + .and_then(DomRoot::downcast::<HTMLBodyElement>) + { + Some(ref body) => body.upcast::<Element>().get_string_attribute(local_name), None => DOMString::new(), } } pub fn set_body_attribute(&self, local_name: &LocalName, value: DOMString) { - if let Some(ref body) = self.GetBody().and_then(DomRoot::downcast::<HTMLBodyElement>) { + if let Some(ref body) = self + .GetBody() + .and_then(DomRoot::downcast::<HTMLBodyElement>) + { let body = body.upcast::<Element>(); let value = body.parse_attribute(&ns!(), &local_name, value); body.set_attribute(local_name, value); @@ -1487,7 +1560,9 @@ impl Document { let ident = self.animation_frame_ident.get() + 1; self.animation_frame_ident.set(ident); - self.animation_frame_list.borrow_mut().push((ident, Some(callback))); + self.animation_frame_list + .borrow_mut() + .push((ident, Some(callback))); // TODO: Should tick animation only when document is visible @@ -1497,9 +1572,10 @@ impl Document { let callback = FakeRequestAnimationFrameCallback { document: Trusted::new(self), }; - self.global() - .schedule_callback(OneshotTimerCallback::FakeRequestAnimationFrame(callback), - MsDuration::new(FAKE_REQUEST_ANIMATION_FRAME_DELAY)); + self.global().schedule_callback( + OneshotTimerCallback::FakeRequestAnimationFrame(callback), + MsDuration::new(FAKE_REQUEST_ANIMATION_FRAME_DELAY), + ); } else if !self.running_animation_callbacks.get() { // No need to send a `ChangeRunningAnimationsState` if we're running animation callbacks: // we're guaranteed to already be in the "animation callbacks present" state. @@ -1507,7 +1583,8 @@ impl Document { // This reduces CPU usage by avoiding needless thread wakeups in the common case of // repeated rAF. - let event = ScriptMsg::ChangeRunningAnimationsState(AnimationState::AnimationCallbacksPresent); + let event = + ScriptMsg::ChangeRunningAnimationsState(AnimationState::AnimationCallbacksPresent); self.window().send_to_constellation(event); } @@ -1527,7 +1604,8 @@ impl Document { rooted_vec!(let mut animation_frame_list); mem::swap( &mut *animation_frame_list, - &mut *self.animation_frame_list.borrow_mut()); + &mut *self.animation_frame_list.borrow_mut(), + ); self.running_animation_callbacks.set(true); let was_faking_animation_frames = self.is_faking_animation_frames(); @@ -1541,7 +1619,9 @@ impl Document { self.running_animation_callbacks.set(false); - let spurious = !self.window.reflow(ReflowGoal::Full, ReflowReason::RequestAnimationFrame); + let spurious = !self + .window + .reflow(ReflowGoal::Full, ReflowReason::RequestAnimationFrame); if spurious && !was_faking_animation_frames { // If the rAF callbacks did not mutate the DOM, then the @@ -1554,7 +1634,8 @@ impl Document { // for the interim frames where we are deciding whether this rAF // is considered spurious, we need to ensure that the layout // and compositor *do* tick the animation. - self.window.force_reflow(ReflowGoal::Full, ReflowReason::RequestAnimationFrame); + self.window + .force_reflow(ReflowGoal::Full, ReflowReason::RequestAnimationFrame); } // Only send the animation change state message after running any callbacks. @@ -1578,23 +1659,29 @@ impl Document { &mut *animation_frame_list, ); } - let event = ScriptMsg::ChangeRunningAnimationsState(AnimationState::NoAnimationCallbacksPresent); + let event = ScriptMsg::ChangeRunningAnimationsState( + AnimationState::NoAnimationCallbacksPresent, + ); self.window().send_to_constellation(event); } // Update the counter of spurious animation frames. if spurious { if self.spurious_animation_frames.get() < SPURIOUS_ANIMATION_FRAME_THRESHOLD { - self.spurious_animation_frames.set(self.spurious_animation_frames.get() + 1) + self.spurious_animation_frames + .set(self.spurious_animation_frames.get() + 1) } } else { self.spurious_animation_frames.set(0) } } - pub fn fetch_async(&self, load: LoadType, - request: RequestInit, - fetch_target: IpcSender<FetchResponseMsg>) { + pub fn fetch_async( + &self, + load: LoadType, + request: RequestInit, + fetch_target: IpcSender<FetchResponseMsg>, + ) { let mut loader = self.loader.borrow_mut(); loader.fetch_async(load, request, fetch_target); } @@ -1620,7 +1707,8 @@ impl Document { // Disarm the reflow timer and trigger the initial reflow. self.reflow_timeout.set(None); self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage); - self.window.reflow(ReflowGoal::Full, ReflowReason::FirstLoad); + self.window + .reflow(ReflowGoal::Full, ReflowReason::FirstLoad); } // Deferred scripts have to wait for page to finish loading, @@ -1660,18 +1748,17 @@ impl Document { self.incr_ignore_opens_during_unload_counter(); //Step 3-5. let document = Trusted::new(self); - let beforeunload_event = BeforeUnloadEvent::new(&self.window, - atom!("beforeunload"), - EventBubbles::Bubbles, - EventCancelable::Cancelable); + let beforeunload_event = BeforeUnloadEvent::new( + &self.window, + atom!("beforeunload"), + EventBubbles::Bubbles, + EventCancelable::Cancelable, + ); let event = beforeunload_event.upcast::<Event>(); event.set_trusted(true); let event_target = self.window.upcast::<EventTarget>(); let has_listeners = event.has_listeners_for(&event_target, &atom!("beforeunload")); - event_target.dispatch_event_with_target( - document.root().upcast(), - &event, - ); + event_target.dispatch_event_with_target(document.root().upcast(), &event); // TODO: Step 6, decrease the event loop's termination nesting level by 1. // Step 7 if has_listeners { @@ -1680,7 +1767,11 @@ impl Document { let mut can_unload = true; // TODO: Step 8, also check sandboxing modals flag. let default_prevented = event.DefaultPrevented(); - let return_value_not_empty = !event.downcast::<BeforeUnloadEvent>().unwrap().ReturnValue().is_empty(); + let return_value_not_empty = !event + .downcast::<BeforeUnloadEvent>() + .unwrap() + .ReturnValue() + .is_empty(); if default_prevented || return_value_not_empty { let (chan, port) = ipc::channel().expect("Failed to create IPC channel!"); let msg = EmbedderMsg::AllowUnload(chan); @@ -1694,7 +1785,7 @@ impl Document { let document = document_from_node(&*iframe); can_unload = document.prompt_to_unload(true); if !document.salvageable() { - self.salvageable.set(false); + self.salvageable.set(false); } if !can_unload { break; @@ -1718,16 +1809,16 @@ impl Document { let event = PageTransitionEvent::new( &self.window, atom!("pagehide"), - false, // bubbles - false, // cancelable + false, // bubbles + false, // cancelable self.salvageable.get(), // persisted ); let event = event.upcast::<Event>(); event.set_trusted(true); - let _ = self.window.upcast::<EventTarget>().dispatch_event_with_target( - document.root().upcast(), - &event, - ); + let _ = self + .window + .upcast::<EventTarget>() + .dispatch_event_with_target(document.root().upcast(), &event); // TODO Step 6, document visibility steps. } // Step 7 @@ -1741,10 +1832,7 @@ impl Document { event.set_trusted(true); let event_target = self.window.upcast::<EventTarget>(); let has_listeners = event.has_listeners_for(&event_target, &atom!("unload")); - let _ = event_target.dispatch_event_with_target( - document.root().upcast(), - &event, - ); + let _ = event_target.dispatch_event_with_target(document.root().upcast(), &event); self.fired_unload.set(true); // Step 9 if has_listeners { @@ -1791,8 +1879,10 @@ impl Document { // Step 7. debug!("Document loads are complete."); let document = Trusted::new(self); - self.window.dom_manipulation_task_source().queue( - task!(fire_load_event: move || { + self.window + .dom_manipulation_task_source() + .queue( + task!(fire_load_event: move || { let document = document.root(); let window = document.window(); if !window.is_alive() { @@ -1835,14 +1925,16 @@ impl Document { document.check_and_scroll_fragment(fragment); } }), - self.window.upcast(), - ).unwrap(); + self.window.upcast(), + ).unwrap(); // Step 8. let document = Trusted::new(self); if document.root().browsing_context().is_some() { - self.window.dom_manipulation_task_source().queue( - task!(fire_pageshow_event: move || { + self.window + .dom_manipulation_task_source() + .queue( + task!(fire_pageshow_event: move || { let document = document.root(); let window = document.window(); if document.page_showing.get() || !window.is_alive() { @@ -1867,8 +1959,8 @@ impl Document { &event, ); }), - self.window.upcast(), - ).unwrap(); + self.window.upcast(), + ).unwrap(); } // Step 9. @@ -1885,11 +1977,14 @@ impl Document { } // https://html.spec.whatwg.org/multipage/#pending-parsing-blocking-script - pub fn set_pending_parsing_blocking_script(&self, - script: &HTMLScriptElement, - load: Option<ScriptResult>) { + pub fn set_pending_parsing_blocking_script( + &self, + script: &HTMLScriptElement, + load: Option<ScriptResult>, + ) { assert!(!self.has_pending_parsing_blocking_script()); - *self.pending_parsing_blocking_script.borrow_mut() = Some(PendingScript::new_with_load(script, load)); + *self.pending_parsing_blocking_script.borrow_mut() = + Some(PendingScript::new_with_load(script, load)); } // https://html.spec.whatwg.org/multipage/#pending-parsing-blocking-script @@ -1898,7 +1993,11 @@ impl Document { } /// https://html.spec.whatwg.org/multipage/#prepare-a-script step 22.d. - pub fn pending_parsing_blocking_script_loaded(&self, element: &HTMLScriptElement, result: ScriptResult) { + pub fn pending_parsing_blocking_script_loaded( + &self, + element: &HTMLScriptElement, + result: ScriptResult, + ) { { let mut blocking_script = self.pending_parsing_blocking_script.borrow_mut(); let entry = blocking_script.as_mut().unwrap(); @@ -1912,19 +2011,24 @@ impl Document { if self.script_blocking_stylesheets_count.get() > 0 { return; } - let pair = self.pending_parsing_blocking_script + let pair = self + .pending_parsing_blocking_script .borrow_mut() .as_mut() .and_then(PendingScript::take_result); if let Some((element, result)) = pair { *self.pending_parsing_blocking_script.borrow_mut() = None; - self.get_current_parser().unwrap().resume_with_pending_parsing_blocking_script(&element, result); + self.get_current_parser() + .unwrap() + .resume_with_pending_parsing_blocking_script(&element, result); } } // https://html.spec.whatwg.org/multipage/#set-of-scripts-that-will-execute-as-soon-as-possible pub fn add_asap_script(&self, script: &HTMLScriptElement) { - self.asap_scripts_set.borrow_mut().push(Dom::from_ref(script)); + self.asap_scripts_set + .borrow_mut() + .push(Dom::from_ref(script)); } /// https://html.spec.whatwg.org/multipage/#the-end step 5. @@ -1932,7 +2036,10 @@ impl Document { pub fn asap_script_loaded(&self, element: &HTMLScriptElement, result: ScriptResult) { { let mut scripts = self.asap_scripts_set.borrow_mut(); - let idx = scripts.iter().position(|entry| &**entry == element).unwrap(); + let idx = scripts + .iter() + .position(|entry| &**entry == element) + .unwrap(); scripts.swap_remove(idx); } element.execute(result); @@ -1945,11 +2052,12 @@ impl Document { /// https://html.spec.whatwg.org/multipage/#the-end step 5. /// https://html.spec.whatwg.org/multipage/#prepare-a-script step 22.c. - pub fn asap_in_order_script_loaded(&self, - element: &HTMLScriptElement, - result: ScriptResult) { + pub fn asap_in_order_script_loaded(&self, element: &HTMLScriptElement, result: ScriptResult) { self.asap_in_order_scripts_list.loaded(element, result); - while let Some((element, result)) = self.asap_in_order_scripts_list.take_next_ready_to_be_executed() { + while let Some((element, result)) = self + .asap_in_order_scripts_list + .take_next_ready_to_be_executed() + { element.execute(result); } } @@ -1976,7 +2084,8 @@ impl Document { if self.script_blocking_stylesheets_count.get() > 0 { return; } - if let Some((element, result)) = self.deferred_scripts.take_next_ready_to_be_executed() { + if let Some((element, result)) = self.deferred_scripts.take_next_ready_to_be_executed() + { element.execute(result); } else { break; @@ -1994,21 +2103,31 @@ impl Document { return; } self.domcontentloaded_dispatched.set(true); - assert_ne!(self.ReadyState(), DocumentReadyState::Complete, - "Complete before DOMContentLoaded?"); + assert_ne!( + self.ReadyState(), + DocumentReadyState::Complete, + "Complete before DOMContentLoaded?" + ); update_with_current_time_ms(&self.dom_content_loaded_event_start); // Step 4.1. let window = self.window(); - window.dom_manipulation_task_source().queue_event(self.upcast(), atom!("DOMContentLoaded"), - EventBubbles::Bubbles, EventCancelable::NotCancelable, window); + window.dom_manipulation_task_source().queue_event( + self.upcast(), + atom!("DOMContentLoaded"), + EventBubbles::Bubbles, + EventCancelable::NotCancelable, + window, + ); window.reflow(ReflowGoal::Full, ReflowReason::DOMContentLoaded); update_with_current_time_ms(&self.dom_content_loaded_event_end); // html parsing has finished - set dom content loaded - self.interactive_time.borrow().maybe_set_tti(self, InteractiveFlag::DOMContentLoaded); + self.interactive_time + .borrow() + .maybe_set_tti(self, InteractiveFlag::DOMContentLoaded); // Step 4.2. // TODO: client message queue. @@ -2046,7 +2165,8 @@ impl Document { // Note: the spec says to discard any tasks queued for fetch. // This cancels all tasks on the networking task source, which might be too broad. // See https://github.com/whatwg/html/issues/3837 - self.window.cancel_all_tasks_from_source(TaskSourceName::Networking); + self.window + .cancel_all_tasks_from_source(TaskSourceName::Networking); // Step 3. if let Some(parser) = self.get_current_parser() { @@ -2073,21 +2193,24 @@ impl Document { // It is safe to run script if the parser is not actively parsing, // or if it is impossible to interact with the token stream. parser.parser_is_not_active() || - self.throw_on_dynamic_markup_insertion_counter.get() > 0 - } + self.throw_on_dynamic_markup_insertion_counter.get() > 0 + }, None => true, } } /// Iterate over all iframes in the document. - pub fn iter_iframes(&self) -> impl Iterator<Item=DomRoot<HTMLIFrameElement>> { + pub fn iter_iframes(&self) -> impl Iterator<Item = DomRoot<HTMLIFrameElement>> { self.upcast::<Node>() .traverse_preorder() .filter_map(DomRoot::downcast::<HTMLIFrameElement>) } /// Find an iframe element in the document. - pub fn find_iframe(&self, browsing_context_id: BrowsingContextId) -> Option<DomRoot<HTMLIFrameElement>> { + pub fn find_iframe( + &self, + browsing_context_id: BrowsingContextId, + ) -> Option<DomRoot<HTMLIFrameElement>> { self.iter_iframes() .find(|node| node.browsing_context_id() == Some(browsing_context_id)) } @@ -2101,7 +2224,9 @@ impl Document { } pub fn set_navigation_start(&self, navigation_start: u64) { - self.interactive_time.borrow_mut().set_navigation_start(navigation_start); + self.interactive_time + .borrow_mut() + .set_navigation_start(navigation_start); } pub fn get_interactive_metrics(&self) -> Ref<InteractiveMetrics> { @@ -2146,26 +2271,37 @@ impl Document { /// if it's been 10s since this doc encountered a task over 50ms, then we consider the /// main thread available and try to set tti pub fn record_tti_if_necessary(&self) { - if self.has_recorded_tti_metric() { return; } + if self.has_recorded_tti_metric() { + return; + } if self.tti_window.borrow().needs_check() { - self.get_interactive_metrics().maybe_set_tti(self, - InteractiveFlag::TimeToInteractive(self.tti_window.borrow().get_start())); + self.get_interactive_metrics().maybe_set_tti( + self, + InteractiveFlag::TimeToInteractive(self.tti_window.borrow().get_start()), + ); } } // https://html.spec.whatwg.org/multipage/#fire-a-focus-event - fn fire_focus_event(&self, focus_event_type: FocusEventType, node: &Node, related_target: Option<&EventTarget>) { + fn fire_focus_event( + &self, + focus_event_type: FocusEventType, + node: &Node, + related_target: Option<&EventTarget>, + ) { let (event_name, does_bubble) = match focus_event_type { FocusEventType::Focus => (DOMString::from("focus"), EventBubbles::DoesNotBubble), FocusEventType::Blur => (DOMString::from("blur"), EventBubbles::DoesNotBubble), }; - let event = FocusEvent::new(&self.window, - event_name, - does_bubble, - EventCancelable::NotCancelable, - Some(&self.window), - 0i32, - related_target); + let event = FocusEvent::new( + &self.window, + event_name, + does_bubble, + EventCancelable::NotCancelable, + Some(&self.window), + 0i32, + related_target, + ); let event = event.upcast::<Event>(); event.set_trusted(true); let target = node.upcast(); @@ -2177,24 +2313,33 @@ impl Document { !self.has_browsing_context || !url_has_network_scheme(&self.url()) } - pub fn nodes_from_point(&self, - client_point: &Point2D<f32>, - reflow_goal: NodesFromPointQueryType) - -> Vec<UntrustedNodeAddress> { - if !self.window.layout_reflow(QueryMsg::NodesFromPointQuery(*client_point, reflow_goal)) { - return vec!(); + pub fn nodes_from_point( + &self, + client_point: &Point2D<f32>, + reflow_goal: NodesFromPointQueryType, + ) -> Vec<UntrustedNodeAddress> { + if !self + .window + .layout_reflow(QueryMsg::NodesFromPointQuery(*client_point, reflow_goal)) + { + return vec![]; }; self.window.layout().nodes_from_point_response() } /// <https://html.spec.whatwg.org/multipage/#look-up-a-custom-element-definition> - pub fn lookup_custom_element_definition(&self, - namespace: &Namespace, - local_name: &LocalName, - is: Option<&LocalName>) - -> Option<Rc<CustomElementDefinition>> { - if !PREFS.get("dom.customelements.enabled").as_boolean().unwrap_or(false) { + pub fn lookup_custom_element_definition( + &self, + namespace: &Namespace, + local_name: &LocalName, + is: Option<&LocalName>, + ) -> Option<Rc<CustomElementDefinition>> { + if !PREFS + .get("dom.customelements.enabled") + .as_boolean() + .unwrap_or(false) + { return None; } @@ -2216,12 +2361,14 @@ impl Document { pub fn increment_throw_on_dynamic_markup_insertion_counter(&self) { let counter = self.throw_on_dynamic_markup_insertion_counter.get(); - self.throw_on_dynamic_markup_insertion_counter.set(counter + 1); + self.throw_on_dynamic_markup_insertion_counter + .set(counter + 1); } pub fn decrement_throw_on_dynamic_markup_insertion_counter(&self) { let counter = self.throw_on_dynamic_markup_insertion_counter.get(); - self.throw_on_dynamic_markup_insertion_counter.set(counter - 1); + self.throw_on_dynamic_markup_insertion_counter + .set(counter - 1); } pub fn react_to_environment_changes(&self) { @@ -2235,7 +2382,11 @@ impl Document { } pub fn unregister_responsive_image(&self, img: &HTMLImageElement) { - let index = self.responsive_images.borrow().iter().position(|x| **x == *img); + let index = self + .responsive_images + .borrow() + .iter() + .position(|x| **x == *img); if let Some(i) = index { self.responsive_images.borrow_mut().remove(i); } @@ -2268,10 +2419,13 @@ impl LayoutDocumentHelpers for LayoutDom<Document> { #[inline] #[allow(unrooted_must_root)] unsafe fn drain_pending_restyles(&self) -> Vec<(LayoutDom<Element>, PendingRestyle)> { - let mut elements = (*self.unsafe_get()).pending_restyles.borrow_mut_for_layout(); + let mut elements = (*self.unsafe_get()) + .pending_restyles + .borrow_mut_for_layout(); // Elements were in a document when they were adding to this list, but that // may no longer be true when the next layout occurs. - let result = elements.drain() + let result = elements + .drain() .map(|(k, v)| (k.to_layout(), v)) .filter(|&(ref k, _)| k.upcast::<Node>().get_flag(NodeFlags::IS_IN_DOC)) .collect(); @@ -2302,7 +2456,10 @@ impl LayoutDocumentHelpers for LayoutDom<Document> { // https://html.spec.whatwg.org/multipage/#is-a-registrable-domain-suffix-of-or-is-equal-to // The spec says to return a bool, we actually return an Option<Host> containing // the parsed host in the successful case, to avoid having to re-parse the host. -fn get_registrable_domain_suffix_of_or_is_equal_to(host_suffix_string: &str, original_host: Host) -> Option<Host> { +fn get_registrable_domain_suffix_of_or_is_equal_to( + host_suffix_string: &str, + original_host: Host, +) -> Option<Host> { // Step 1 if host_suffix_string.is_empty() { return None; @@ -2362,20 +2519,21 @@ pub enum HasBrowsingContext { } impl Document { - pub fn new_inherited(window: &Window, - has_browsing_context: HasBrowsingContext, - url: Option<ServoUrl>, - origin: MutableOrigin, - is_html_document: IsHTMLDocument, - content_type: Option<Mime>, - last_modified: Option<String>, - activity: DocumentActivity, - source: DocumentSource, - doc_loader: DocumentLoader, - referrer: Option<String>, - referrer_policy: Option<ReferrerPolicy>, - canceller: FetchCanceller) - -> Document { + pub fn new_inherited( + window: &Window, + has_browsing_context: HasBrowsingContext, + url: Option<ServoUrl>, + origin: MutableOrigin, + is_html_document: IsHTMLDocument, + content_type: Option<Mime>, + last_modified: Option<String>, + activity: DocumentActivity, + source: DocumentSource, + doc_loader: DocumentLoader, + referrer: Option<String>, + referrer_policy: Option<ReferrerPolicy>, + canceller: FetchCanceller, + ) -> Document { let url = url.unwrap_or_else(|| ServoUrl::parse("about:blank").unwrap()); let (ready_state, domcontentloaded_dispatched) = if source == DocumentSource::FromParser { @@ -2384,7 +2542,8 @@ impl Document { (DocumentReadyState::Complete, true) }; - let interactive_time = InteractiveMetrics::new(window.time_profiler_chan().clone(), url.clone()); + let interactive_time = + InteractiveMetrics::new(window.time_profiler_chan().clone(), url.clone()); Document { node: Node::new_document_node(), @@ -2397,7 +2556,9 @@ impl Document { // https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument IsHTMLDocument::HTMLDocument => Mime(TopLevel::Text, SubLevel::Html, vec![]), // https://dom.spec.whatwg.org/#concept-document-content-type - IsHTMLDocument::NonHTMLDocument => Mime(TopLevel::Application, SubLevel::Xml, vec![]), + IsHTMLDocument::NonHTMLDocument => { + Mime(TopLevel::Application, SubLevel::Xml, vec![]) + }, }), }, last_modified: last_modified, @@ -2485,7 +2646,7 @@ impl Document { page_showing: Cell::new(false), salvageable: Cell::new(true), fired_unload: Cell::new(false), - responsive_images: Default::default() + responsive_images: Default::default(), } } @@ -2493,35 +2654,38 @@ impl Document { pub fn Constructor(window: &Window) -> Fallible<DomRoot<Document>> { let doc = window.Document(); let docloader = DocumentLoader::new(&*doc.loader()); - Ok(Document::new(window, - HasBrowsingContext::No, - None, - doc.origin().clone(), - IsHTMLDocument::NonHTMLDocument, - None, - None, - DocumentActivity::Inactive, - DocumentSource::NotFromParser, - docloader, - None, - None, - Default::default())) - } - - pub fn new(window: &Window, - has_browsing_context: HasBrowsingContext, - url: Option<ServoUrl>, - origin: MutableOrigin, - doctype: IsHTMLDocument, - content_type: Option<Mime>, - last_modified: Option<String>, - activity: DocumentActivity, - source: DocumentSource, - doc_loader: DocumentLoader, - referrer: Option<String>, - referrer_policy: Option<ReferrerPolicy>, - canceller: FetchCanceller) - -> DomRoot<Document> { + Ok(Document::new( + window, + HasBrowsingContext::No, + None, + doc.origin().clone(), + IsHTMLDocument::NonHTMLDocument, + None, + None, + DocumentActivity::Inactive, + DocumentSource::NotFromParser, + docloader, + None, + None, + Default::default(), + )) + } + + pub fn new( + window: &Window, + has_browsing_context: HasBrowsingContext, + url: Option<ServoUrl>, + origin: MutableOrigin, + doctype: IsHTMLDocument, + content_type: Option<Mime>, + last_modified: Option<String>, + activity: DocumentActivity, + source: DocumentSource, + doc_loader: DocumentLoader, + referrer: Option<String>, + referrer_policy: Option<ReferrerPolicy>, + canceller: FetchCanceller, + ) -> DomRoot<Document> { let document = reflect_dom_object( Box::new(Document::new_inherited( window, @@ -2536,10 +2700,10 @@ impl Document { doc_loader, referrer, referrer_policy, - canceller + canceller, )), window, - DocumentBinding::Wrap + DocumentBinding::Wrap, ); { let node = document.upcast::<Node>(); @@ -2551,9 +2715,10 @@ impl Document { fn create_node_list<F: Fn(&Node) -> bool>(&self, callback: F) -> DomRoot<NodeList> { let doc = self.GetDocumentElement(); let maybe_node = doc.r().map(Castable::upcast::<Node>); - let iter = maybe_node.iter() - .flat_map(|node| node.traverse_preorder()) - .filter(|node| callback(&node)); + let iter = maybe_node + .iter() + .flat_map(|node| node.traverse_preorder()) + .filter(|node| callback(&node)); NodeList::new_simple_list(&self.window, iter) } @@ -2591,7 +2756,11 @@ impl Document { let window_size = self.window().window_size()?; let viewport_size = window_size.initial_viewport; let device_pixel_ratio = window_size.device_pixel_ratio; - Some(Device::new(MediaType::screen(), viewport_size, device_pixel_ratio)) + Some(Device::new( + MediaType::screen(), + viewport_size, + device_pixel_ratio, + )) } /// Remove a stylesheet owned by `owner` from the list of document sheets. @@ -2622,25 +2791,27 @@ impl Document { // FIXME(emilio): It'd be nice to unify more code between the elements // that own stylesheets, but StylesheetOwner is more about loading // them... - debug_assert!(owner.as_stylesheet_owner().is_some() || - owner.is::<HTMLMetaElement>(), "Wat"); + debug_assert!( + owner.as_stylesheet_owner().is_some() || owner.is::<HTMLMetaElement>(), + "Wat" + ); let mut stylesheets = self.stylesheets.borrow_mut(); - let insertion_point = - stylesheets - .iter() - .map(|(sheet, _origin)| sheet) - .find(|sheet_in_doc| { - owner.upcast::<Node>().is_before(sheet_in_doc.owner.upcast()) - }).cloned(); + let insertion_point = stylesheets + .iter() + .map(|(sheet, _origin)| sheet) + .find(|sheet_in_doc| { + owner + .upcast::<Node>() + .is_before(sheet_in_doc.owner.upcast()) + }).cloned(); self.window() .layout_chan() .send(Msg::AddStylesheet( sheet.clone(), - insertion_point.as_ref().map(|s| s.sheet.clone()) - )) - .unwrap(); + insertion_point.as_ref().map(|s| s.sheet.clone()), + )).unwrap(); let sheet = StyleSheetInDocument { sheet, @@ -2653,10 +2824,10 @@ impl Document { match insertion_point { Some(ip) => { stylesheets.insert_stylesheet_before(None, sheet, ip, &guard); - } + }, None => { stylesheets.append_stylesheet(None, sheet, &guard); - } + }, } } @@ -2672,45 +2843,56 @@ impl Document { pub fn stylesheet_at(&self, index: usize) -> Option<DomRoot<CSSStyleSheet>> { let stylesheets = self.stylesheets.borrow(); - stylesheets.get(Origin::Author, index).and_then(|s| { - s.owner.upcast::<Node>().get_cssom_stylesheet() - }) + stylesheets + .get(Origin::Author, index) + .and_then(|s| s.owner.upcast::<Node>().get_cssom_stylesheet()) } /// <https://html.spec.whatwg.org/multipage/#appropriate-template-contents-owner-document> pub fn appropriate_template_contents_owner_document(&self) -> DomRoot<Document> { - self.appropriate_template_contents_owner_document.or_init(|| { - let doctype = if self.is_html_document { - IsHTMLDocument::HTMLDocument - } else { - IsHTMLDocument::NonHTMLDocument - }; - let new_doc = Document::new(self.window(), - HasBrowsingContext::No, - None, - // https://github.com/whatwg/html/issues/2109 - MutableOrigin::new(ImmutableOrigin::new_opaque()), - doctype, - None, - None, - DocumentActivity::Inactive, - DocumentSource::NotFromParser, - DocumentLoader::new(&self.loader()), - None, - None, - Default::default()); - new_doc.appropriate_template_contents_owner_document.set(Some(&new_doc)); - new_doc - }) + self.appropriate_template_contents_owner_document + .or_init(|| { + let doctype = if self.is_html_document { + IsHTMLDocument::HTMLDocument + } else { + IsHTMLDocument::NonHTMLDocument + }; + let new_doc = Document::new( + self.window(), + HasBrowsingContext::No, + None, + // https://github.com/whatwg/html/issues/2109 + MutableOrigin::new(ImmutableOrigin::new_opaque()), + doctype, + None, + None, + DocumentActivity::Inactive, + DocumentSource::NotFromParser, + DocumentLoader::new(&self.loader()), + None, + None, + Default::default(), + ); + new_doc + .appropriate_template_contents_owner_document + .set(Some(&new_doc)); + new_doc + }) } pub fn get_element_by_id(&self, id: &Atom) -> Option<DomRoot<Element>> { - self.id_map.borrow().get(&id).map(|ref elements| DomRoot::from_ref(&*(*elements)[0])) + self.id_map + .borrow() + .get(&id) + .map(|ref elements| DomRoot::from_ref(&*(*elements)[0])) } pub fn ensure_pending_restyle(&self, el: &Element) -> RefMut<PendingRestyle> { let map = self.pending_restyles.borrow_mut(); - RefMut::map(map, |m| m.entry(Dom::from_ref(el)).or_insert_with(PendingRestyle::new)) + RefMut::map(map, |m| { + m.entry(Dom::from_ref(el)) + .or_insert_with(PendingRestyle::new) + }) } pub fn element_state_will_change(&self, el: &Element) { @@ -2751,10 +2933,11 @@ impl Document { snapshot.other_attributes_changed = true; } if snapshot.attrs.is_none() { - let attrs = el.attrs() - .iter() - .map(|attr| (attr.identifier().clone(), attr.value().clone())) - .collect(); + let attrs = el + .attrs() + .iter() + .map(|attr| (attr.identifier().clone(), attr.value().clone())) + .collect(); snapshot.attrs = Some(attrs); } } @@ -2779,17 +2962,18 @@ impl Document { element.set_target_state(true); } - self.window.reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); + self.window + .reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); } pub fn incr_ignore_destructive_writes_counter(&self) { - self.ignore_destructive_writes_counter.set( - self.ignore_destructive_writes_counter.get() + 1); + self.ignore_destructive_writes_counter + .set(self.ignore_destructive_writes_counter.get() + 1); } pub fn decr_ignore_destructive_writes_counter(&self) { - self.ignore_destructive_writes_counter.set( - self.ignore_destructive_writes_counter.get() - 1); + self.ignore_destructive_writes_counter + .set(self.ignore_destructive_writes_counter.get() - 1); } pub fn is_prompting_or_unloading(&self) -> bool { @@ -2797,13 +2981,13 @@ impl Document { } fn incr_ignore_opens_during_unload_counter(&self) { - self.ignore_opens_during_unload_counter.set( - self.ignore_opens_during_unload_counter.get() + 1); + self.ignore_opens_during_unload_counter + .set(self.ignore_opens_during_unload_counter.get() + 1); } fn decr_ignore_opens_during_unload_counter(&self) { - self.ignore_opens_during_unload_counter.set( - self.ignore_opens_during_unload_counter.get() - 1); + self.ignore_opens_during_unload_counter + .set(self.ignore_opens_during_unload_counter.get() - 1); } /// Whether we've seen so many spurious animation frames (i.e. animation frames that didn't @@ -2826,12 +3010,12 @@ impl Document { if pending.local_name().as_ref() != "math" { error = true; } - } + }, ns!(svg) => { if pending.local_name().as_ref() != "svg" { error = true; } - } + }, ns!(html) => (), _ => error = true, } @@ -2880,7 +3064,7 @@ impl Document { // Step 2 if self.fullscreen_element.get().is_none() { promise.reject_error(Error::Type(String::from("fullscreen is null"))); - return promise + return promise; } // TODO Step 3-6 let element = self.fullscreen_element.get().unwrap(); @@ -2927,9 +3111,11 @@ impl Document { true } else { // Step 3 - window.GetFrameElement().map_or(false, |el| el.has_attribute(&local_name!("allowfullscreen"))) + window.GetFrameElement().map_or(false, |el| { + el.has_attribute(&local_name!("allowfullscreen")) + }) } - } + }, } } @@ -2937,15 +3123,16 @@ impl Document { let map = self.form_id_listener_map.borrow(); if let Some(listeners) = map.get(id) { for listener in listeners { - listener.r().as_maybe_form_control() - .expect("Element must be a form control") - .reset_form_owner(); + listener + .r() + .as_maybe_form_control() + .expect("Element must be a form control") + .reset_form_owner(); } } } } - impl Element { fn click_event_filter_by_disabled_state(&self) -> bool { let node = self.upcast::<Node>(); @@ -2975,7 +3162,8 @@ impl ProfilerMetadataFactory for Document { impl DocumentMethods for Document { // https://drafts.csswg.org/cssom/#dom-document-stylesheets fn StyleSheets(&self) -> DomRoot<StyleSheetList> { - self.stylesheet_list.or_init(|| StyleSheetList::new(&self.window, Dom::from_ref(&self))) + self.stylesheet_list + .or_init(|| StyleSheetList::new(&self.window, Dom::from_ref(&self))) } // https://dom.spec.whatwg.org/#dom-document-implementation @@ -2993,8 +3181,9 @@ impl DocumentMethods for Document { // TODO: Step 2. match self.get_focused_element() { - Some(element) => Some(element), // Step 3. and 4. - None => match self.GetBody() { // Step 5. + Some(element) => Some(element), // Step 3. and 4. + None => match self.GetBody() { + // Step 5. Some(body) => Some(DomRoot::upcast(body)), None => self.GetDocumentElement(), }, @@ -3046,7 +3235,8 @@ impl DocumentMethods for Document { }; // Step 5 - let host = match get_registrable_domain_suffix_of_or_is_equal_to(&*value, effective_domain) { + let host = match get_registrable_domain_suffix_of_or_is_equal_to(&*value, effective_domain) + { None => return Err(Error::Security), Some(host) => host, }; @@ -3061,7 +3251,7 @@ impl DocumentMethods for Document { fn Referrer(&self) -> DOMString { match self.referrer { Some(ref referrer) => DOMString::from(referrer.to_string()), - None => DOMString::new() + None => DOMString::new(), } } @@ -3100,7 +3290,10 @@ impl DocumentMethods for Document { // https://dom.spec.whatwg.org/#dom-document-doctype fn GetDoctype(&self) -> Option<DomRoot<DocumentType>> { - self.upcast::<Node>().children().filter_map(DomRoot::downcast).next() + self.upcast::<Node>() + .children() + .filter_map(DomRoot::downcast) + .next() } // https://dom.spec.whatwg.org/#dom-document-documentelement @@ -3114,19 +3307,20 @@ impl DocumentMethods for Document { match self.tag_map.borrow_mut().entry(qualified_name.clone()) { Occupied(entry) => DomRoot::from_ref(entry.get()), Vacant(entry) => { - let result = HTMLCollection::by_qualified_name( - &self.window, self.upcast(), qualified_name); + let result = + HTMLCollection::by_qualified_name(&self.window, self.upcast(), qualified_name); entry.insert(Dom::from_ref(&*result)); result - } + }, } } // https://dom.spec.whatwg.org/#dom-document-getelementsbytagnamens - fn GetElementsByTagNameNS(&self, - maybe_ns: Option<DOMString>, - tag_name: DOMString) - -> DomRoot<HTMLCollection> { + fn GetElementsByTagNameNS( + &self, + maybe_ns: Option<DOMString>, + tag_name: DOMString, + ) -> DomRoot<HTMLCollection> { let ns = namespace_from_domstring(maybe_ns); let local = LocalName::from(tag_name); let qname = QualName::new(None, ns, local); @@ -3136,24 +3330,21 @@ impl DocumentMethods for Document { let result = HTMLCollection::by_qual_tag_name(&self.window, self.upcast(), qname); entry.insert(Dom::from_ref(&*result)); result - } + }, } } // https://dom.spec.whatwg.org/#dom-document-getelementsbyclassname fn GetElementsByClassName(&self, classes: DOMString) -> DomRoot<HTMLCollection> { - let class_atoms: Vec<Atom> = split_html_space_chars(&classes) - .map(Atom::from) - .collect(); + let class_atoms: Vec<Atom> = split_html_space_chars(&classes).map(Atom::from).collect(); match self.classes_map.borrow_mut().entry(class_atoms.clone()) { Occupied(entry) => DomRoot::from_ref(entry.get()), Vacant(entry) => { - let result = HTMLCollection::by_atomic_class_name(&self.window, - self.upcast(), - class_atoms); + let result = + HTMLCollection::by_atomic_class_name(&self.window, self.upcast(), class_atoms); entry.insert(Dom::from_ref(&*result)); result - } + }, } } @@ -3163,10 +3354,11 @@ impl DocumentMethods for Document { } // https://dom.spec.whatwg.org/#dom-document-createelement - fn CreateElement(&self, - mut local_name: DOMString, - options: &ElementCreationOptions) - -> Fallible<DomRoot<Element>> { + fn CreateElement( + &self, + mut local_name: DOMString, + options: &ElementCreationOptions, + ) -> Fallible<DomRoot<Element>> { if xml_name_type(&local_name) == InvalidXMLName { debug!("Not a valid element name"); return Err(Error::InvalidCharacter); @@ -3175,7 +3367,8 @@ impl DocumentMethods for Document { local_name.make_ascii_lowercase(); } - let is_xhtml = self.content_type.0 == TopLevel::Application && self.content_type.1.as_str() == "xhtml+xml"; + let is_xhtml = self.content_type.0 == TopLevel::Application && + self.content_type.1.as_str() == "xhtml+xml"; let ns = if self.is_html_document || is_xhtml { ns!(html) } else { @@ -3184,20 +3377,32 @@ impl DocumentMethods for Document { let name = QualName::new(None, ns, LocalName::from(local_name)); let is = options.is.as_ref().map(|is| LocalName::from(&**is)); - Ok(Element::create(name, is, self, ElementCreator::ScriptCreated, CustomElementCreationMode::Synchronous)) + Ok(Element::create( + name, + is, + self, + ElementCreator::ScriptCreated, + CustomElementCreationMode::Synchronous, + )) } // https://dom.spec.whatwg.org/#dom-document-createelementns - fn CreateElementNS(&self, - namespace: Option<DOMString>, - qualified_name: DOMString, - options: &ElementCreationOptions) - -> Fallible<DomRoot<Element>> { - let (namespace, prefix, local_name) = validate_and_extract(namespace, - &qualified_name)?; + fn CreateElementNS( + &self, + namespace: Option<DOMString>, + qualified_name: DOMString, + options: &ElementCreationOptions, + ) -> Fallible<DomRoot<Element>> { + let (namespace, prefix, local_name) = validate_and_extract(namespace, &qualified_name)?; let name = QualName::new(prefix, namespace, local_name); let is = options.is.as_ref().map(|is| LocalName::from(&**is)); - Ok(Element::create(name, is, self, ElementCreator::ScriptCreated, CustomElementCreationMode::Synchronous)) + Ok(Element::create( + name, + is, + self, + ElementCreator::ScriptCreated, + CustomElementCreationMode::Synchronous, + )) } // https://dom.spec.whatwg.org/#dom-document-createattribute @@ -3212,25 +3417,35 @@ impl DocumentMethods for Document { let name = LocalName::from(local_name); let value = AttrValue::String("".to_owned()); - Ok(Attr::new(&self.window, name.clone(), value, name, ns!(), None, None)) + Ok(Attr::new( + &self.window, + name.clone(), + value, + name, + ns!(), + None, + None, + )) } // https://dom.spec.whatwg.org/#dom-document-createattributens - fn CreateAttributeNS(&self, - namespace: Option<DOMString>, - qualified_name: DOMString) - -> Fallible<DomRoot<Attr>> { - let (namespace, prefix, local_name) = validate_and_extract(namespace, - &qualified_name)?; + fn CreateAttributeNS( + &self, + namespace: Option<DOMString>, + qualified_name: DOMString, + ) -> Fallible<DomRoot<Attr>> { + let (namespace, prefix, local_name) = validate_and_extract(namespace, &qualified_name)?; let value = AttrValue::String("".to_owned()); let qualified_name = LocalName::from(qualified_name); - Ok(Attr::new(&self.window, - local_name, - value, - qualified_name, - namespace, - prefix, - None)) + Ok(Attr::new( + &self.window, + local_name, + value, + qualified_name, + namespace, + prefix, + None, + )) } // https://dom.spec.whatwg.org/#dom-document-createdocumentfragment @@ -3249,10 +3464,11 @@ impl DocumentMethods for Document { } // https://dom.spec.whatwg.org/#dom-document-createprocessinginstruction - fn CreateProcessingInstruction(&self, - target: DOMString, - data: DOMString) - -> Fallible<DomRoot<ProcessingInstruction>> { + fn CreateProcessingInstruction( + &self, + target: DOMString, + data: DOMString, + ) -> Fallible<DomRoot<ProcessingInstruction>> { // Step 1. if xml_name_type(&target) == InvalidXMLName { return Err(Error::InvalidCharacter); @@ -3302,49 +3518,58 @@ impl DocumentMethods for Document { fn CreateEvent(&self, mut interface: DOMString) -> Fallible<DomRoot<Event>> { interface.make_ascii_lowercase(); match &*interface { - "beforeunloadevent" => - Ok(DomRoot::upcast(BeforeUnloadEvent::new_uninitialized(&self.window))), - "closeevent" => - Ok(DomRoot::upcast(CloseEvent::new_uninitialized(self.window.upcast()))), - "customevent" => - Ok(DomRoot::upcast(CustomEvent::new_uninitialized(self.window.upcast()))), - "errorevent" => - Ok(DomRoot::upcast(ErrorEvent::new_uninitialized(self.window.upcast()))), - "events" | "event" | "htmlevents" | "svgevents" => - Ok(Event::new_uninitialized(&self.window.upcast())), - "focusevent" => - Ok(DomRoot::upcast(FocusEvent::new_uninitialized(&self.window))), - "hashchangeevent" => - Ok(DomRoot::upcast(HashChangeEvent::new_uninitialized(&self.window))), - "keyboardevent" => - Ok(DomRoot::upcast(KeyboardEvent::new_uninitialized(&self.window))), - "messageevent" => - Ok(DomRoot::upcast(MessageEvent::new_uninitialized(self.window.upcast()))), - "mouseevent" | "mouseevents" => - Ok(DomRoot::upcast(MouseEvent::new_uninitialized(&self.window))), - "pagetransitionevent" => - Ok(DomRoot::upcast(PageTransitionEvent::new_uninitialized(&self.window))), - "popstateevent" => - Ok(DomRoot::upcast(PopStateEvent::new_uninitialized(&self.window))), - "progressevent" => - Ok(DomRoot::upcast(ProgressEvent::new_uninitialized(self.window.upcast()))), - "storageevent" => { - Ok(DomRoot::upcast(StorageEvent::new_uninitialized(&self.window, "".into()))) + "beforeunloadevent" => Ok(DomRoot::upcast(BeforeUnloadEvent::new_uninitialized( + &self.window, + ))), + "closeevent" => Ok(DomRoot::upcast(CloseEvent::new_uninitialized( + self.window.upcast(), + ))), + "customevent" => Ok(DomRoot::upcast(CustomEvent::new_uninitialized( + self.window.upcast(), + ))), + "errorevent" => Ok(DomRoot::upcast(ErrorEvent::new_uninitialized( + self.window.upcast(), + ))), + "events" | "event" | "htmlevents" | "svgevents" => { + Ok(Event::new_uninitialized(&self.window.upcast())) }, - "touchevent" => - Ok(DomRoot::upcast( - TouchEvent::new_uninitialized(&self.window, - &TouchList::new(&self.window, &[]), - &TouchList::new(&self.window, &[]), - &TouchList::new(&self.window, &[]), - ) - )), - "uievent" | "uievents" => - Ok(DomRoot::upcast(UIEvent::new_uninitialized(&self.window))), - "webglcontextevent" => - Ok(DomRoot::upcast(WebGLContextEvent::new_uninitialized(&self.window))), - _ => - Err(Error::NotSupported), + "focusevent" => Ok(DomRoot::upcast(FocusEvent::new_uninitialized(&self.window))), + "hashchangeevent" => Ok(DomRoot::upcast(HashChangeEvent::new_uninitialized( + &self.window, + ))), + "keyboardevent" => Ok(DomRoot::upcast(KeyboardEvent::new_uninitialized( + &self.window, + ))), + "messageevent" => Ok(DomRoot::upcast(MessageEvent::new_uninitialized( + self.window.upcast(), + ))), + "mouseevent" | "mouseevents" => { + Ok(DomRoot::upcast(MouseEvent::new_uninitialized(&self.window))) + }, + "pagetransitionevent" => Ok(DomRoot::upcast(PageTransitionEvent::new_uninitialized( + &self.window, + ))), + "popstateevent" => Ok(DomRoot::upcast(PopStateEvent::new_uninitialized( + &self.window, + ))), + "progressevent" => Ok(DomRoot::upcast(ProgressEvent::new_uninitialized( + self.window.upcast(), + ))), + "storageevent" => Ok(DomRoot::upcast(StorageEvent::new_uninitialized( + &self.window, + "".into(), + ))), + "touchevent" => Ok(DomRoot::upcast(TouchEvent::new_uninitialized( + &self.window, + &TouchList::new(&self.window, &[]), + &TouchList::new(&self.window, &[]), + &TouchList::new(&self.window, &[]), + ))), + "uievent" | "uievents" => Ok(DomRoot::upcast(UIEvent::new_uninitialized(&self.window))), + "webglcontextevent" => Ok(DomRoot::upcast(WebGLContextEvent::new_uninitialized( + &self.window, + ))), + _ => Err(Error::NotSupported), } } @@ -3352,7 +3577,12 @@ impl DocumentMethods for Document { fn LastModified(&self) -> DOMString { match self.last_modified { Some(ref t) => DOMString::from(t.clone()), - None => DOMString::from(time::now().strftime("%m/%d/%Y %H:%M:%S").unwrap().to_string()), + None => DOMString::from( + time::now() + .strftime("%m/%d/%Y %H:%M:%S") + .unwrap() + .to_string(), + ), } } @@ -3362,35 +3592,31 @@ impl DocumentMethods for Document { } // https://dom.spec.whatwg.org/#dom-document-createnodeiteratorroot-whattoshow-filter - fn CreateNodeIterator(&self, - root: &Node, - what_to_show: u32, - filter: Option<Rc<NodeFilter>>) - -> DomRoot<NodeIterator> { + fn CreateNodeIterator( + &self, + root: &Node, + what_to_show: u32, + filter: Option<Rc<NodeFilter>>, + ) -> DomRoot<NodeIterator> { NodeIterator::new(self, root, what_to_show, filter) } // https://w3c.github.io/touch-events/#idl-def-Document - fn CreateTouch(&self, - window: &Window, - target: &EventTarget, - identifier: i32, - page_x: Finite<f64>, - page_y: Finite<f64>, - screen_x: Finite<f64>, - screen_y: Finite<f64>) - -> DomRoot<Touch> { + fn CreateTouch( + &self, + window: &Window, + target: &EventTarget, + identifier: i32, + page_x: Finite<f64>, + page_y: Finite<f64>, + screen_x: Finite<f64>, + screen_y: Finite<f64>, + ) -> DomRoot<Touch> { let client_x = Finite::wrap(*page_x - window.PageXOffset() as f64); let client_y = Finite::wrap(*page_y - window.PageYOffset() as f64); - Touch::new(window, - identifier, - target, - screen_x, - screen_y, - client_x, - client_y, - page_x, - page_y) + Touch::new( + window, identifier, target, screen_x, screen_y, client_x, client_y, page_x, page_y, + ) } // https://w3c.github.io/touch-events/#idl-def-document-createtouchlist(touch...) @@ -3399,11 +3625,12 @@ impl DocumentMethods for Document { } // https://dom.spec.whatwg.org/#dom-document-createtreewalker - fn CreateTreeWalker(&self, - root: &Node, - what_to_show: u32, - filter: Option<Rc<NodeFilter>>) - -> DomRoot<TreeWalker> { + fn CreateTreeWalker( + &self, + root: &Node, + what_to_show: u32, + filter: Option<Rc<NodeFilter>>, + ) -> DomRoot<TreeWalker> { TreeWalker::new(self, root, what_to_show, filter) } @@ -3416,8 +3643,7 @@ impl DocumentMethods for Document { .child_elements() .find(|node| { node.namespace() == &ns!(svg) && node.local_name() == &local_name!("title") - }) - .map(DomRoot::upcast::<Node>) + }).map(DomRoot::upcast::<Node>) } else { // Step 2. root.upcast::<Node>() @@ -3451,39 +3677,41 @@ impl DocumentMethods for Document { Some(elem) => DomRoot::upcast::<Node>(elem), None => { let name = QualName::new(None, ns!(svg), local_name!("title")); - let elem = Element::create(name, - None, - self, - ElementCreator::ScriptCreated, - CustomElementCreationMode::Synchronous); + let elem = Element::create( + name, + None, + self, + ElementCreator::ScriptCreated, + CustomElementCreationMode::Synchronous, + ); let parent = root.upcast::<Node>(); let child = elem.upcast::<Node>(); - parent.InsertBefore(child, parent.GetFirstChild().r()) - .unwrap() - } + parent + .InsertBefore(child, parent.GetFirstChild().r()) + .unwrap() + }, } } else if root.namespace() == &ns!(html) { - let elem = root.upcast::<Node>() - .traverse_preorder() - .find(|node| node.is::<HTMLTitleElement>()); + let elem = root + .upcast::<Node>() + .traverse_preorder() + .find(|node| node.is::<HTMLTitleElement>()); match elem { Some(elem) => elem, - None => { - match self.GetHead() { - Some(head) => { - let name = QualName::new(None, ns!(html), local_name!("title")); - let elem = Element::create(name, - None, - self, - ElementCreator::ScriptCreated, - CustomElementCreationMode::Synchronous); - head.upcast::<Node>() - .AppendChild(elem.upcast()) - .unwrap() - }, - None => return, - } - } + None => match self.GetHead() { + Some(head) => { + let name = QualName::new(None, ns!(html), local_name!("title")); + let elem = Element::create( + name, + None, + self, + ElementCreator::ScriptCreated, + CustomElementCreationMode::Synchronous, + ); + head.upcast::<Node>().AppendChild(elem.upcast()).unwrap() + }, + None => return, + }, } } else { return; @@ -3494,8 +3722,12 @@ impl DocumentMethods for Document { // https://html.spec.whatwg.org/multipage/#dom-document-head fn GetHead(&self) -> Option<DomRoot<HTMLHeadElement>> { - self.get_html_element() - .and_then(|root| root.upcast::<Node>().children().filter_map(DomRoot::downcast).next()) + self.get_html_element().and_then(|root| { + root.upcast::<Node>() + .children() + .filter_map(DomRoot::downcast) + .next() + }) } // https://html.spec.whatwg.org/multipage/#dom-document-currentscript @@ -3507,13 +3739,16 @@ impl DocumentMethods for Document { fn GetBody(&self) -> Option<DomRoot<HTMLElement>> { self.get_html_element().and_then(|root| { let node = root.upcast::<Node>(); - node.children().find(|child| { - match child.type_id() { - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBodyElement)) | - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFrameSetElement)) => true, - _ => false - } - }).map(|node| DomRoot::downcast(node).unwrap()) + node.children() + .find(|child| match child.type_id() { + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLBodyElement, + )) | + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLFrameSetElement, + )) => true, + _ => false, + }).map(|node| DomRoot::downcast(node).unwrap()) }) } @@ -3528,7 +3763,9 @@ impl DocumentMethods for Document { let node = new_body.upcast::<Node>(); match node.type_id() { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBodyElement)) | - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFrameSetElement)) => {} + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLFrameSetElement, + )) => {}, _ => return Err(Error::HierarchyRequest), } @@ -3542,7 +3779,8 @@ impl DocumentMethods for Document { // Step 3. (Some(ref root), &Some(ref child)) => { let root = root.upcast::<Node>(); - root.ReplaceChild(new_body.upcast(), child.upcast()).unwrap(); + root.ReplaceChild(new_body.upcast(), child.upcast()) + .unwrap(); }, // Step 4. @@ -3552,7 +3790,7 @@ impl DocumentMethods for Document { (Some(ref root), &None) => { let root = root.upcast::<Node>(); root.AppendChild(new_body.upcast()).unwrap(); - } + }, } Ok(()) } @@ -3567,8 +3805,9 @@ impl DocumentMethods for Document { if element.namespace() != &ns!(html) { return false; } - element.get_attribute(&ns!(), &local_name!("name")) - .map_or(false, |attr| &**attr.value() == &*name) + element + .get_attribute(&ns!(), &local_name!("name")) + .map_or(false, |attr| &**attr.value() == &*name) }) } @@ -3627,9 +3866,8 @@ impl DocumentMethods for Document { // https://html.spec.whatwg.org/multipage/#dom-document-applets fn Applets(&self) -> DomRoot<HTMLCollection> { - self.applets.or_init(|| { - HTMLCollection::always_empty(&self.window, self.upcast()) - }) + self.applets + .or_init(|| HTMLCollection::always_empty(&self.window, self.upcast())) } // https://html.spec.whatwg.org/multipage/#dom-document-location @@ -3653,7 +3891,10 @@ impl DocumentMethods for Document { // https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild fn GetLastElementChild(&self) -> Option<DomRoot<Element>> { - self.upcast::<Node>().rev_children().filter_map(DomRoot::downcast).next() + self.upcast::<Node>() + .rev_children() + .filter_map(DomRoot::downcast) + .next() } // https://dom.spec.whatwg.org/#dom-parentnode-childelementcount @@ -3709,7 +3950,8 @@ impl DocumentMethods for Document { let url = self.url(); let (tx, rx) = profile_ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); - let _ = self.window + let _ = self + .window .upcast::<GlobalScope>() .resource_threads() .send(GetCookiesForUrl(url, tx, NonHTTP)); @@ -3728,13 +3970,16 @@ impl DocumentMethods for Document { } if let Ok(cookie_header) = SetCookie::parse_header(&vec![cookie.to_string().into_bytes()]) { - let cookies = cookie_header.0.into_iter().filter_map(|cookie| { - cookie_rs::Cookie::parse(cookie).ok().map(Serde) - }).collect(); - let _ = self.window - .upcast::<GlobalScope>() - .resource_threads() - .send(SetCookiesForUrl(self.url(), cookies, NonHTTP)); + let cookies = cookie_header + .0 + .into_iter() + .filter_map(|cookie| cookie_rs::Cookie::parse(cookie).ok().map(Serde)) + .collect(); + let _ = self + .window + .upcast::<GlobalScope>() + .resource_threads() + .send(SetCookiesForUrl(self.url(), cookies, NonHTTP)); } Ok(()) } @@ -3761,7 +4006,11 @@ impl DocumentMethods for Document { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter - unsafe fn NamedGetter(&self, _cx: *mut JSContext, name: DOMString) -> Option<NonNull<JSObject>> { + unsafe fn NamedGetter( + &self, + _cx: *mut JSContext, + name: DOMString, + ) -> Option<NonNull<JSObject>> { #[derive(JSTraceable, MallocSizeOf)] struct NamedElementFilter { name: Atom, @@ -3811,25 +4060,28 @@ impl DocumentMethods for Document { let root = self.upcast::<Node>(); { // Step 1. - let mut elements = root.traverse_preorder() - .filter(|node| filter_by_name(&name, &node)) - .peekable(); + let mut elements = root + .traverse_preorder() + .filter(|node| filter_by_name(&name, &node)) + .peekable(); if let Some(first) = elements.next() { if elements.peek().is_none() { // TODO: Step 2. // Step 3. - return Some(NonNull::new_unchecked(first.reflector().get_jsobject().get())); + return Some(NonNull::new_unchecked( + first.reflector().get_jsobject().get(), + )); } } else { return None; } } // Step 4. - let filter = NamedElementFilter { - name: name, - }; + let filter = NamedElementFilter { name: name }; let collection = HTMLCollection::create(self.window(), root, Box::new(filter)); - Some(NonNull::new_unchecked(collection.reflector().get_jsobject().get())) + Some(NonNull::new_unchecked( + collection.reflector().get_jsobject().get(), + )) } // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:supported-property-names @@ -3857,7 +4109,11 @@ impl DocumentMethods for Document { global_event_handlers!(); // https://html.spec.whatwg.org/multipage/#handler-onreadystatechange - event_handler!(readystatechange, GetOnreadystatechange, SetOnreadystatechange); + event_handler!( + readystatechange, + GetOnreadystatechange, + SetOnreadystatechange + ); #[allow(unsafe_code)] // https://drafts.csswg.org/cssom-view/#dom-document-elementfrompoint @@ -3876,20 +4132,21 @@ impl DocumentMethods for Document { return None; } - match self.nodes_from_point(point, NodesFromPointQueryType::Topmost).first() { + match self + .nodes_from_point(point, NodesFromPointQueryType::Topmost) + .first() + { Some(address) => { let js_runtime = unsafe { JS_GetRuntime(window.get_cx()) }; - let node = unsafe { - node::from_untrusted_node_address(js_runtime, *address) - }; + let node = unsafe { node::from_untrusted_node_address(js_runtime, *address) }; let parent_node = node.GetParentNode().unwrap(); - let element_ref = node.downcast::<Element>().unwrap_or_else(|| { - parent_node.downcast::<Element>().unwrap() - }); + let element_ref = node + .downcast::<Element>() + .unwrap_or_else(|| parent_node.downcast::<Element>().unwrap()); Some(DomRoot::from_ref(element_ref)) }, - None => self.GetDocumentElement() + None => self.GetDocumentElement(), } } @@ -3902,29 +4159,30 @@ impl DocumentMethods for Document { let window = window_from_node(self); let viewport = match window.window_size() { Some(size) => size.initial_viewport, - None => return vec![] + None => return vec![], }; if self.browsing_context().is_none() { - return vec!(); + return vec![]; } // Step 2 if x < 0.0 || y < 0.0 || x > viewport.width || y > viewport.height { - return vec!(); + return vec![]; } let js_runtime = unsafe { JS_GetRuntime(window.get_cx()) }; // Step 1 and Step 3 let nodes = self.nodes_from_point(point, NodesFromPointQueryType::All); - let mut elements: Vec<DomRoot<Element>> = nodes.iter() + let mut elements: Vec<DomRoot<Element>> = nodes + .iter() .flat_map(|&untrusted_node_address| { let node = unsafe { node::from_untrusted_node_address(js_runtime, untrusted_node_address) }; DomRoot::downcast::<Element>(node) - }).collect(); + }).collect(); // Step 4 if let Some(root_element) = self.GetDocumentElement() { @@ -3964,7 +4222,10 @@ impl DocumentMethods for Document { return Err(Error::Security); } - if self.get_current_parser().map_or(false, |parser| parser.is_active()) { + if self + .get_current_parser() + .map_or(false, |parser| parser.is_active()) + { // Step 5. return Ok(DomRoot::from_ref(self)); } @@ -4045,8 +4306,11 @@ impl DocumentMethods for Document { // TODO: mute iframe load. // Step 26. - let resource_threads = - self.window.upcast::<GlobalScope>().resource_threads().clone(); + let resource_threads = self + .window + .upcast::<GlobalScope>() + .resource_threads() + .clone(); *self.loader.borrow_mut() = DocumentLoader::new_with_threads(resource_threads, Some(url.clone())); ServoParser::parse_html_script_input(self, url, "text/html"); @@ -4108,7 +4372,7 @@ impl DocumentMethods for Document { // Step 5. self.Open(None, "".into())?; self.get_current_parser().unwrap() - } + }, }; // Step 7. @@ -4144,7 +4408,7 @@ impl DocumentMethods for Document { _ => { // Step 3. return Ok(()); - } + }, }; // Step 4-6. @@ -4160,7 +4424,11 @@ impl DocumentMethods for Document { event_handler!(fullscreenerror, GetOnfullscreenerror, SetOnfullscreenerror); // https://fullscreen.spec.whatwg.org/#handler-document-onfullscreenchange - event_handler!(fullscreenchange, GetOnfullscreenchange, SetOnfullscreenchange); + event_handler!( + fullscreenchange, + GetOnfullscreenchange, + SetOnfullscreenchange + ); // https://fullscreen.spec.whatwg.org/#dom-document-fullscreenenabled fn FullscreenEnabled(&self) -> bool { @@ -4212,14 +4480,14 @@ pub fn determine_policy_for_token(token: &str) -> Option<ReferrerPolicy> { /// Specifies the type of focus event that is sent to a pipeline #[derive(Clone, Copy, PartialEq)] pub enum FocusType { - Element, // The first focus message - focus the element itself - Parent, // Focusing a parent element (an iframe) + Element, // The first focus message - focus the element itself + Parent, // Focusing a parent element (an iframe) } /// Focus events pub enum FocusEventType { - Focus, // Element gained focus. Doesn't bubble. - Blur, // Element lost focus. Doesn't bubble. + Focus, // Element gained focus. Doesn't bubble. + Blur, // Element lost focus. Doesn't bubble. } /// A fake `requestAnimationFrame()` callback—"fake" because it is not triggered by the video @@ -4244,10 +4512,12 @@ impl FakeRequestAnimationFrameCallback { #[derive(JSTraceable, MallocSizeOf)] pub enum AnimationFrameCallback { - DevtoolsFramerateTick { actor_name: String }, + DevtoolsFramerateTick { + actor_name: String, + }, FrameRequestCallback { #[ignore_malloc_size_of = "Rc is hard"] - callback: Rc<FrameRequestCallback> + callback: Rc<FrameRequestCallback>, }, } @@ -4256,14 +4526,18 @@ impl AnimationFrameCallback { match *self { AnimationFrameCallback::DevtoolsFramerateTick { ref actor_name } => { let msg = ScriptToDevtoolsControlMsg::FramerateTick(actor_name.clone(), now); - let devtools_sender = document.window().upcast::<GlobalScope>().devtools_chan().unwrap(); + let devtools_sender = document + .window() + .upcast::<GlobalScope>() + .devtools_chan() + .unwrap(); devtools_sender.send(msg).unwrap(); - } + }, AnimationFrameCallback::FrameRequestCallback { ref callback } => { // TODO(jdm): The spec says that any exceptions should be suppressed: // https://github.com/servo/servo/issues/6928 let _ = callback.Call__(Finite::wrap(now), ExceptionHandling::Report); - } + }, } } } @@ -4280,12 +4554,17 @@ impl PendingInOrderScriptVec { } fn push(&self, element: &HTMLScriptElement) { - self.scripts.borrow_mut().push_back(PendingScript::new(element)); + self.scripts + .borrow_mut() + .push_back(PendingScript::new(element)); } fn loaded(&self, element: &HTMLScriptElement, result: ScriptResult) { let mut scripts = self.scripts.borrow_mut(); - let entry = scripts.iter_mut().find(|entry| &*entry.element == element).unwrap(); + let entry = scripts + .iter_mut() + .find(|entry| &*entry.element == element) + .unwrap(); entry.loaded(result); } @@ -4310,11 +4589,17 @@ struct PendingScript { impl PendingScript { fn new(element: &HTMLScriptElement) -> Self { - Self { element: Dom::from_ref(element), load: None } + Self { + element: Dom::from_ref(element), + load: None, + } } fn new_with_load(element: &HTMLScriptElement, load: Option<ScriptResult>) -> Self { - Self { element: Dom::from_ref(element), load } + Self { + element: Dom::from_ref(element), + load, + } } fn loaded(&mut self, result: ScriptResult) { @@ -4323,6 +4608,8 @@ impl PendingScript { } fn take_result(&mut self) -> Option<(DomRoot<HTMLScriptElement>, ScriptResult)> { - self.load.take().map(|result| (DomRoot::from_ref(&*self.element), result)) + self.load + .take() + .map(|result| (DomRoot::from_ref(&*self.element), result)) } } diff --git a/components/script/dom/documentfragment.rs b/components/script/dom/documentfragment.rs index b4a0e3cd04b..444398700bc 100644 --- a/components/script/dom/documentfragment.rs +++ b/components/script/dom/documentfragment.rs @@ -34,9 +34,11 @@ impl DocumentFragment { } pub fn new(document: &Document) -> DomRoot<DocumentFragment> { - Node::reflect_node(Box::new(DocumentFragment::new_inherited(document)), - document, - DocumentFragmentBinding::Wrap) + Node::reflect_node( + Box::new(DocumentFragment::new_inherited(document)), + document, + DocumentFragmentBinding::Wrap, + ) } pub fn Constructor(window: &Window) -> Fallible<DomRoot<DocumentFragment>> { @@ -57,12 +59,14 @@ impl DocumentFragmentMethods for DocumentFragment { fn GetElementById(&self, id: DOMString) -> Option<DomRoot<Element>> { let node = self.upcast::<Node>(); let id = Atom::from(id); - node.traverse_preorder().filter_map(DomRoot::downcast::<Element>).find(|descendant| { - match descendant.get_attribute(&ns!(), &local_name!("id")) { - None => false, - Some(attr) => *attr.value().as_atom() == id, - } - }) + node.traverse_preorder() + .filter_map(DomRoot::downcast::<Element>) + .find( + |descendant| match descendant.get_attribute(&ns!(), &local_name!("id")) { + None => false, + Some(attr) => *attr.value().as_atom() == id, + }, + ) } // https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild @@ -72,7 +76,10 @@ impl DocumentFragmentMethods for DocumentFragment { // https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild fn GetLastElementChild(&self) -> Option<DomRoot<Element>> { - self.upcast::<Node>().rev_children().filter_map(DomRoot::downcast::<Element>).next() + self.upcast::<Node>() + .rev_children() + .filter_map(DomRoot::downcast::<Element>) + .next() } // https://dom.spec.whatwg.org/#dom-parentnode-childelementcount diff --git a/components/script/dom/documenttype.rs b/components/script/dom/documenttype.rs index d00ecb7ff56..007790abe4d 100644 --- a/components/script/dom/documenttype.rs +++ b/components/script/dom/documenttype.rs @@ -24,11 +24,12 @@ pub struct DocumentType { } impl DocumentType { - fn new_inherited(name: DOMString, - public_id: Option<DOMString>, - system_id: Option<DOMString>, - document: &Document) - -> DocumentType { + fn new_inherited( + name: DOMString, + public_id: Option<DOMString>, + system_id: Option<DOMString>, + document: &Document, + ) -> DocumentType { DocumentType { node: Node::new_inherited(document), name: name, @@ -37,14 +38,19 @@ impl DocumentType { } } #[allow(unrooted_must_root)] - pub fn new(name: DOMString, - public_id: Option<DOMString>, - system_id: Option<DOMString>, - document: &Document) - -> DomRoot<DocumentType> { - Node::reflect_node(Box::new(DocumentType::new_inherited(name, public_id, system_id, document)), - document, - DocumentTypeBinding::Wrap) + pub fn new( + name: DOMString, + public_id: Option<DOMString>, + system_id: Option<DOMString>, + document: &Document, + ) -> DomRoot<DocumentType> { + Node::reflect_node( + Box::new(DocumentType::new_inherited( + name, public_id, system_id, document, + )), + document, + DocumentTypeBinding::Wrap, + ) } #[inline] diff --git a/components/script/dom/domexception.rs b/components/script/dom/domexception.rs index 4f2c076ec66..92debdc825e 100644 --- a/components/script/dom/domexception.rs +++ b/components/script/dom/domexception.rs @@ -53,9 +53,11 @@ impl DOMException { } pub fn new(global: &GlobalScope, code: DOMErrorName) -> DomRoot<DOMException> { - reflect_dom_object(Box::new(DOMException::new_inherited(code)), - global, - DOMExceptionBinding::Wrap) + reflect_dom_object( + Box::new(DOMException::new_inherited(code)), + global, + DOMExceptionBinding::Wrap, + ) } } @@ -74,7 +76,9 @@ impl DOMExceptionMethods for DOMException { fn Message(&self) -> DOMString { let message = match self.code { DOMErrorName::IndexSizeError => "The index is not in the allowed range.", - DOMErrorName::HierarchyRequestError => "The operation would yield an incorrect node tree.", + DOMErrorName::HierarchyRequestError => { + "The operation would yield an incorrect node tree." + }, DOMErrorName::WrongDocumentError => "The object is in the wrong document.", DOMErrorName::InvalidCharacterError => "The string contains invalid characters.", DOMErrorName::NoModificationAllowedError => "The object can not be modified.", @@ -85,17 +89,20 @@ impl DOMExceptionMethods for DOMException { DOMErrorName::SyntaxError => "The string did not match the expected pattern.", DOMErrorName::InvalidModificationError => "The object can not be modified in this way.", DOMErrorName::NamespaceError => "The operation is not allowed by Namespaces in XML.", - DOMErrorName::InvalidAccessError => "The object does not support the operation or argument.", + DOMErrorName::InvalidAccessError => { + "The object does not support the operation or argument." + }, DOMErrorName::SecurityError => "The operation is insecure.", DOMErrorName::NetworkError => "A network error occurred.", DOMErrorName::AbortError => "The operation was aborted.", DOMErrorName::TypeMismatchError => "The given type does not match any expected type.", DOMErrorName::QuotaExceededError => "The quota has been exceeded.", DOMErrorName::TimeoutError => "The operation timed out.", - DOMErrorName::InvalidNodeTypeError => - "The supplied node is incorrect or has an incorrect ancestor for this operation.", + DOMErrorName::InvalidNodeTypeError => { + "The supplied node is incorrect or has an incorrect ancestor for this operation." + }, DOMErrorName::DataCloneError => "The object can not be cloned.", - DOMErrorName::NotReadableError => "The I/O read operation failed." + DOMErrorName::NotReadableError => "The I/O read operation failed.", }; DOMString::from(message) diff --git a/components/script/dom/domimplementation.rs b/components/script/dom/domimplementation.rs index c93182aab6e..f20cc61f3df 100644 --- a/components/script/dom/domimplementation.rs +++ b/components/script/dom/domimplementation.rs @@ -44,57 +44,79 @@ impl DOMImplementation { pub fn new(document: &Document) -> DomRoot<DOMImplementation> { let window = document.window(); - reflect_dom_object(Box::new(DOMImplementation::new_inherited(document)), - window, - DOMImplementationBinding::Wrap) + reflect_dom_object( + Box::new(DOMImplementation::new_inherited(document)), + window, + DOMImplementationBinding::Wrap, + ) } } // https://dom.spec.whatwg.org/#domimplementation impl DOMImplementationMethods for DOMImplementation { // https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype - fn CreateDocumentType(&self, - qualified_name: DOMString, - pubid: DOMString, - sysid: DOMString) - -> Fallible<DomRoot<DocumentType>> { + fn CreateDocumentType( + &self, + qualified_name: DOMString, + pubid: DOMString, + sysid: DOMString, + ) -> Fallible<DomRoot<DocumentType>> { validate_qualified_name(&qualified_name)?; - Ok(DocumentType::new(qualified_name, Some(pubid), Some(sysid), &self.document)) + Ok(DocumentType::new( + qualified_name, + Some(pubid), + Some(sysid), + &self.document, + )) } // https://dom.spec.whatwg.org/#dom-domimplementation-createdocument - fn CreateDocument(&self, - maybe_namespace: Option<DOMString>, - qname: DOMString, - maybe_doctype: Option<&DocumentType>) - -> Fallible<DomRoot<XMLDocument>> { + fn CreateDocument( + &self, + maybe_namespace: Option<DOMString>, + qname: DOMString, + maybe_doctype: Option<&DocumentType>, + ) -> Fallible<DomRoot<XMLDocument>> { let win = self.document.window(); let loader = DocumentLoader::new(&self.document.loader()); let namespace = namespace_from_domstring(maybe_namespace.to_owned()); let content_type = match namespace { - ns!(html) => Mime(TopLevel::Application, SubLevel::Ext("xhtml+xml".to_string()), vec![]), - ns!(svg) => Mime(TopLevel::Image, SubLevel::Ext("svg+xml".to_string()), vec![]), - _ => Mime(TopLevel::Application, SubLevel::Xml, vec![]) + ns!(html) => Mime( + TopLevel::Application, + SubLevel::Ext("xhtml+xml".to_string()), + vec![], + ), + ns!(svg) => Mime( + TopLevel::Image, + SubLevel::Ext("svg+xml".to_string()), + vec![], + ), + _ => Mime(TopLevel::Application, SubLevel::Xml, vec![]), }; // Step 1. - let doc = XMLDocument::new(win, - HasBrowsingContext::No, - None, - self.document.origin().clone(), - IsHTMLDocument::NonHTMLDocument, - Some(content_type), - None, - DocumentActivity::Inactive, - DocumentSource::NotFromParser, - loader); + let doc = XMLDocument::new( + win, + HasBrowsingContext::No, + None, + self.document.origin().clone(), + IsHTMLDocument::NonHTMLDocument, + Some(content_type), + None, + DocumentActivity::Inactive, + DocumentSource::NotFromParser, + loader, + ); // Step 2-3. let maybe_elem = if qname.is_empty() { None } else { let options = ElementCreationOptions { is: None }; - match doc.upcast::<Document>().CreateElementNS(maybe_namespace, qname, &options) { + match doc + .upcast::<Document>() + .CreateElementNS(maybe_namespace, qname, &options) + { Err(error) => return Err(error), Ok(elem) => Some(elem), } @@ -127,19 +149,21 @@ impl DOMImplementationMethods for DOMImplementation { let loader = DocumentLoader::new(&self.document.loader()); // Step 1-2. - let doc = Document::new(win, - HasBrowsingContext::No, - None, - self.document.origin().clone(), - IsHTMLDocument::HTMLDocument, - None, - None, - DocumentActivity::Inactive, - DocumentSource::NotFromParser, - loader, - None, - None, - Default::default()); + let doc = Document::new( + win, + HasBrowsingContext::No, + None, + self.document.origin().clone(), + IsHTMLDocument::HTMLDocument, + None, + None, + DocumentActivity::Inactive, + DocumentSource::NotFromParser, + loader, + None, + None, + Default::default(), + ); { // Step 3. @@ -151,25 +175,24 @@ impl DOMImplementationMethods for DOMImplementation { { // Step 4. let doc_node = doc.upcast::<Node>(); - let doc_html = DomRoot::upcast::<Node>(HTMLHtmlElement::new(local_name!("html"), - None, - &doc)); + let doc_html = + DomRoot::upcast::<Node>(HTMLHtmlElement::new(local_name!("html"), None, &doc)); doc_node.AppendChild(&doc_html).expect("Appending failed"); { // Step 5. - let doc_head = DomRoot::upcast::<Node>(HTMLHeadElement::new(local_name!("head"), - None, - &doc)); + let doc_head = + DomRoot::upcast::<Node>(HTMLHeadElement::new(local_name!("head"), None, &doc)); doc_html.AppendChild(&doc_head).unwrap(); // Step 6. if let Some(title_str) = title { // Step 6.1. - let doc_title = - DomRoot::upcast::<Node>(HTMLTitleElement::new(local_name!("title"), - None, - &doc)); + let doc_title = DomRoot::upcast::<Node>(HTMLTitleElement::new( + local_name!("title"), + None, + &doc, + )); doc_head.AppendChild(&doc_title).unwrap(); // Step 6.2. diff --git a/components/script/dom/dommatrix.rs b/components/script/dom/dommatrix.rs index 5cbe4ad9b68..6e6a2098774 100644 --- a/components/script/dom/dommatrix.rs +++ b/components/script/dom/dommatrix.rs @@ -17,7 +17,7 @@ use js::typedarray::{Float32Array, Float64Array}; #[dom_struct] pub struct DOMMatrix { - parent: DOMMatrixReadOnly + parent: DOMMatrixReadOnly, } impl DOMMatrix { @@ -29,7 +29,7 @@ impl DOMMatrix { pub fn new_inherited(is2D: bool, matrix: Transform3D<f64>) -> Self { DOMMatrix { - parent: DOMMatrixReadOnly::new_inherited(is2D, matrix) + parent: DOMMatrixReadOnly::new_inherited(is2D, matrix), } } @@ -40,18 +40,12 @@ impl DOMMatrix { // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-dommatrix-numbersequence pub fn Constructor_(global: &GlobalScope, entries: Vec<f64>) -> Fallible<DomRoot<Self>> { - entries_to_matrix(&entries[..]) - .map(|(is2D, matrix)| { - Self::new(global, is2D, matrix) - }) + entries_to_matrix(&entries[..]).map(|(is2D, matrix)| Self::new(global, is2D, matrix)) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-frommatrix pub fn FromMatrix(global: &GlobalScope, other: &DOMMatrixInit) -> Fallible<DomRoot<Self>> { - dommatrixinit_to_matrix(&other) - .map(|(is2D, matrix)| { - Self::new(global, is2D, matrix) - }) + dommatrixinit_to_matrix(&other).map(|(is2D, matrix)| Self::new(global, is2D, matrix)) } pub fn from_readonly(global: &GlobalScope, ro: &DOMMatrixReadOnly) -> DomRoot<Self> { @@ -299,7 +293,7 @@ impl DOMMatrixMethods for DOMMatrix { } // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-multiplyself - fn MultiplySelf(&self, other:&DOMMatrixInit) -> Fallible<DomRoot<DOMMatrix>> { + fn MultiplySelf(&self, other: &DOMMatrixInit) -> Fallible<DomRoot<DOMMatrix>> { // Steps 1-3. self.upcast::<DOMMatrixReadOnly>().multiply_self(other) // Step 4. @@ -307,7 +301,7 @@ impl DOMMatrixMethods for DOMMatrix { } // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-premultiplyself - fn PreMultiplySelf(&self, other:&DOMMatrixInit) -> Fallible<DomRoot<DOMMatrix>> { + fn PreMultiplySelf(&self, other: &DOMMatrixInit) -> Fallible<DomRoot<DOMMatrix>> { // Steps 1-3. self.upcast::<DOMMatrixReadOnly>().pre_multiply_self(other) // Step 4. @@ -317,24 +311,40 @@ impl DOMMatrixMethods for DOMMatrix { // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-translateself fn TranslateSelf(&self, tx: f64, ty: f64, tz: f64) -> DomRoot<DOMMatrix> { // Steps 1-2. - self.upcast::<DOMMatrixReadOnly>().translate_self(tx, ty, tz); + self.upcast::<DOMMatrixReadOnly>() + .translate_self(tx, ty, tz); // Step 3. DomRoot::from_ref(&self) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-scaleself - fn ScaleSelf(&self, scaleX: f64, scaleY: Option<f64>, scaleZ: f64, - originX: f64, originY: f64, originZ: f64) -> DomRoot<DOMMatrix> { + fn ScaleSelf( + &self, + scaleX: f64, + scaleY: Option<f64>, + scaleZ: f64, + originX: f64, + originY: f64, + originZ: f64, + ) -> DomRoot<DOMMatrix> { // Steps 1-6. - self.upcast::<DOMMatrixReadOnly>().scale_self(scaleX, scaleY, scaleZ, originX, originY, originZ); + self.upcast::<DOMMatrixReadOnly>() + .scale_self(scaleX, scaleY, scaleZ, originX, originY, originZ); // Step 7. DomRoot::from_ref(&self) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-scale3dself - fn Scale3dSelf(&self, scale: f64, originX: f64, originY: f64, originZ: f64) -> DomRoot<DOMMatrix> { + fn Scale3dSelf( + &self, + scale: f64, + originX: f64, + originY: f64, + originZ: f64, + ) -> DomRoot<DOMMatrix> { // Steps 1-4. - self.upcast::<DOMMatrixReadOnly>().scale_3d_self(scale, originX, originY, originZ); + self.upcast::<DOMMatrixReadOnly>() + .scale_3d_self(scale, originX, originY, originZ); // Step 5. DomRoot::from_ref(&self) } @@ -342,7 +352,8 @@ impl DOMMatrixMethods for DOMMatrix { // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-rotateself fn RotateSelf(&self, rotX: f64, rotY: Option<f64>, rotZ: Option<f64>) -> DomRoot<DOMMatrix> { // Steps 1-7. - self.upcast::<DOMMatrixReadOnly>().rotate_self(rotX, rotY, rotZ); + self.upcast::<DOMMatrixReadOnly>() + .rotate_self(rotX, rotY, rotZ); // Step 8. DomRoot::from_ref(&self) } @@ -350,7 +361,8 @@ impl DOMMatrixMethods for DOMMatrix { // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-rotatefromvectorself fn RotateFromVectorSelf(&self, x: f64, y: f64) -> DomRoot<DOMMatrix> { // Step 1. - self.upcast::<DOMMatrixReadOnly>().rotate_from_vector_self(x, y); + self.upcast::<DOMMatrixReadOnly>() + .rotate_from_vector_self(x, y); // Step 2. DomRoot::from_ref(&self) } @@ -358,7 +370,8 @@ impl DOMMatrixMethods for DOMMatrix { // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-rotateaxisangleself fn RotateAxisAngleSelf(&self, x: f64, y: f64, z: f64, angle: f64) -> DomRoot<DOMMatrix> { // Steps 1-2. - self.upcast::<DOMMatrixReadOnly>().rotate_axis_angle_self(x, y, z, angle); + self.upcast::<DOMMatrixReadOnly>() + .rotate_axis_angle_self(x, y, z, angle); // Step 3. DomRoot::from_ref(&self) } diff --git a/components/script/dom/dommatrixreadonly.rs b/components/script/dom/dommatrixreadonly.rs index 4996cf428b2..a698ba81111 100644 --- a/components/script/dom/dommatrixreadonly.rs +++ b/components/script/dom/dommatrixreadonly.rs @@ -53,18 +53,12 @@ impl DOMMatrixReadOnly { // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-dommatrixreadonly-numbersequence pub fn Constructor_(global: &GlobalScope, entries: Vec<f64>) -> Fallible<DomRoot<Self>> { - entries_to_matrix(&entries[..]) - .map(|(is2D, matrix)| { - Self::new(global, is2D, matrix) - }) + entries_to_matrix(&entries[..]).map(|(is2D, matrix)| Self::new(global, is2D, matrix)) } // 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) - }) + dommatrixinit_to_matrix(&other).map(|(is2D, matrix)| Self::new(global, is2D, matrix)) } pub fn matrix(&self) -> Ref<Transform3D<f64>> { @@ -155,7 +149,6 @@ impl DOMMatrixReadOnly { self.matrix.borrow_mut().m44 = value; } - // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-multiplyself pub fn multiply_self(&self, other: &DOMMatrixInit) -> Fallible<()> { // Step 1. @@ -200,8 +193,15 @@ impl DOMMatrixReadOnly { } // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-scaleself - pub fn scale_self(&self, scaleX: f64, scaleY: Option<f64>, scaleZ: f64, - mut originX: f64, mut originY: f64, mut originZ: f64) { + pub fn scale_self( + &self, + scaleX: f64, + scaleY: Option<f64>, + scaleZ: f64, + mut originX: f64, + mut originY: f64, + mut originZ: f64, + ) { // Step 1. self.translate_self(originX, originY, originZ); // Step 2. @@ -262,19 +262,22 @@ impl DOMMatrixReadOnly { } if rotZ != 0.0 { // Step 5. - let rotation = Transform3D::create_rotation(0.0, 0.0, 1.0, Angle::radians(rotZ.to_radians())); + let rotation = + Transform3D::create_rotation(0.0, 0.0, 1.0, Angle::radians(rotZ.to_radians())); let mut matrix = self.matrix.borrow_mut(); *matrix = rotation.post_mul(&matrix); } if rotY != 0.0 { // Step 6. - let rotation = Transform3D::create_rotation(0.0, 1.0, 0.0, Angle::radians(rotY.to_radians())); + let rotation = + Transform3D::create_rotation(0.0, 1.0, 0.0, Angle::radians(rotY.to_radians())); let mut matrix = self.matrix.borrow_mut(); *matrix = rotation.post_mul(&matrix); } if rotX != 0.0 { // Step 7. - let rotation = Transform3D::create_rotation(1.0, 0.0, 0.0, Angle::radians(rotX.to_radians())); + let rotation = + Transform3D::create_rotation(1.0, 0.0, 0.0, Angle::radians(rotX.to_radians())); let mut matrix = self.matrix.borrow_mut(); *matrix = rotation.post_mul(&matrix); } @@ -298,7 +301,12 @@ impl DOMMatrixReadOnly { pub fn rotate_axis_angle_self(&self, x: f64, y: f64, z: f64, angle: f64) { // Step 1. let (norm_x, norm_y, norm_z) = normalize_point(x, y, z); - let rotation = Transform3D::create_rotation(norm_x, norm_y, norm_z, Angle::radians(angle.to_radians())); + let rotation = Transform3D::create_rotation( + norm_x, + norm_y, + norm_z, + Angle::radians(angle.to_radians()), + ); let mut matrix = self.matrix.borrow_mut(); *matrix = rotation.post_mul(&matrix); // Step 2. @@ -333,10 +341,24 @@ impl DOMMatrixReadOnly { *matrix = matrix.inverse().unwrap_or_else(|| { // Step 2. self.is2D.set(false); - Transform3D::row_major(f64::NAN, f64::NAN, f64::NAN, f64::NAN, - f64::NAN, f64::NAN, f64::NAN, f64::NAN, - f64::NAN, f64::NAN, f64::NAN, f64::NAN, - f64::NAN, f64::NAN, f64::NAN, f64::NAN) + Transform3D::row_major( + f64::NAN, + f64::NAN, + f64::NAN, + f64::NAN, + f64::NAN, + f64::NAN, + f64::NAN, + f64::NAN, + f64::NAN, + f64::NAN, + f64::NAN, + f64::NAN, + f64::NAN, + f64::NAN, + f64::NAN, + f64::NAN, + ) }) // Step 3 in DOMMatrix.InvertSelf } @@ -362,7 +384,6 @@ impl DOMMatrixReadOnly { } } - impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-m11 fn M11(&self) -> f64 { @@ -482,10 +503,22 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-isidentity fn IsIdentity(&self) -> bool { let matrix = self.matrix.borrow(); - matrix.m12 == 0.0 && matrix.m13 == 0.0 && matrix.m14 == 0.0 && matrix.m21 == 0.0 && - matrix.m23 == 0.0 && matrix.m24 == 0.0 && matrix.m31 == 0.0 && matrix.m32 == 0.0 && - matrix.m34 == 0.0 && matrix.m41 == 0.0 && matrix.m42 == 0.0 && matrix.m43 == 0.0 && - matrix.m11 == 1.0 && matrix.m22 == 1.0 && matrix.m33 == 1.0 && matrix.m44 == 1.0 + matrix.m12 == 0.0 && + matrix.m13 == 0.0 && + matrix.m14 == 0.0 && + matrix.m21 == 0.0 && + matrix.m23 == 0.0 && + matrix.m24 == 0.0 && + matrix.m31 == 0.0 && + matrix.m32 == 0.0 && + matrix.m34 == 0.0 && + matrix.m41 == 0.0 && + matrix.m42 == 0.0 && + matrix.m43 == 0.0 && + matrix.m11 == 1.0 && + matrix.m22 == 1.0 && + matrix.m33 == 1.0 && + matrix.m44 == 1.0 } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-translate @@ -494,16 +527,22 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-scale - fn Scale(&self, scaleX: f64, scaleY: Option<f64>, scaleZ: f64, - originX: f64, originY: f64, originZ: f64) -> DomRoot<DOMMatrix> { + fn Scale( + &self, + scaleX: f64, + scaleY: Option<f64>, + scaleZ: f64, + originX: f64, + originY: f64, + originZ: f64, + ) -> DomRoot<DOMMatrix> { DOMMatrix::from_readonly(&self.global(), self) .ScaleSelf(scaleX, scaleY, scaleZ, originX, originY, originZ) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-scale3d fn Scale3d(&self, scale: f64, originX: f64, originY: f64, originZ: f64) -> DomRoot<DOMMatrix> { - DOMMatrix::from_readonly(&self.global(), self) - .Scale3dSelf(scale, originX, originY, originZ) + DOMMatrix::from_readonly(&self.global(), self).Scale3dSelf(scale, originX, originY, originZ) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-rotate @@ -539,10 +578,9 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-flipx fn FlipX(&self) -> DomRoot<DOMMatrix> { let is2D = self.is2D.get(); - let flip = Transform3D::row_major(-1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0); + let flip = Transform3D::row_major( + -1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, + ); let matrix = flip.post_mul(&self.matrix.borrow()); DOMMatrix::new(&self.global(), is2D, matrix) } @@ -550,10 +588,9 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-flipy fn FlipY(&self) -> DomRoot<DOMMatrix> { let is2D = self.is2D.get(); - let flip = Transform3D::row_major(1.0, 0.0, 0.0, 0.0, - 0.0, -1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0); + let flip = Transform3D::row_major( + 1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, + ); let matrix = flip.post_mul(&self.matrix.borrow()); DOMMatrix::new(&self.global(), is2D, matrix) } @@ -583,11 +620,15 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-tofloat32array #[allow(unsafe_code)] unsafe fn ToFloat32Array(&self, cx: *mut JSContext) -> NonNull<JSObject> { - let vec: Vec<f32> = self.matrix - .borrow().to_row_major_array().iter().map(|&x| x as f32).collect(); + let vec: Vec<f32> = self + .matrix + .borrow() + .to_row_major_array() + .iter() + .map(|&x| x as f32) + .collect(); rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); - let _ = Float32Array::create(cx, CreateWith::Slice(&vec), array.handle_mut()) - .unwrap(); + let _ = Float32Array::create(cx, CreateWith::Slice(&vec), array.handle_mut()).unwrap(); NonNull::new_unchecked(array.get()) } @@ -596,28 +637,39 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { unsafe fn ToFloat64Array(&self, cx: *mut JSContext) -> NonNull<JSObject> { let arr = self.matrix.borrow().to_row_major_array(); rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); - let _ = Float64Array::create(cx, CreateWith::Slice(&arr), array.handle_mut()) - .unwrap(); + let _ = Float64Array::create(cx, CreateWith::Slice(&arr), array.handle_mut()).unwrap(); NonNull::new_unchecked(array.get()) } } - // https://drafts.fxtf.org/geometry-1/#create-a-2d-matrix fn create_2d_matrix(entries: &[f64]) -> Transform3D<f64> { - Transform3D::row_major(entries[0], entries[1], 0.0, 0.0, - entries[2], entries[3], 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - entries[4], entries[5], 0.0, 1.0) + Transform3D::row_major( + entries[0], entries[1], 0.0, 0.0, entries[2], entries[3], 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, + entries[4], entries[5], 0.0, 1.0, + ) } - // https://drafts.fxtf.org/geometry-1/#create-a-3d-matrix fn create_3d_matrix(entries: &[f64]) -> Transform3D<f64> { - Transform3D::row_major(entries[0], entries[1], entries[2], entries[3], - entries[4], entries[5], entries[6], entries[7], - entries[8], entries[9], entries[10], entries[11], - entries[12], entries[13], entries[14], entries[15]) + Transform3D::row_major( + entries[0], + entries[1], + entries[2], + entries[3], + entries[4], + entries[5], + entries[6], + entries[7], + entries[8], + entries[9], + entries[10], + entries[11], + entries[12], + entries[13], + entries[14], + entries[15], + ) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-dommatrixreadonly-numbersequence @@ -632,21 +684,29 @@ pub fn entries_to_matrix(entries: &[f64]) -> Fallible<(bool, Transform3D<f64>)> } } - // https://drafts.fxtf.org/geometry-1/#validate-and-fixup pub fn dommatrixinit_to_matrix(dict: &DOMMatrixInit) -> Fallible<(bool, Transform3D<f64>)> { // Step 1. if dict.a.is_some() && dict.m11.is_some() && dict.a.unwrap() != dict.m11.unwrap() || - dict.b.is_some() && dict.m12.is_some() && dict.b.unwrap() != dict.m12.unwrap() || - dict.c.is_some() && dict.m21.is_some() && dict.c.unwrap() != dict.m21.unwrap() || - dict.d.is_some() && dict.m22.is_some() && dict.d.unwrap() != dict.m22.unwrap() || - dict.e.is_some() && dict.m41.is_some() && dict.e.unwrap() != dict.m41.unwrap() || - dict.f.is_some() && dict.m42.is_some() && dict.f.unwrap() != dict.m42.unwrap() || - dict.is2D.is_some() && dict.is2D.unwrap() && - (dict.m31 != 0.0 || dict.m32 != 0.0 || dict.m13 != 0.0 || dict.m23 != 0.0 || - dict.m43 != 0.0 || dict.m14 != 0.0 || dict.m24 != 0.0 || dict.m34 != 0.0 || - dict.m33 != 1.0 || dict.m44 != 1.0) { - Err(error::Error::Type("Invalid matrix initializer.".to_owned())) + dict.b.is_some() && dict.m12.is_some() && dict.b.unwrap() != dict.m12.unwrap() || + dict.c.is_some() && dict.m21.is_some() && dict.c.unwrap() != dict.m21.unwrap() || + dict.d.is_some() && dict.m22.is_some() && dict.d.unwrap() != dict.m22.unwrap() || + dict.e.is_some() && dict.m41.is_some() && dict.e.unwrap() != dict.m41.unwrap() || + dict.f.is_some() && dict.m42.is_some() && dict.f.unwrap() != dict.m42.unwrap() || + dict.is2D.is_some() && + dict.is2D.unwrap() && + (dict.m31 != 0.0 || + dict.m32 != 0.0 || + dict.m13 != 0.0 || + dict.m23 != 0.0 || + dict.m43 != 0.0 || + dict.m14 != 0.0 || + dict.m24 != 0.0 || + dict.m34 != 0.0 || + dict.m33 != 1.0 || + dict.m44 != 1.0) + { + Err(error::Error::Type("Invalid matrix initializer.".to_owned())) } else { let mut is2D = dict.is2D; // Step 2. @@ -663,25 +723,31 @@ pub fn dommatrixinit_to_matrix(dict: &DOMMatrixInit) -> Fallible<(bool, Transfor let m42 = dict.m42.unwrap_or(dict.f.unwrap_or(0.0)); // Step 8. if is2D.is_none() && - (dict.m31 != 0.0 || dict.m32 != 0.0 || dict.m13 != 0.0 || - dict.m23 != 0.0 || dict.m43 != 0.0 || dict.m14 != 0.0 || - dict.m24 != 0.0 || dict.m34 != 0.0 || - dict.m33 != 1.0 || dict.m44 != 1.0) { - is2D = Some(false); + (dict.m31 != 0.0 || + dict.m32 != 0.0 || + dict.m13 != 0.0 || + dict.m23 != 0.0 || + dict.m43 != 0.0 || + dict.m14 != 0.0 || + dict.m24 != 0.0 || + dict.m34 != 0.0 || + dict.m33 != 1.0 || + dict.m44 != 1.0) + { + is2D = Some(false); } // Step 9. if is2D.is_none() { is2D = Some(true); } - let matrix = Transform3D::row_major(m11, m12, dict.m13, dict.m14, - m21, m22, dict.m23, dict.m24, - dict.m31, dict.m32, dict.m33, dict.m34, - m41, m42, dict.m43, dict.m44); + let matrix = Transform3D::row_major( + m11, m12, dict.m13, dict.m14, m21, m22, dict.m23, dict.m24, dict.m31, dict.m32, + dict.m33, dict.m34, m41, m42, dict.m43, dict.m44, + ); Ok((is2D.unwrap(), matrix)) } } - #[inline] fn normalize_point(x: f64, y: f64, z: f64) -> (f64, f64, f64) { let len = (x * x + y * y + z * z).sqrt(); diff --git a/components/script/dom/domparser.rs b/components/script/dom/domparser.rs index 2d293d0a184..d2b5ac80b95 100644 --- a/components/script/dom/domparser.rs +++ b/components/script/dom/domparser.rs @@ -37,9 +37,11 @@ impl DOMParser { } pub fn new(window: &Window) -> DomRoot<DOMParser> { - reflect_dom_object(Box::new(DOMParser::new_inherited(window)), - window, - DOMParserBinding::Wrap) + reflect_dom_object( + Box::new(DOMParser::new_inherited(window)), + window, + DOMParserBinding::Wrap, + ) } pub fn Constructor(window: &Window) -> Fallible<DomRoot<DOMParser>> { @@ -49,51 +51,59 @@ impl DOMParser { impl DOMParserMethods for DOMParser { // https://w3c.github.io/DOM-Parsing/#the-domparser-interface - fn ParseFromString(&self, - s: DOMString, - ty: DOMParserBinding::SupportedType) - -> Fallible<DomRoot<Document>> { + fn ParseFromString( + &self, + s: DOMString, + ty: DOMParserBinding::SupportedType, + ) -> Fallible<DomRoot<Document>> { let url = self.window.get_url(); - let content_type = ty.as_str().parse().expect("Supported type is not a MIME type"); + let content_type = ty + .as_str() + .parse() + .expect("Supported type is not a MIME type"); let doc = self.window.Document(); let loader = DocumentLoader::new(&*doc.loader()); match ty { Text_html => { - let document = Document::new(&self.window, - HasBrowsingContext::No, - Some(url.clone()), - doc.origin().clone(), - IsHTMLDocument::HTMLDocument, - Some(content_type), - None, - DocumentActivity::Inactive, - DocumentSource::FromParser, - loader, - None, - None, - Default::default()); + let document = Document::new( + &self.window, + HasBrowsingContext::No, + Some(url.clone()), + doc.origin().clone(), + IsHTMLDocument::HTMLDocument, + Some(content_type), + None, + DocumentActivity::Inactive, + DocumentSource::FromParser, + loader, + None, + None, + Default::default(), + ); ServoParser::parse_html_document(&document, s, url); document.set_ready_state(DocumentReadyState::Complete); Ok(document) - } + }, Text_xml | Application_xml | Application_xhtml_xml => { - let document = Document::new(&self.window, - HasBrowsingContext::No, - Some(url.clone()), - doc.origin().clone(), - IsHTMLDocument::NonHTMLDocument, - Some(content_type), - None, - DocumentActivity::Inactive, - DocumentSource::FromParser, - loader, - None, - None, - Default::default()); + let document = Document::new( + &self.window, + HasBrowsingContext::No, + Some(url.clone()), + doc.origin().clone(), + IsHTMLDocument::NonHTMLDocument, + Some(content_type), + None, + DocumentActivity::Inactive, + DocumentSource::FromParser, + loader, + None, + None, + Default::default(), + ); ServoParser::parse_xml_document(&document, s, url); document.set_ready_state(DocumentReadyState::Complete); Ok(document) - } + }, } } } diff --git a/components/script/dom/dompoint.rs b/components/script/dom/dompoint.rs index 9653c08a120..ec0e96062bd 100644 --- a/components/script/dom/dompoint.rs +++ b/components/script/dom/dompoint.rs @@ -28,12 +28,13 @@ impl DOMPoint { reflect_dom_object(Box::new(DOMPoint::new_inherited(x, y, z, w)), global, Wrap) } - pub fn Constructor(global: &GlobalScope, - x: f64, - y: f64, - z: f64, - w: f64) - -> Fallible<DomRoot<DOMPoint>> { + pub fn Constructor( + global: &GlobalScope, + x: f64, + y: f64, + z: f64, + w: f64, + ) -> Fallible<DomRoot<DOMPoint>> { Ok(DOMPoint::new(global, x, y, z, w)) } diff --git a/components/script/dom/dompointreadonly.rs b/components/script/dom/dompointreadonly.rs index 03570b27362..28b3fea458f 100644 --- a/components/script/dom/dompointreadonly.rs +++ b/components/script/dom/dompointreadonly.rs @@ -32,17 +32,20 @@ impl DOMPointReadOnly { } pub fn new(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> DomRoot<DOMPointReadOnly> { - reflect_dom_object(Box::new(DOMPointReadOnly::new_inherited(x, y, z, w)), - global, - Wrap) + reflect_dom_object( + Box::new(DOMPointReadOnly::new_inherited(x, y, z, w)), + global, + Wrap, + ) } - pub fn Constructor(global: &GlobalScope, - x: f64, - y: f64, - z: f64, - w: f64) - -> Fallible<DomRoot<DOMPointReadOnly>> { + pub fn Constructor( + global: &GlobalScope, + x: f64, + y: f64, + z: f64, + w: f64, + ) -> Fallible<DomRoot<DOMPointReadOnly>> { Ok(DOMPointReadOnly::new(global, x, y, z, w)) } } diff --git a/components/script/dom/domquad.rs b/components/script/dom/domquad.rs index 49c882db9bd..b4270898d3f 100644 --- a/components/script/dom/domquad.rs +++ b/components/script/dom/domquad.rs @@ -24,11 +24,7 @@ pub struct DOMQuad { } impl DOMQuad { - fn new_inherited(p1: &DOMPoint, - p2: &DOMPoint, - p3: &DOMPoint, - p4: &DOMPoint) - -> DOMQuad { + fn new_inherited(p1: &DOMPoint, p2: &DOMPoint, p3: &DOMPoint, p4: &DOMPoint) -> DOMQuad { DOMQuad { reflector_: Reflector::new(), p1: Dom::from_ref(p1), @@ -38,45 +34,62 @@ impl DOMQuad { } } - pub fn new(global: &GlobalScope, - p1: &DOMPoint, - p2: &DOMPoint, - p3: &DOMPoint, - p4: &DOMPoint) -> DomRoot<DOMQuad> { - reflect_dom_object(Box::new(DOMQuad::new_inherited(p1, p2, p3, p4)), - global, - Wrap) + pub fn new( + global: &GlobalScope, + p1: &DOMPoint, + p2: &DOMPoint, + p3: &DOMPoint, + p4: &DOMPoint, + ) -> DomRoot<DOMQuad> { + reflect_dom_object( + Box::new(DOMQuad::new_inherited(p1, p2, p3, p4)), + global, + Wrap, + ) } - pub fn Constructor(global: &GlobalScope, - p1: &DOMPointInit, - p2: &DOMPointInit, - p3: &DOMPointInit, - p4: &DOMPointInit) - -> Fallible<DomRoot<DOMQuad>> { - Ok(DOMQuad::new(global, - &*DOMPoint::new_from_init(global, p1), - &*DOMPoint::new_from_init(global, p2), - &*DOMPoint::new_from_init(global, p3), - &*DOMPoint::new_from_init(global, p4))) + pub fn Constructor( + global: &GlobalScope, + p1: &DOMPointInit, + p2: &DOMPointInit, + p3: &DOMPointInit, + p4: &DOMPointInit, + ) -> Fallible<DomRoot<DOMQuad>> { + Ok(DOMQuad::new( + global, + &*DOMPoint::new_from_init(global, p1), + &*DOMPoint::new_from_init(global, p2), + &*DOMPoint::new_from_init(global, p3), + &*DOMPoint::new_from_init(global, p4), + )) } // https://drafts.fxtf.org/geometry/#dom-domquad-fromrect pub fn FromRect(global: &GlobalScope, other: &DOMRectInit) -> DomRoot<DOMQuad> { - DOMQuad::new(global, - &*DOMPoint::new(global, other.x, other.y, 0f64, 1f64), - &*DOMPoint::new(global, other.x + other.width, other.y, 0f64, 1f64), - &*DOMPoint::new(global, other.x + other.width, other.y + other.height, 0f64, 1f64), - &*DOMPoint::new(global, other.x, other.y + other.height, 0f64, 1f64)) + DOMQuad::new( + global, + &*DOMPoint::new(global, other.x, other.y, 0f64, 1f64), + &*DOMPoint::new(global, other.x + other.width, other.y, 0f64, 1f64), + &*DOMPoint::new( + global, + other.x + other.width, + other.y + other.height, + 0f64, + 1f64, + ), + &*DOMPoint::new(global, other.x, other.y + other.height, 0f64, 1f64), + ) } // https://drafts.fxtf.org/geometry/#dom-domquad-fromquad pub fn FromQuad(global: &GlobalScope, other: &DOMQuadInit) -> DomRoot<DOMQuad> { - DOMQuad::new(global, - &DOMPoint::new_from_init(global, &other.p1), - &DOMPoint::new_from_init(global, &other.p2), - &DOMPoint::new_from_init(global, &other.p3), - &DOMPoint::new_from_init(global, &other.p4)) + DOMQuad::new( + global, + &DOMPoint::new_from_init(global, &other.p1), + &DOMPoint::new_from_init(global, &other.p2), + &DOMPoint::new_from_init(global, &other.p3), + &DOMPoint::new_from_init(global, &other.p4), + ) } } @@ -103,15 +116,31 @@ impl DOMQuadMethods for DOMQuad { // https://drafts.fxtf.org/geometry/#dom-domquad-getbounds fn GetBounds(&self) -> DomRoot<DOMRect> { - let left = self.p1.X().min(self.p2.X()).min(self.p3.X()).min(self.p4.X()); - let top = self.p1.Y().min(self.p2.Y()).min(self.p3.Y()).min(self.p4.Y()); - let right = self.p1.X().max(self.p2.X()).max(self.p3.X()).max(self.p4.X()); - let bottom = self.p1.Y().max(self.p2.Y()).max(self.p3.Y()).max(self.p4.Y()); + let left = self + .p1 + .X() + .min(self.p2.X()) + .min(self.p3.X()) + .min(self.p4.X()); + let top = self + .p1 + .Y() + .min(self.p2.Y()) + .min(self.p3.Y()) + .min(self.p4.Y()); + let right = self + .p1 + .X() + .max(self.p2.X()) + .max(self.p3.X()) + .max(self.p4.X()); + let bottom = self + .p1 + .Y() + .max(self.p2.Y()) + .max(self.p3.Y()) + .max(self.p4.Y()); - DOMRect::new(&self.global(), - left, - top, - right - left, - bottom - top) + DOMRect::new(&self.global(), left, top, right - left, bottom - top) } } diff --git a/components/script/dom/domrect.rs b/components/script/dom/domrect.rs index 8944b0d28df..cb5b3caadb9 100644 --- a/components/script/dom/domrect.rs +++ b/components/script/dom/domrect.rs @@ -25,17 +25,20 @@ impl DOMRect { } pub fn new(global: &GlobalScope, x: f64, y: f64, width: f64, height: f64) -> DomRoot<DOMRect> { - reflect_dom_object(Box::new(DOMRect::new_inherited(x, y, width, height)), - global, - DOMRectBinding::Wrap) + reflect_dom_object( + Box::new(DOMRect::new_inherited(x, y, width, height)), + global, + DOMRectBinding::Wrap, + ) } - pub fn Constructor(global: &GlobalScope, - x: f64, - y: f64, - width: f64, - height: f64) - -> Fallible<DomRoot<DOMRect>> { + pub fn Constructor( + global: &GlobalScope, + x: f64, + y: f64, + width: f64, + height: f64, + ) -> Fallible<DomRoot<DOMRect>> { Ok(DOMRect::new(global, x, y, width, height)) } } diff --git a/components/script/dom/domrectreadonly.rs b/components/script/dom/domrectreadonly.rs index f5e92812080..86eeab0b2fd 100644 --- a/components/script/dom/domrectreadonly.rs +++ b/components/script/dom/domrectreadonly.rs @@ -30,23 +30,27 @@ impl DOMRectReadOnly { } } - pub fn new(global: &GlobalScope, - x: f64, - y: f64, - width: f64, - height: f64) - -> DomRoot<DOMRectReadOnly> { - reflect_dom_object(Box::new(DOMRectReadOnly::new_inherited(x, y, width, height)), - global, - Wrap) + pub fn new( + global: &GlobalScope, + x: f64, + y: f64, + width: f64, + height: f64, + ) -> DomRoot<DOMRectReadOnly> { + reflect_dom_object( + Box::new(DOMRectReadOnly::new_inherited(x, y, width, height)), + global, + Wrap, + ) } - pub fn Constructor(global: &GlobalScope, - x: f64, - y: f64, - width: f64, - height: f64) - -> Fallible<DomRoot<DOMRectReadOnly>> { + pub fn Constructor( + global: &GlobalScope, + x: f64, + y: f64, + width: f64, + height: f64, + ) -> Fallible<DomRoot<DOMRectReadOnly>> { Ok(DOMRectReadOnly::new(global, x, y, width, height)) } diff --git a/components/script/dom/domstringmap.rs b/components/script/dom/domstringmap.rs index c64375e0bdb..514781c9a1d 100644 --- a/components/script/dom/domstringmap.rs +++ b/components/script/dom/domstringmap.rs @@ -28,9 +28,11 @@ impl DOMStringMap { pub fn new(element: &HTMLElement) -> DomRoot<DOMStringMap> { let window = window_from_node(element); - reflect_dom_object(Box::new(DOMStringMap::new_inherited(element)), - &*window, - DOMStringMapBinding::Wrap) + reflect_dom_object( + Box::new(DOMStringMap::new_inherited(element)), + &*window, + DOMStringMapBinding::Wrap, + ) } } @@ -53,6 +55,10 @@ impl DOMStringMapMethods for DOMStringMap { // https://html.spec.whatwg.org/multipage/#the-domstringmap-interface:supported-property-names fn SupportedPropertyNames(&self) -> Vec<DOMString> { - self.element.supported_prop_names_custom_attr().iter().cloned().collect() + self.element + .supported_prop_names_custom_attr() + .iter() + .cloned() + .collect() } } diff --git a/components/script/dom/domtokenlist.rs b/components/script/dom/domtokenlist.rs index 18999f59f13..f1244ab4936 100644 --- a/components/script/dom/domtokenlist.rs +++ b/components/script/dom/domtokenlist.rs @@ -34,9 +34,11 @@ impl DOMTokenList { pub fn new(element: &Element, local_name: &LocalName) -> DomRoot<DOMTokenList> { let window = window_from_node(element); - reflect_dom_object(Box::new(DOMTokenList::new_inherited(element, local_name.clone())), - &*window, - DOMTokenListBinding::Wrap) + reflect_dom_object( + Box::new(DOMTokenList::new_inherited(element, local_name.clone())), + &*window, + DOMTokenListBinding::Wrap, + ) } fn attribute(&self) -> Option<DomRoot<Attr>> { @@ -56,16 +58,18 @@ impl DOMTokenList { impl DOMTokenListMethods for DOMTokenList { // https://dom.spec.whatwg.org/#dom-domtokenlist-length fn Length(&self) -> u32 { - self.attribute().map_or(0, |attr| { - attr.value().as_tokens().len() - }) as u32 + self.attribute() + .map_or(0, |attr| attr.value().as_tokens().len()) as u32 } // https://dom.spec.whatwg.org/#dom-domtokenlist-item fn Item(&self, index: u32) -> Option<DOMString> { self.attribute().and_then(|attr| { // FIXME(ajeffrey): Convert directly from Atom to DOMString - attr.value().as_tokens().get(index as usize).map(|token| DOMString::from(&**token)) + attr.value() + .as_tokens() + .get(index as usize) + .map(|token| DOMString::from(&**token)) }) } @@ -89,7 +93,8 @@ impl DOMTokenListMethods for DOMTokenList { atoms.push(token); } } - self.element.set_atomic_tokenlist_attribute(&self.local_name, atoms); + self.element + .set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(()) } @@ -98,9 +103,13 @@ impl DOMTokenListMethods for DOMTokenList { let mut atoms = self.element.get_tokenlist_attribute(&self.local_name); for token in &tokens { let token = self.check_token_exceptions(&token)?; - atoms.iter().position(|atom| *atom == token).map(|index| atoms.remove(index)); + atoms + .iter() + .position(|atom| *atom == token) + .map(|index| atoms.remove(index)); } - self.element.set_atomic_tokenlist_attribute(&self.local_name, atoms); + self.element + .set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(()) } @@ -113,17 +122,19 @@ impl DOMTokenListMethods for DOMTokenList { Some(true) => Ok(true), _ => { atoms.remove(index); - self.element.set_atomic_tokenlist_attribute(&self.local_name, atoms); + self.element + .set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(false) - } + }, }, None => match force { Some(false) => Ok(false), _ => { atoms.push(token); - self.element.set_atomic_tokenlist_attribute(&self.local_name, atoms); + self.element + .set_atomic_tokenlist_attribute(&self.local_name, atoms); Ok(true) - } + }, }, } } @@ -135,7 +146,8 @@ impl DOMTokenListMethods for DOMTokenList { // https://dom.spec.whatwg.org/#dom-domtokenlist-value fn SetValue(&self, value: DOMString) { - self.element.set_tokenlist_attribute(&self.local_name, value); + self.element + .set_tokenlist_attribute(&self.local_name, value); } // https://dom.spec.whatwg.org/#dom-domtokenlist-replace @@ -159,7 +171,8 @@ impl DOMTokenListMethods for DOMTokenList { atoms.remove(pos); } // Step 5. - self.element.set_atomic_tokenlist_attribute(&self.local_name, atoms); + self.element + .set_atomic_tokenlist_attribute(&self.local_name, atoms); } Ok(()) } diff --git a/components/script/dom/element.rs b/components/script/dom/element.rs index 2101b1e6a7f..4144bb972ca 100644 --- a/components/script/dom/element.rs +++ b/components/script/dom/element.rs @@ -237,26 +237,38 @@ impl FromStr for AdjacentPosition { // Element methods // impl Element { - pub fn create(name: QualName, - is: Option<LocalName>, - document: &Document, - creator: ElementCreator, - mode: CustomElementCreationMode) - -> DomRoot<Element> { + pub fn create( + name: QualName, + is: Option<LocalName>, + document: &Document, + creator: ElementCreator, + mode: CustomElementCreationMode, + ) -> DomRoot<Element> { create_element(name, is, document, creator, mode) } - pub fn new_inherited(local_name: LocalName, - namespace: Namespace, prefix: Option<Prefix>, - document: &Document) -> Element { - Element::new_inherited_with_state(ElementState::empty(), local_name, - namespace, prefix, document) + pub fn new_inherited( + local_name: LocalName, + namespace: Namespace, + prefix: Option<Prefix>, + document: &Document, + ) -> Element { + Element::new_inherited_with_state( + ElementState::empty(), + local_name, + namespace, + prefix, + document, + ) } - pub fn new_inherited_with_state(state: ElementState, local_name: LocalName, - namespace: Namespace, prefix: Option<Prefix>, - document: &Document) - -> Element { + pub fn new_inherited_with_state( + state: ElementState, + local_name: LocalName, + namespace: Namespace, + prefix: Option<Prefix>, + document: &Document, + ) -> Element { Element { node: Node::new_inherited(document), local_name: local_name, @@ -277,14 +289,19 @@ impl Element { } } - pub fn new(local_name: LocalName, - namespace: Namespace, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<Element> { + pub fn new( + local_name: LocalName, + namespace: Namespace, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<Element> { Node::reflect_node( - Box::new(Element::new_inherited(local_name, namespace, prefix, document)), + Box::new(Element::new_inherited( + local_name, namespace, prefix, document, + )), document, - ElementBinding::Wrap) + ElementBinding::Wrap, + ) } pub fn restyle(&self, damage: NodeDamage) { @@ -325,11 +342,15 @@ impl Element { } pub fn push_callback_reaction(&self, function: Rc<Function>, args: Box<[Heap<JSVal>]>) { - self.custom_element_reaction_queue.borrow_mut().push(CustomElementReaction::Callback(function, args)); + self.custom_element_reaction_queue + .borrow_mut() + .push(CustomElementReaction::Callback(function, args)); } pub fn push_upgrade_reaction(&self, definition: Rc<CustomElementDefinition>) { - self.custom_element_reaction_queue.borrow_mut().push(CustomElementReaction::Upgrade(definition)); + self.custom_element_reaction_queue + .borrow_mut() + .push(CustomElementReaction::Upgrade(definition)); } pub fn clear_reaction_queue(&self) { @@ -341,7 +362,10 @@ impl Element { // after clear_reaction_queue has been called. rooted_vec!(let mut reactions); while !self.custom_element_reaction_queue.borrow().is_empty() { - mem::swap(&mut *reactions, &mut *self.custom_element_reaction_queue.borrow_mut()); + mem::swap( + &mut *reactions, + &mut *self.custom_element_reaction_queue.borrow_mut(), + ); for reaction in reactions.iter() { reaction.invoke(self); } @@ -352,9 +376,7 @@ impl Element { /// style will be `None` for elements in a `display: none` subtree. otherwise, the element has a /// layout box iff it doesn't have `display: none`. pub fn style(&self) -> Option<Arc<ComputedValues>> { - window_from_node(self).style_query( - self.upcast::<Node>().to_trusted_node_address() - ) + window_from_node(self).style_query(self.upcast::<Node>().to_trusted_node_address()) } // https://drafts.csswg.org/cssom-view/#css-layout-box @@ -376,8 +398,7 @@ impl Element { } fn has_overflow(&self) -> bool { - self.ScrollHeight() > self.ClientHeight() || - self.ScrollWidth() > self.ClientWidth() + self.ScrollHeight() > self.ClientHeight() || self.ScrollWidth() > self.ClientWidth() } // TODO: Once #19183 is closed (overflow-x/y types moved out of mako), then we could implement @@ -408,55 +429,69 @@ impl Element { #[allow(unsafe_code)] pub trait RawLayoutElementHelpers { - unsafe fn get_attr_for_layout<'a>(&'a self, namespace: &Namespace, name: &LocalName) - -> Option<&'a AttrValue>; - unsafe fn get_attr_val_for_layout<'a>(&'a self, namespace: &Namespace, name: &LocalName) - -> Option<&'a str>; + unsafe fn get_attr_for_layout<'a>( + &'a self, + namespace: &Namespace, + name: &LocalName, + ) -> Option<&'a AttrValue>; + unsafe fn get_attr_val_for_layout<'a>( + &'a self, + namespace: &Namespace, + name: &LocalName, + ) -> Option<&'a str>; unsafe fn get_attr_vals_for_layout<'a>(&'a self, name: &LocalName) -> Vec<&'a AttrValue>; } #[inline] #[allow(unsafe_code)] -pub unsafe fn get_attr_for_layout<'a>(elem: &'a Element, namespace: &Namespace, name: &LocalName) - -> Option<LayoutDom<Attr>> { +pub unsafe fn get_attr_for_layout<'a>( + elem: &'a Element, + namespace: &Namespace, + name: &LocalName, +) -> Option<LayoutDom<Attr>> { // cast to point to T in RefCell<T> directly let attrs = elem.attrs.borrow_for_layout(); - attrs.iter().find(|attr| { - let attr = attr.to_layout(); - *name == attr.local_name_atom_forever() && - (*attr.unsafe_get()).namespace() == namespace - }).map(|attr| attr.to_layout()) + attrs + .iter() + .find(|attr| { + let attr = attr.to_layout(); + *name == attr.local_name_atom_forever() && (*attr.unsafe_get()).namespace() == namespace + }).map(|attr| attr.to_layout()) } #[allow(unsafe_code)] impl RawLayoutElementHelpers for Element { #[inline] - unsafe fn get_attr_for_layout<'a>(&'a self, namespace: &Namespace, name: &LocalName) - -> Option<&'a AttrValue> { - get_attr_for_layout(self, namespace, name).map(|attr| { - attr.value_forever() - }) + unsafe fn get_attr_for_layout<'a>( + &'a self, + namespace: &Namespace, + name: &LocalName, + ) -> Option<&'a AttrValue> { + get_attr_for_layout(self, namespace, name).map(|attr| attr.value_forever()) } #[inline] - unsafe fn get_attr_val_for_layout<'a>(&'a self, namespace: &Namespace, name: &LocalName) - -> Option<&'a str> { - get_attr_for_layout(self, namespace, name).map(|attr| { - attr.value_ref_forever() - }) + unsafe fn get_attr_val_for_layout<'a>( + &'a self, + namespace: &Namespace, + name: &LocalName, + ) -> Option<&'a str> { + get_attr_for_layout(self, namespace, name).map(|attr| attr.value_ref_forever()) } #[inline] unsafe fn get_attr_vals_for_layout<'a>(&'a self, name: &LocalName) -> Vec<&'a AttrValue> { let attrs = self.attrs.borrow_for_layout(); - attrs.iter().filter_map(|attr| { - let attr = attr.to_layout(); - if *name == attr.local_name_atom_forever() { - Some(attr.value_forever()) - } else { - None - } - }).collect() + attrs + .iter() + .filter_map(|attr| { + let attr = attr.to_layout(); + if *name == attr.local_name_atom_forever() { + Some(attr.value_forever()) + } else { + None + } + }).collect() } } @@ -468,7 +503,8 @@ pub trait LayoutElementHelpers { #[allow(unsafe_code)] unsafe fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, &mut V) - where V: Push<ApplicableDeclarationBlock>; + where + V: Push<ApplicableDeclarationBlock>; #[allow(unsafe_code)] unsafe fn get_colspan(self) -> u32; #[allow(unsafe_code)] @@ -491,9 +527,15 @@ impl LayoutElementHelpers for LayoutDom<Element> { #[allow(unsafe_code)] #[inline] unsafe fn has_class_for_layout(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool { - get_attr_for_layout(&*self.unsafe_get(), &ns!(), &local_name!("class")).map_or(false, |attr| { - attr.value_tokens_forever().unwrap().iter().any(|atom| case_sensitivity.eq_atom(atom, name)) - }) + get_attr_for_layout(&*self.unsafe_get(), &ns!(), &local_name!("class")).map_or( + false, + |attr| { + attr.value_tokens_forever() + .unwrap() + .iter() + .any(|atom| case_sensitivity.eq_atom(atom, name)) + }, + ) } #[allow(unsafe_code)] @@ -505,17 +547,22 @@ impl LayoutElementHelpers for LayoutDom<Element> { #[allow(unsafe_code)] unsafe fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, hints: &mut V) - where V: Push<ApplicableDeclarationBlock> + where + V: Push<ApplicableDeclarationBlock>, { // FIXME(emilio): Just a single PDB should be enough. #[inline] - fn from_declaration(shared_lock: &SharedRwLock, declaration: PropertyDeclaration) - -> ApplicableDeclarationBlock { + fn from_declaration( + shared_lock: &SharedRwLock, + declaration: PropertyDeclaration, + ) -> ApplicableDeclarationBlock { ApplicableDeclarationBlock::from_declarations( Arc::new(shared_lock.wrap(PropertyDeclarationBlock::with_one( - declaration, Importance::Normal + declaration, + Importance::Normal, ))), - CascadeLevel::PresHints) + CascadeLevel::PresHints, + ) } let document = self.upcast::<Node>().owner_doc_for_layout(); @@ -538,7 +585,7 @@ impl LayoutElementHelpers for LayoutDom<Element> { if let Some(color) = bgcolor { hints.push(from_declaration( shared_lock, - PropertyDeclaration::BackgroundColor(color.into()) + PropertyDeclaration::BackgroundColor(color.into()), )); } @@ -551,10 +598,10 @@ impl LayoutElementHelpers for LayoutDom<Element> { if let Some(url) = background { hints.push(from_declaration( shared_lock, - PropertyDeclaration::BackgroundImage( - background_image::SpecifiedValue(vec![ - Either::Second(specified::Image::for_cascade(url.into())) - ])))); + PropertyDeclaration::BackgroundImage(background_image::SpecifiedValue(vec![ + Either::Second(specified::Image::for_cascade(url.into())), + ])), + )); } let color = if let Some(this) = self.downcast::<HTMLFontElement>() { @@ -572,9 +619,7 @@ impl LayoutElementHelpers for LayoutDom<Element> { if let Some(color) = color { hints.push(from_declaration( shared_lock, - PropertyDeclaration::Color( - longhands::color::SpecifiedValue(color.into()) - ) + PropertyDeclaration::Color(longhands::color::SpecifiedValue(color.into())), )); } @@ -587,21 +632,24 @@ impl LayoutElementHelpers for LayoutDom<Element> { if let Some(font_family) = font_family { hints.push(from_declaration( shared_lock, - PropertyDeclaration::FontFamily( - font_family::SpecifiedValue::Values( - computed::font::FontFamilyList::new(Box::new([ - computed::font::SingleFontFamily::from_atom( - font_family)])))))); + PropertyDeclaration::FontFamily(font_family::SpecifiedValue::Values( + computed::font::FontFamilyList::new(Box::new([ + computed::font::SingleFontFamily::from_atom(font_family), + ])), + )), + )); } - let font_size = self.downcast::<HTMLFontElement>().and_then(|this| this.get_size()); + let font_size = self + .downcast::<HTMLFontElement>() + .and_then(|this| this.get_size()); if let Some(font_size) = font_size { hints.push(from_declaration( shared_lock, - PropertyDeclaration::FontSize( - font_size::SpecifiedValue::from_html_size(font_size as u8) - ) + PropertyDeclaration::FontSize(font_size::SpecifiedValue::from_html_size( + font_size as u8, + )), )) } @@ -615,32 +663,37 @@ impl LayoutElementHelpers for LayoutDom<Element> { let width_value = specified::Length::from_px(cellspacing as f32); hints.push(from_declaration( shared_lock, - PropertyDeclaration::BorderSpacing( - Box::new(border_spacing::SpecifiedValue::new( - width_value.clone().into(), - width_value.into() - )) - ) + PropertyDeclaration::BorderSpacing(Box::new(border_spacing::SpecifiedValue::new( + width_value.clone().into(), + width_value.into(), + ))), )); } - let size = if let Some(this) = self.downcast::<HTMLInputElement>() { // FIXME(pcwalton): More use of atoms, please! match (*self.unsafe_get()).get_attr_val_for_layout(&ns!(), &local_name!("type")) { // Not text entry widget - Some("hidden") | Some("date") | Some("month") | Some("week") | - Some("time") | Some("datetime-local") | Some("number") | Some("range") | - Some("color") | Some("checkbox") | Some("radio") | Some("file") | - Some("submit") | Some("image") | Some("reset") | Some("button") => { - None - }, + Some("hidden") | + Some("date") | + Some("month") | + Some("week") | + Some("time") | + Some("datetime-local") | + Some("number") | + Some("range") | + Some("color") | + Some("checkbox") | + Some("radio") | + Some("file") | + Some("submit") | + Some("image") | + Some("reset") | + Some("button") => None, // Others - _ => { - match this.size_for_layout() { - 0 => None, - s => Some(s as i32), - } + _ => match this.size_for_layout() { + 0 => None, + s => Some(s as i32), }, } } else { @@ -648,11 +701,12 @@ impl LayoutElementHelpers for LayoutDom<Element> { }; if let Some(size) = size { - let value = specified::NoCalcLength::ServoCharacterWidth(specified::CharacterWidth(size)); + let value = + specified::NoCalcLength::ServoCharacterWidth(specified::CharacterWidth(size)); hints.push(from_declaration( shared_lock, - PropertyDeclaration::Width( - specified::LengthOrPercentageOrAuto::Length(value)))); + PropertyDeclaration::Width(specified::LengthOrPercentageOrAuto::Length(value)), + )); } let width = if let Some(this) = self.downcast::<HTMLIFrameElement>() { @@ -674,24 +728,28 @@ impl LayoutElementHelpers for LayoutDom<Element> { // FIXME(emilio): Use from_computed value here and below. match width { - LengthOrPercentageOrAuto::Auto => {} + LengthOrPercentageOrAuto::Auto => {}, LengthOrPercentageOrAuto::Percentage(percentage) => { - let width_value = - specified::LengthOrPercentageOrAuto::Percentage(computed::Percentage(percentage)); + let width_value = specified::LengthOrPercentageOrAuto::Percentage( + computed::Percentage(percentage), + ); hints.push(from_declaration( shared_lock, - PropertyDeclaration::Width(width_value))); - } + PropertyDeclaration::Width(width_value), + )); + }, LengthOrPercentageOrAuto::Length(length) => { - let width_value = specified::LengthOrPercentageOrAuto::Length( - specified::NoCalcLength::Absolute(specified::AbsoluteLength::Px(length.to_f32_px()))); + let width_value = + specified::LengthOrPercentageOrAuto::Length(specified::NoCalcLength::Absolute( + specified::AbsoluteLength::Px(length.to_f32_px()), + )); hints.push(from_declaration( shared_lock, - PropertyDeclaration::Width(width_value))); - } + PropertyDeclaration::Width(width_value), + )); + }, } - let height = if let Some(this) = self.downcast::<HTMLIFrameElement>() { this.get_height() } else if let Some(this) = self.downcast::<HTMLImageElement>() { @@ -703,24 +761,28 @@ impl LayoutElementHelpers for LayoutDom<Element> { }; match height { - LengthOrPercentageOrAuto::Auto => {} + LengthOrPercentageOrAuto::Auto => {}, LengthOrPercentageOrAuto::Percentage(percentage) => { - let height_value = - specified::LengthOrPercentageOrAuto::Percentage(computed::Percentage(percentage)); + let height_value = specified::LengthOrPercentageOrAuto::Percentage( + computed::Percentage(percentage), + ); hints.push(from_declaration( shared_lock, - PropertyDeclaration::Height(height_value))); - } + PropertyDeclaration::Height(height_value), + )); + }, LengthOrPercentageOrAuto::Length(length) => { - let height_value = specified::LengthOrPercentageOrAuto::Length( - specified::NoCalcLength::Absolute(specified::AbsoluteLength::Px(length.to_f32_px()))); + let height_value = + specified::LengthOrPercentageOrAuto::Length(specified::NoCalcLength::Absolute( + specified::AbsoluteLength::Px(length.to_f32_px()), + )); hints.push(from_declaration( shared_lock, - PropertyDeclaration::Height(height_value))); - } + PropertyDeclaration::Height(height_value), + )); + }, } - let cols = if let Some(this) = self.downcast::<HTMLTextAreaElement>() { match this.get_cols() { 0 => None, @@ -736,10 +798,12 @@ impl LayoutElementHelpers for LayoutDom<Element> { // scrollbar size into consideration (but we don't have a scrollbar yet!) // // https://html.spec.whatwg.org/multipage/#textarea-effective-width - let value = specified::NoCalcLength::ServoCharacterWidth(specified::CharacterWidth(cols)); + let value = + specified::NoCalcLength::ServoCharacterWidth(specified::CharacterWidth(cols)); hints.push(from_declaration( shared_lock, - PropertyDeclaration::Width(specified::LengthOrPercentageOrAuto::Length(value)))); + PropertyDeclaration::Width(specified::LengthOrPercentageOrAuto::Length(value)), + )); } let rows = if let Some(this) = self.downcast::<HTMLTextAreaElement>() { @@ -755,13 +819,15 @@ impl LayoutElementHelpers for LayoutDom<Element> { // TODO(mttr) This should take scrollbar size into consideration. // // https://html.spec.whatwg.org/multipage/#textarea-effective-height - let value = specified::NoCalcLength::FontRelative(specified::FontRelativeLength::Em(rows as CSSFloat)); + let value = specified::NoCalcLength::FontRelative(specified::FontRelativeLength::Em( + rows as CSSFloat, + )); hints.push(from_declaration( shared_lock, - PropertyDeclaration::Height(specified::LengthOrPercentageOrAuto::Length(value)))); + PropertyDeclaration::Height(specified::LengthOrPercentageOrAuto::Length(value)), + )); } - let border = if let Some(this) = self.downcast::<HTMLTableElement>() { this.get_border() } else { @@ -769,19 +835,24 @@ impl LayoutElementHelpers for LayoutDom<Element> { }; if let Some(border) = border { - let width_value = specified::BorderSideWidth::Length(specified::Length::from_px(border as f32)); + let width_value = + specified::BorderSideWidth::Length(specified::Length::from_px(border as f32)); hints.push(from_declaration( shared_lock, - PropertyDeclaration::BorderTopWidth(width_value.clone()))); + PropertyDeclaration::BorderTopWidth(width_value.clone()), + )); hints.push(from_declaration( shared_lock, - PropertyDeclaration::BorderLeftWidth(width_value.clone()))); + PropertyDeclaration::BorderLeftWidth(width_value.clone()), + )); hints.push(from_declaration( shared_lock, - PropertyDeclaration::BorderBottomWidth(width_value.clone()))); + PropertyDeclaration::BorderBottomWidth(width_value.clone()), + )); hints.push(from_declaration( shared_lock, - PropertyDeclaration::BorderRightWidth(width_value))); + PropertyDeclaration::BorderRightWidth(width_value), + )); } } @@ -815,30 +886,22 @@ impl LayoutElementHelpers for LayoutDom<Element> { #[allow(unsafe_code)] fn id_attribute(&self) -> *const Option<Atom> { - unsafe { - (*self.unsafe_get()).id_attribute.borrow_for_layout() - } + unsafe { (*self.unsafe_get()).id_attribute.borrow_for_layout() } } #[allow(unsafe_code)] fn style_attribute(&self) -> *const Option<Arc<Locked<PropertyDeclarationBlock>>> { - unsafe { - (*self.unsafe_get()).style_attribute.borrow_for_layout() - } + unsafe { (*self.unsafe_get()).style_attribute.borrow_for_layout() } } #[allow(unsafe_code)] fn local_name(&self) -> &LocalName { - unsafe { - &(*self.unsafe_get()).local_name - } + unsafe { &(*self.unsafe_get()).local_name } } #[allow(unsafe_code)] fn namespace(&self) -> &Namespace { - unsafe { - &(*self.unsafe_get()).namespace - } + unsafe { &(*self.unsafe_get()).namespace } } #[allow(unsafe_code)] @@ -849,14 +912,18 @@ impl LayoutElementHelpers for LayoutDom<Element> { current_node = node.parent_node_ref(); match node.downcast::<Element>().map(|el| el.unsafe_get()) { Some(elem) => { - if let Some(attr) = (*elem).get_attr_val_for_layout(&ns!(xml), &local_name!("lang")) { + if let Some(attr) = + (*elem).get_attr_val_for_layout(&ns!(xml), &local_name!("lang")) + { return attr.to_owned(); } - if let Some(attr) = (*elem).get_attr_val_for_layout(&ns!(), &local_name!("lang")) { + if let Some(attr) = + (*elem).get_attr_val_for_layout(&ns!(), &local_name!("lang")) + { return attr.to_owned(); } - } - None => continue + }, + None => continue, } } // TODO: Check meta tags for a pragma-set default language @@ -870,9 +937,7 @@ impl LayoutElementHelpers for LayoutDom<Element> { fn get_checked_state_for_layout(&self) -> bool { // TODO option and menuitem can also have a checked state. match self.downcast::<HTMLInputElement>() { - Some(input) => unsafe { - input.checked_state_for_layout() - }, + Some(input) => unsafe { input.checked_state_for_layout() }, None => false, } } @@ -882,9 +947,7 @@ impl LayoutElementHelpers for LayoutDom<Element> { fn get_indeterminate_state_for_layout(&self) -> bool { // TODO progress elements can also be matched with :indeterminate match self.downcast::<HTMLInputElement>() { - Some(input) => unsafe { - input.indeterminate_state_for_layout() - }, + Some(input) => unsafe { input.indeterminate_state_for_layout() }, None => false, } } @@ -892,9 +955,7 @@ impl LayoutElementHelpers for LayoutDom<Element> { #[inline] #[allow(unsafe_code)] fn get_state_for_layout(&self) -> ElementState { - unsafe { - (*self.unsafe_get()).state.get() - } + unsafe { (*self.unsafe_get()).state.get() } } #[inline] @@ -910,9 +971,7 @@ impl LayoutElementHelpers for LayoutDom<Element> { #[inline] #[allow(unsafe_code)] fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool { - unsafe { - (*self.unsafe_get()).selector_flags.get().contains(flags) - } + unsafe { (*self.unsafe_get()).selector_flags.get().contains(flags) } } } @@ -956,10 +1015,10 @@ impl Element { pub fn locate_namespace(&self, prefix: Option<DOMString>) -> Namespace { let prefix = prefix.map(String::from).map(LocalName::from); - let inclusive_ancestor_elements = - self.upcast::<Node>() - .inclusive_ancestors() - .filter_map(DomRoot::downcast::<Self>); + let inclusive_ancestor_elements = self + .upcast::<Node>() + .inclusive_ancestors() + .filter_map(DomRoot::downcast::<Self>); // Steps 3-4. for element in inclusive_ancestor_elements { @@ -999,39 +1058,53 @@ impl Element { } pub fn summarize(&self) -> Vec<AttrInfo> { - self.attrs.borrow().iter() - .map(|attr| attr.summarize()) - .collect() + self.attrs + .borrow() + .iter() + .map(|attr| attr.summarize()) + .collect() } pub fn is_void(&self) -> bool { if self.namespace != ns!(html) { - return false + return false; } match self.local_name { /* List of void elements from https://html.spec.whatwg.org/multipage/#html-fragment-serialisation-algorithm */ - - local_name!("area") | local_name!("base") | local_name!("basefont") | - local_name!("bgsound") | local_name!("br") | - local_name!("col") | local_name!("embed") | local_name!("frame") | - local_name!("hr") | local_name!("img") | - local_name!("input") | local_name!("keygen") | local_name!("link") | - local_name!("menuitem") | local_name!("meta") | - local_name!("param") | local_name!("source") | local_name!("track") | + local_name!("area") | + local_name!("base") | + local_name!("basefont") | + local_name!("bgsound") | + local_name!("br") | + local_name!("col") | + local_name!("embed") | + local_name!("frame") | + local_name!("hr") | + local_name!("img") | + local_name!("input") | + local_name!("keygen") | + local_name!("link") | + local_name!("menuitem") | + local_name!("meta") | + local_name!("param") | + local_name!("source") | + local_name!("track") | local_name!("wbr") => true, - _ => false + _ => false, } } pub fn serialize(&self, traversal_scope: TraversalScope) -> Fallible<DOMString> { let mut writer = vec![]; - match serialize(&mut writer, - &self.upcast::<Node>(), - SerializeOpts { - traversal_scope: traversal_scope, - ..Default::default() - }) { + match serialize( + &mut writer, + &self.upcast::<Node>(), + SerializeOpts { + traversal_scope: traversal_scope, + ..Default::default() + }, + ) { // FIXME(ajeffrey): Directly convert UTF8 to DOMString Ok(()) => Ok(DOMString::from(String::from_utf8(writer).unwrap())), Err(_) => panic!("Cannot serialize element"), @@ -1040,12 +1113,14 @@ impl Element { pub fn xmlSerialize(&self, traversal_scope: XmlTraversalScope) -> Fallible<DOMString> { let mut writer = vec![]; - match xmlSerialize::serialize(&mut writer, - &self.upcast::<Node>(), - XmlSerializeOpts { - traversal_scope: traversal_scope, - ..Default::default() - }) { + match xmlSerialize::serialize( + &mut writer, + &self.upcast::<Node>(), + XmlSerializeOpts { + traversal_scope: traversal_scope, + ..Default::default() + }, + ) { Ok(()) => Ok(DOMString::from(String::from_utf8(writer).unwrap())), Err(_) => panic!("Cannot serialize element"), } @@ -1080,7 +1155,8 @@ impl Element { // Step 2. for attr in element.attrs.borrow().iter() { if attr.prefix() == Some(&namespace_prefix!("xmlns")) && - **attr.value() == *namespace { + **attr.value() == *namespace + { return Some(attr.LocalName()); } } @@ -1115,12 +1191,18 @@ impl Element { } // https://html.spec.whatwg.org/multipage/#specially-focusable match node.type_id() { - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) | - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) | - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) | - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => { - true - } + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLAnchorElement, + )) | + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLInputElement, + )) | + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLSelectElement, + )) | + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLTextAreaElement, + )) => true, _ => false, } } @@ -1128,13 +1210,21 @@ impl Element { pub fn is_actually_disabled(&self) -> bool { let node = self.upcast::<Node>(); match node.type_id() { - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) | - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) | - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) | - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) | - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptionElement)) => { - self.disabled_state() - } + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLButtonElement, + )) | + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLInputElement, + )) | + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLSelectElement, + )) | + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLTextAreaElement, + )) | + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLOptionElement, + )) => self.disabled_state(), // TODO: // an optgroup element that has a disabled attribute // a menuitem element that has a disabled attribute @@ -1143,20 +1233,24 @@ impl Element { } } - pub fn push_new_attribute(&self, - local_name: LocalName, - value: AttrValue, - name: LocalName, - namespace: Namespace, - prefix: Option<Prefix>) { + pub fn push_new_attribute( + &self, + local_name: LocalName, + value: AttrValue, + name: LocalName, + namespace: Namespace, + prefix: Option<Prefix>, + ) { let window = window_from_node(self); - let attr = Attr::new(&window, - local_name, - value, - name, - namespace, - prefix, - Some(self)); + let attr = Attr::new( + &window, + local_name, + value, + name, + namespace, + prefix, + Some(self), + ); self.push_attribute(&attr); } @@ -1185,7 +1279,11 @@ impl Element { } } - pub fn get_attribute(&self, namespace: &Namespace, local_name: &LocalName) -> Option<DomRoot<Attr>> { + pub fn get_attribute( + &self, + namespace: &Namespace, + local_name: &LocalName, + ) -> Option<DomRoot<Attr>> { self.attrs .borrow() .iter() @@ -1196,18 +1294,26 @@ impl Element { // https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name pub fn get_attribute_by_name(&self, name: DOMString) -> Option<DomRoot<Attr>> { let name = &self.parsed_name(name); - self.attrs.borrow().iter().find(|a| a.name() == name).map(|js| DomRoot::from_ref(&**js)) + self.attrs + .borrow() + .iter() + .find(|a| a.name() == name) + .map(|js| DomRoot::from_ref(&**js)) } - pub fn set_attribute_from_parser(&self, - qname: QualName, - value: DOMString, - prefix: Option<Prefix>) { + pub fn set_attribute_from_parser( + &self, + qname: QualName, + value: DOMString, + prefix: Option<Prefix>, + ) { // Don't set if the attribute already exists, so we can handle add_attrs_if_missing - if self.attrs - .borrow() - .iter() - .any(|a| *a.local_name() == qname.local && *a.namespace() == qname.ns) { + if self + .attrs + .borrow() + .iter() + .any(|a| *a.local_name() == qname.local && *a.namespace() == qname.ns) + { return; } @@ -1226,12 +1332,9 @@ impl Element { assert!(name == &name.to_ascii_lowercase()); assert!(!name.contains(":")); - self.set_first_matching_attribute(name.clone(), - value, - name.clone(), - ns!(), - None, - |attr| attr.local_name() == name); + self.set_first_matching_attribute(name.clone(), value, name.clone(), ns!(), None, |attr| { + attr.local_name() == name + }); } // https://html.spec.whatwg.org/multipage/#attr-data-* @@ -1244,31 +1347,29 @@ impl Element { // Steps 2-5. let name = LocalName::from(name); let value = self.parse_attribute(&ns!(), &name, value); - self.set_first_matching_attribute(name.clone(), - value, - name.clone(), - ns!(), - None, - |attr| { - *attr.name() == name && *attr.namespace() == ns!() - }); + self.set_first_matching_attribute(name.clone(), value, name.clone(), ns!(), None, |attr| { + *attr.name() == name && *attr.namespace() == ns!() + }); Ok(()) } - fn set_first_matching_attribute<F>(&self, - local_name: LocalName, - value: AttrValue, - name: LocalName, - namespace: Namespace, - prefix: Option<Prefix>, - find: F) - where F: Fn(&Attr) -> bool + fn set_first_matching_attribute<F>( + &self, + local_name: LocalName, + value: AttrValue, + name: LocalName, + namespace: Namespace, + prefix: Option<Prefix>, + find: F, + ) where + F: Fn(&Attr) -> bool, { - let attr = self.attrs - .borrow() - .iter() - .find(|attr| find(&attr)) - .map(|js| DomRoot::from_ref(&**js)); + let attr = self + .attrs + .borrow() + .iter() + .find(|attr| find(&attr)) + .map(|js| DomRoot::from_ref(&**js)); if let Some(attr) = attr { attr.set_value(value, self); } else { @@ -1276,11 +1377,12 @@ impl Element { }; } - pub fn parse_attribute(&self, - namespace: &Namespace, - local_name: &LocalName, - value: DOMString) - -> AttrValue { + pub fn parse_attribute( + &self, + namespace: &Namespace, + local_name: &LocalName, + value: DOMString, + ) -> AttrValue { if *namespace == ns!() { vtable_for(self.upcast()).parse_plain_attribute(local_name, value) } else { @@ -1288,7 +1390,11 @@ impl Element { } } - pub fn remove_attribute(&self, namespace: &Namespace, local_name: &LocalName) -> Option<DomRoot<Attr>> { + pub fn remove_attribute( + &self, + namespace: &Namespace, + local_name: &LocalName, + ) -> Option<DomRoot<Attr>> { self.remove_first_matching_attribute(|attr| { attr.namespace() == namespace && attr.local_name() == local_name }) @@ -1299,7 +1405,9 @@ impl Element { } fn remove_first_matching_attribute<F>(&self, find: F) -> Option<DomRoot<Attr>> - where F: Fn(&Attr) -> bool { + where + F: Fn(&Attr) -> bool, + { let idx = self.attrs.borrow().iter().position(|attr| find(&attr)); idx.map(|idx| { let attr = DomRoot::from_ref(&*(*self.attrs.borrow())[idx]); @@ -1316,7 +1424,8 @@ impl Element { MutationObserver::queue_a_mutation_record(&self.node, mutation); - let reaction = CallbackReaction::AttributeChanged(name, Some(old_value), None, namespace); + let reaction = + CallbackReaction::AttributeChanged(name, Some(old_value), None, namespace); ScriptThread::enqueue_callback_reaction(self, reaction, None); self.attrs.borrow_mut().remove(idx); @@ -1329,9 +1438,13 @@ impl Element { } pub fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool { - self.get_attribute(&ns!(), &local_name!("class")).map_or(false, |attr| { - attr.value().as_tokens().iter().any(|atom| case_sensitivity.eq_atom(name, atom)) - }) + self.get_attribute(&ns!(), &local_name!("class")) + .map_or(false, |attr| { + attr.value() + .as_tokens() + .iter() + .any(|atom| case_sensitivity.eq_atom(name, atom)) + }) } pub fn set_atomic_attribute(&self, local_name: &LocalName, value: DOMString) { @@ -1368,7 +1481,8 @@ impl Element { let value = &**attr.value(); // XXXManishearth this doesn't handle `javascript:` urls properly let base = document_from_node(self).base_url(); - let value = base.join(value) + let value = base + .join(value) .map(|parsed| parsed.into_string()) .unwrap_or_else(|_| value.to_owned()); DOMString::from(value) @@ -1387,17 +1501,17 @@ impl Element { } pub fn get_tokenlist_attribute(&self, local_name: &LocalName) -> Vec<Atom> { - self.get_attribute(&ns!(), local_name).map(|attr| { - attr.value() - .as_tokens() - .to_vec() - }).unwrap_or(vec!()) + self.get_attribute(&ns!(), local_name) + .map(|attr| attr.value().as_tokens().to_vec()) + .unwrap_or(vec![]) } pub fn set_tokenlist_attribute(&self, local_name: &LocalName, value: DOMString) { assert!(*local_name == local_name.to_ascii_lowercase()); - self.set_attribute(local_name, - AttrValue::from_serialized_tokenlist(value.into())); + self.set_attribute( + local_name, + AttrValue::from_serialized_tokenlist(value.into()), + ); } pub fn set_atomic_tokenlist_attribute(&self, local_name: &LocalName, tokens: Vec<Atom>) { @@ -1407,19 +1521,21 @@ impl Element { pub fn get_int_attribute(&self, local_name: &LocalName, default: i32) -> i32 { // TODO: Is this assert necessary? - assert!(local_name.chars().all(|ch| { - !ch.is_ascii() || ch.to_ascii_lowercase() == ch - })); + assert!( + local_name + .chars() + .all(|ch| !ch.is_ascii() || ch.to_ascii_lowercase() == ch) + ); let attribute = self.get_attribute(&ns!(), local_name); match attribute { - Some(ref attribute) => { - match *attribute.value() { - AttrValue::Int(_, value) => value, - _ => panic!("Expected an AttrValue::Int: \ - implement parse_plain_attribute"), - } - } + Some(ref attribute) => match *attribute.value() { + AttrValue::Int(_, value) => value, + _ => panic!( + "Expected an AttrValue::Int: \ + implement parse_plain_attribute" + ), + }, None => default, } } @@ -1430,15 +1546,17 @@ impl Element { } pub fn get_uint_attribute(&self, local_name: &LocalName, default: u32) -> u32 { - assert!(local_name.chars().all(|ch| !ch.is_ascii() || ch.to_ascii_lowercase() == ch)); + assert!( + local_name + .chars() + .all(|ch| !ch.is_ascii() || ch.to_ascii_lowercase() == ch) + ); let attribute = self.get_attribute(&ns!(), local_name); match attribute { - Some(ref attribute) => { - match *attribute.value() { - AttrValue::UInt(_, value) => value, - _ => panic!("Expected an AttrValue::UInt: implement parse_plain_attribute"), - } - } + Some(ref attribute) => match *attribute.value() { + AttrValue::UInt(_, value) => value, + _ => panic!("Expected an AttrValue::UInt: implement parse_plain_attribute"), + }, None => default, } } @@ -1453,8 +1571,11 @@ impl Element { } // https://dom.spec.whatwg.org/#insert-adjacent - pub fn insert_adjacent(&self, where_: AdjacentPosition, node: &Node) - -> Fallible<Option<DomRoot<Node>>> { + pub fn insert_adjacent( + &self, + where_: AdjacentPosition, + node: &Node, + ) -> Fallible<Option<DomRoot<Node>>> { let self_node = self.upcast::<Node>(); match where_ { AdjacentPosition::BeforeBegin => { @@ -1463,20 +1584,18 @@ impl Element { } else { Ok(None) } - } + }, AdjacentPosition::AfterBegin => { Node::pre_insert(node, &self_node, self_node.GetFirstChild().r()).map(Some) - } - AdjacentPosition::BeforeEnd => { - Node::pre_insert(node, &self_node, None).map(Some) - } + }, + AdjacentPosition::BeforeEnd => Node::pre_insert(node, &self_node, None).map(Some), AdjacentPosition::AfterEnd => { if let Some(parent) = self_node.GetParentNode() { Node::pre_insert(node, &parent, self_node.GetNextSibling().r()).map(Some) } else { Ok(None) } - } + }, } } @@ -1513,17 +1632,15 @@ impl Element { // Step 9 if doc.GetBody().r() == self.downcast::<HTMLElement>() && - doc.quirks_mode() == QuirksMode::Quirks && - !self.potentially_scrollable() { - win.scroll(x, y, behavior); - return; + doc.quirks_mode() == QuirksMode::Quirks && + !self.potentially_scrollable() + { + win.scroll(x, y, behavior); + return; } // Step 10 - if !self.has_css_layout_box() || - !self.has_scrolling_box() || - !self.has_overflow() - { + if !self.has_css_layout_box() || !self.has_scrolling_box() || !self.has_overflow() { return; } @@ -1549,19 +1666,20 @@ impl Element { pub fn fragment_parsing_context(owner_doc: &Document, element: Option<&Self>) -> DomRoot<Self> { match element { - Some(elem) if elem.local_name() != &local_name!("html") || !elem.html_element_in_html_document() => { + Some(elem) + if elem.local_name() != &local_name!("html") || + !elem.html_element_in_html_document() => + { DomRoot::from_ref(elem) }, - _ => { - DomRoot::upcast(HTMLBodyElement::new(local_name!("body"), None, owner_doc)) - } + _ => DomRoot::upcast(HTMLBodyElement::new(local_name!("body"), None, owner_doc)), } } // https://fullscreen.spec.whatwg.org/#fullscreen-element-ready-check pub fn fullscreen_element_ready_check(&self) -> bool { if !self.is_connected() { - return false + return false; } let document = document_from_node(self); document.get_allow_fullscreen() @@ -1569,7 +1687,8 @@ impl Element { // https://html.spec.whatwg.org/multipage/#home-subtree pub fn is_in_same_home_subtree<T>(&self, other: &T) -> bool - where T: DerivedFrom<Element> + DomObject + where + T: DerivedFrom<Element> + DomObject, { let other = other.upcast::<Element>(); self.root_element() == other.root_element() @@ -1597,10 +1716,8 @@ impl ElementMethods for Element { fn TagName(&self) -> DOMString { let name = self.tag_name.or_init(|| { let qualified_name = match *self.prefix.borrow() { - Some(ref prefix) => { - Cow::Owned(format!("{}:{}", &**prefix, &*self.local_name)) - }, - None => Cow::Borrowed(&*self.local_name) + Some(ref prefix) => Cow::Owned(format!("{}:{}", &**prefix, &*self.local_name)), + None => Cow::Borrowed(&*self.local_name), }; if self.html_element_in_html_document() { LocalName::from(qualified_name.to_ascii_uppercase()) @@ -1633,12 +1750,14 @@ impl ElementMethods for Element { // https://dom.spec.whatwg.org/#dom-element-classlist fn ClassList(&self) -> DomRoot<DOMTokenList> { - self.class_list.or_init(|| DOMTokenList::new(self, &local_name!("class"))) + self.class_list + .or_init(|| DOMTokenList::new(self, &local_name!("class"))) } // https://dom.spec.whatwg.org/#dom-element-attributes fn Attributes(&self) -> DomRoot<NamedNodeMap> { - self.attr_list.or_init(|| NamedNodeMap::new(&window_from_node(self), self)) + self.attr_list + .or_init(|| NamedNodeMap::new(&window_from_node(self), self)) } // https://dom.spec.whatwg.org/#dom-element-hasattributes @@ -1653,15 +1772,15 @@ impl ElementMethods for Element { // https://dom.spec.whatwg.org/#dom-element-getattribute fn GetAttribute(&self, name: DOMString) -> Option<DOMString> { - self.GetAttributeNode(name) - .map(|s| s.Value()) + self.GetAttributeNode(name).map(|s| s.Value()) } // https://dom.spec.whatwg.org/#dom-element-getattributens - fn GetAttributeNS(&self, - namespace: Option<DOMString>, - local_name: DOMString) - -> Option<DOMString> { + fn GetAttributeNS( + &self, + namespace: Option<DOMString>, + local_name: DOMString, + ) -> Option<DOMString> { self.GetAttributeNodeNS(namespace, local_name) .map(|attr| attr.Value()) } @@ -1672,10 +1791,11 @@ impl ElementMethods for Element { } // https://dom.spec.whatwg.org/#dom-element-getattributenodens - fn GetAttributeNodeNS(&self, - namespace: Option<DOMString>, - local_name: DOMString) - -> Option<DomRoot<Attr>> { + fn GetAttributeNodeNS( + &self, + namespace: Option<DOMString>, + local_name: DOMString, + ) -> Option<DomRoot<Attr>> { let namespace = &namespace_from_domstring(namespace); self.get_attribute(namespace, &LocalName::from(local_name)) } @@ -1698,8 +1818,13 @@ impl ElementMethods for Element { // Step 4.1. None | Some(true) => { self.set_first_matching_attribute( - name.clone(), AttrValue::String(String::new()), name.clone(), ns!(), None, - |attr| *attr.name() == name); + name.clone(), + AttrValue::String(String::new()), + name.clone(), + ns!(), + None, + |attr| *attr.name() == name, + ); Ok(true) }, // Step 4.2. @@ -1729,24 +1854,30 @@ impl ElementMethods for Element { // Step 3-5. let value = self.parse_attribute(&ns!(), &name, value); - self.set_first_matching_attribute( - name.clone(), value, name.clone(), ns!(), None, - |attr| *attr.name() == name); + self.set_first_matching_attribute(name.clone(), value, name.clone(), ns!(), None, |attr| { + *attr.name() == name + }); Ok(()) } // https://dom.spec.whatwg.org/#dom-element-setattributens - fn SetAttributeNS(&self, - namespace: Option<DOMString>, - qualified_name: DOMString, - value: DOMString) -> ErrorResult { - let (namespace, prefix, local_name) = - validate_and_extract(namespace, &qualified_name)?; + fn SetAttributeNS( + &self, + namespace: Option<DOMString>, + qualified_name: DOMString, + value: DOMString, + ) -> ErrorResult { + let (namespace, prefix, local_name) = validate_and_extract(namespace, &qualified_name)?; let qualified_name = LocalName::from(qualified_name); let value = self.parse_attribute(&namespace, &local_name, value); self.set_first_matching_attribute( - local_name.clone(), value, qualified_name, namespace.clone(), prefix, - |attr| *attr.local_name() == local_name && *attr.namespace() == namespace); + local_name.clone(), + value, + qualified_name, + namespace.clone(), + prefix, + |attr| *attr.local_name() == local_name && *attr.namespace() == namespace, + ); Ok(()) } @@ -1764,9 +1895,7 @@ impl ElementMethods for Element { // This ensures that the attribute is of the expected kind for this // specific element. This is inefficient and should probably be done // differently. - attr.swap_value( - &mut vtable.parse_plain_attribute(attr.local_name(), attr.Value()), - ); + attr.swap_value(&mut vtable.parse_plain_attribute(attr.local_name(), attr.Value())); // Step 2. let position = self.attrs.borrow().iter().position(|old_attr| { @@ -1787,8 +1916,12 @@ impl ElementMethods for Element { let old_value = DOMString::from(&**old_attr.value()); let new_value = DOMString::from(&**attr.value()); let namespace = old_attr.namespace().clone(); - let reaction = CallbackReaction::AttributeChanged(old_name, Some(old_value), - Some(new_value), namespace); + let reaction = CallbackReaction::AttributeChanged( + old_name, + Some(old_value), + Some(new_value), + namespace, + ); ScriptThread::enqueue_callback_reaction(self, reaction, None); } self.will_mutate_attr(attr); @@ -1796,8 +1929,7 @@ impl ElementMethods for Element { self.attrs.borrow_mut()[position] = Dom::from_ref(attr); old_attr.set_owner(None); if attr.namespace() == &ns!() { - vtable.attribute_mutated( - &attr, AttributeMutation::Set(Some(&old_attr.value()))); + vtable.attribute_mutated(&attr, AttributeMutation::Set(Some(&old_attr.value()))); } // Step 6. @@ -1853,10 +1985,11 @@ impl ElementMethods for Element { } // https://dom.spec.whatwg.org/#dom-element-getelementsbytagnamens - fn GetElementsByTagNameNS(&self, - maybe_ns: Option<DOMString>, - localname: DOMString) - -> DomRoot<HTMLCollection> { + fn GetElementsByTagNameNS( + &self, + maybe_ns: Option<DOMString>, + localname: DOMString, + ) -> DomRoot<HTMLCollection> { let window = window_from_node(self); HTMLCollection::by_tag_name_ns(&window, self.upcast(), localname, maybe_ns) } @@ -1871,24 +2004,30 @@ impl ElementMethods for Element { fn GetClientRects(&self) -> Vec<DomRoot<DOMRect>> { let win = window_from_node(self); let raw_rects = self.upcast::<Node>().content_boxes(); - raw_rects.iter().map(|rect| { - DOMRect::new(win.upcast(), - rect.origin.x.to_f64_px(), - rect.origin.y.to_f64_px(), - rect.size.width.to_f64_px(), - rect.size.height.to_f64_px()) - }).collect() + raw_rects + .iter() + .map(|rect| { + DOMRect::new( + win.upcast(), + rect.origin.x.to_f64_px(), + rect.origin.y.to_f64_px(), + rect.size.width.to_f64_px(), + rect.size.height.to_f64_px(), + ) + }).collect() } // https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect fn GetBoundingClientRect(&self) -> DomRoot<DOMRect> { let win = window_from_node(self); let rect = self.upcast::<Node>().bounding_content_box_or_zero(); - DOMRect::new(win.upcast(), - rect.origin.x.to_f64_px(), - rect.origin.y.to_f64_px(), - rect.size.width.to_f64_px(), - rect.size.height.to_f64_px()) + DOMRect::new( + win.upcast(), + rect.origin.x.to_f64_px(), + rect.origin.y.to_f64_px(), + rect.size.width.to_f64_px(), + rect.size.height.to_f64_px(), + ) } // https://drafts.csswg.org/cssom-view/#dom-element-scroll @@ -1921,8 +2060,7 @@ impl ElementMethods for Element { let delta_top = options.top.unwrap_or(0.0f64); let left = self.ScrollLeft(); let top = self.ScrollTop(); - self.scroll(left + delta_left, top + delta_top, - options.parent.behavior); + self.scroll(left + delta_left, top + delta_top, options.parent.behavior); } // https://drafts.csswg.org/cssom-view/#dom-element-scrollby @@ -1962,12 +2100,12 @@ impl ElementMethods for Element { // Step 7 if doc.GetBody().r() == self.downcast::<HTMLElement>() && - doc.quirks_mode() == QuirksMode::Quirks && - !self.potentially_scrollable() { - return win.ScrollY() as f64; + doc.quirks_mode() == QuirksMode::Quirks && + !self.potentially_scrollable() + { + return win.ScrollY() as f64; } - // Step 8 if !self.has_css_layout_box() { return 0.0; @@ -2012,17 +2150,15 @@ impl ElementMethods for Element { // Step 9 if doc.GetBody().r() == self.downcast::<HTMLElement>() && - doc.quirks_mode() == QuirksMode::Quirks && - !self.potentially_scrollable() { - win.scroll(win.ScrollX() as f64, y, behavior); - return; + doc.quirks_mode() == QuirksMode::Quirks && + !self.potentially_scrollable() + { + win.scroll(win.ScrollX() as f64, y, behavior); + return; } // Step 10 - if !self.has_css_layout_box() || - !self.has_scrolling_box() || - !self.has_overflow() - { + if !self.has_css_layout_box() || !self.has_scrolling_box() || !self.has_overflow() { return; } @@ -2060,12 +2196,12 @@ impl ElementMethods for Element { // Step 7 if doc.GetBody().r() == self.downcast::<HTMLElement>() && - doc.quirks_mode() == QuirksMode::Quirks && - !self.potentially_scrollable() { - return win.ScrollX() as f64; + doc.quirks_mode() == QuirksMode::Quirks && + !self.potentially_scrollable() + { + return win.ScrollX() as f64; } - // Step 8 if !self.has_css_layout_box() { return 0.0; @@ -2111,17 +2247,15 @@ impl ElementMethods for Element { // Step 9 if doc.GetBody().r() == self.downcast::<HTMLElement>() && - doc.quirks_mode() == QuirksMode::Quirks && - !self.potentially_scrollable() { - win.scroll(x, win.ScrollY() as f64, behavior); - return; + doc.quirks_mode() == QuirksMode::Quirks && + !self.potentially_scrollable() + { + win.scroll(x, win.ScrollY() as f64, behavior); + return; } // Step 10 - if !self.has_css_layout_box() || - !self.has_scrolling_box() || - !self.has_overflow() - { + if !self.has_css_layout_box() || !self.has_scrolling_box() || !self.has_overflow() { return; } @@ -2161,9 +2295,11 @@ impl ElementMethods for Element { /// <https://w3c.github.io/DOM-Parsing/#widl-Element-innerHTML> fn GetInnerHTML(&self) -> Fallible<DOMString> { - let qname = QualName::new(self.prefix().clone(), - self.namespace().clone(), - self.local_name().clone()); + let qname = QualName::new( + self.prefix().clone(), + self.namespace().clone(), + self.local_name().clone(), + ); if document_from_node(self).is_html_document() { return self.serialize(ChildrenOnly(Some(qname))); } else { @@ -2214,14 +2350,16 @@ impl ElementMethods for Element { // Step 4. NodeTypeId::DocumentFragment => { - let body_elem = Element::create(QualName::new(None, ns!(html), local_name!("body")), - None, - &context_document, - ElementCreator::ScriptCreated, - CustomElementCreationMode::Synchronous); + let body_elem = Element::create( + QualName::new(None, ns!(html), local_name!("body")), + None, + &context_document, + ElementCreator::ScriptCreated, + CustomElementCreationMode::Synchronous, + ); DomRoot::upcast(body_elem) }, - _ => context_node.GetParentElement().unwrap() + _ => context_node.GetParentElement().unwrap(), }; // Step 5. @@ -2233,12 +2371,18 @@ impl ElementMethods for Element { // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling fn GetPreviousElementSibling(&self) -> Option<DomRoot<Element>> { - self.upcast::<Node>().preceding_siblings().filter_map(DomRoot::downcast).next() + self.upcast::<Node>() + .preceding_siblings() + .filter_map(DomRoot::downcast) + .next() } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling fn GetNextElementSibling(&self) -> Option<DomRoot<Element>> { - self.upcast::<Node>().following_siblings().filter_map(DomRoot::downcast).next() + self.upcast::<Node>() + .following_siblings() + .filter_map(DomRoot::downcast) + .next() } // https://dom.spec.whatwg.org/#dom-parentnode-children @@ -2254,7 +2398,10 @@ impl ElementMethods for Element { // https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild fn GetLastElementChild(&self) -> Option<DomRoot<Element>> { - self.upcast::<Node>().rev_children().filter_map(DomRoot::downcast::<Element>).next() + self.upcast::<Node>() + .rev_children() + .filter_map(DomRoot::downcast::<Element>) + .next() } // https://dom.spec.whatwg.org/#dom-parentnode-childelementcount @@ -2306,11 +2453,10 @@ impl ElementMethods for Element { // https://dom.spec.whatwg.org/#dom-element-matches fn Matches(&self, selectors: DOMString) -> Fallible<bool> { - let selectors = - match SelectorParser::parse_author_origin_no_namespace(&selectors) { - Err(_) => return Err(Error::Syntax), - Ok(selectors) => selectors, - }; + let selectors = match SelectorParser::parse_author_origin_no_namespace(&selectors) { + Err(_) => return Err(Error::Syntax), + Ok(selectors) => selectors, + }; let quirks_mode = document_from_node(self).quirks_mode(); let element = DomRoot::from_ref(self); @@ -2325,11 +2471,10 @@ impl ElementMethods for Element { // https://dom.spec.whatwg.org/#dom-element-closest fn Closest(&self, selectors: DOMString) -> Fallible<Option<DomRoot<Element>>> { - let selectors = - match SelectorParser::parse_author_origin_no_namespace(&selectors) { - Err(_) => return Err(Error::Syntax), - Ok(selectors) => selectors, - }; + let selectors = match SelectorParser::parse_author_origin_no_namespace(&selectors) { + Err(_) => return Err(Error::Syntax), + Ok(selectors) => selectors, + }; let quirks_mode = document_from_node(self).quirks_mode(); Ok(dom_apis::element_closest( @@ -2340,16 +2485,18 @@ impl ElementMethods for Element { } // https://dom.spec.whatwg.org/#dom-element-insertadjacentelement - fn InsertAdjacentElement(&self, where_: DOMString, element: &Element) - -> Fallible<Option<DomRoot<Element>>> { + fn InsertAdjacentElement( + &self, + where_: DOMString, + element: &Element, + ) -> Fallible<Option<DomRoot<Element>>> { let where_ = where_.parse::<AdjacentPosition>()?; let inserted_node = self.insert_adjacent(where_, element.upcast())?; Ok(inserted_node.map(|node| DomRoot::downcast(node).unwrap())) } // https://dom.spec.whatwg.org/#dom-element-insertadjacenttext - fn InsertAdjacentText(&self, where_: DOMString, data: DOMString) - -> ErrorResult { + fn InsertAdjacentText(&self, where_: DOMString, data: DOMString) -> ErrorResult { // Step 1. let text = Text::new(data, &document_from_node(self)); @@ -2359,35 +2506,34 @@ impl ElementMethods for Element { } // https://w3c.github.io/DOM-Parsing/#dom-element-insertadjacenthtml - fn InsertAdjacentHTML(&self, position: DOMString, text: DOMString) - -> ErrorResult { + fn InsertAdjacentHTML(&self, position: DOMString, text: DOMString) -> ErrorResult { // Step 1. let position = position.parse::<AdjacentPosition>()?; let context = match position { - AdjacentPosition::BeforeBegin | AdjacentPosition::AfterEnd => { - match self.upcast::<Node>().GetParentNode() { - Some(ref node) if node.is::<Document>() => { - return Err(Error::NoModificationAllowed) - } - None => return Err(Error::NoModificationAllowed), - Some(node) => node, - } - } + AdjacentPosition::BeforeBegin | AdjacentPosition::AfterEnd => match self + .upcast::<Node>() + .GetParentNode() + { + Some(ref node) if node.is::<Document>() => return Err(Error::NoModificationAllowed), + None => return Err(Error::NoModificationAllowed), + Some(node) => node, + }, AdjacentPosition::AfterBegin | AdjacentPosition::BeforeEnd => { DomRoot::from_ref(self.upcast::<Node>()) - } + }, }; // Step 2. - let context = Element::fragment_parsing_context( - &context.owner_doc(), context.downcast::<Element>()); + let context = + Element::fragment_parsing_context(&context.owner_doc(), context.downcast::<Element>()); // Step 3. let fragment = context.parse_fragment(text)?; // Step 4. - self.insert_adjacent(position, fragment.upcast()).map(|_| ()) + self.insert_adjacent(position, fragment.upcast()) + .map(|_| ()) } // check-tidy: no specs after this line @@ -2397,7 +2543,7 @@ impl ElementMethods for Element { a.enter_formal_activation_state(); return Ok(()); }, - None => return Err(Error::NotSupported) + None => return Err(Error::NotSupported), } } @@ -2407,7 +2553,7 @@ impl ElementMethods for Element { a.exit_formal_activation_state(); return Ok(()); }, - None => return Err(Error::NotSupported) + None => return Err(Error::NotSupported), } } @@ -2426,12 +2572,14 @@ impl VirtualMethods for Element { fn attribute_affects_presentational_hints(&self, attr: &Attr) -> bool { // FIXME: This should be more fine-grained, not all elements care about these. - if attr.local_name() == &local_name!("width") || - attr.local_name() == &local_name!("height") { + if attr.local_name() == &local_name!("width") || attr.local_name() == &local_name!("height") + { return true; } - self.super_type().unwrap().attribute_affects_presentational_hints(attr) + self.super_type() + .unwrap() + .attribute_affects_presentational_hints(attr) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { @@ -2469,26 +2617,24 @@ impl VirtualMethods for Element { &attr.value(), &doc.base_url(), win.css_error_reporter(), - doc.quirks_mode()))) + doc.quirks_mode(), + ))) }; Some(block) - } - AttributeMutation::Removed => { - None - } + }, + AttributeMutation::Removed => None, }; }, &local_name!("id") => { - *self.id_attribute.borrow_mut() = - mutation.new_value(attr).and_then(|value| { - let value = value.as_atom(); - if value != &atom!("") { - Some(value.clone()) - } else { - None - } - }); + *self.id_attribute.borrow_mut() = mutation.new_value(attr).and_then(|value| { + let value = value.as_atom(); + if value != &atom!("") { + Some(value.clone()) + } else { + None + } + }); if node.is_in_doc() { let value = attr.value().as_atom().clone(); match mutation { @@ -2505,15 +2651,14 @@ impl VirtualMethods for Element { if value != atom!("") { doc.unregister_named_element(self, value); } - } + }, } } }, _ => { // FIXME(emilio): This is pretty dubious, and should be done in // the relevant super-classes. - if attr.namespace() == &ns!() && - attr.local_name() == &local_name!("src") { + if attr.namespace() == &ns!() && attr.local_name() == &local_name!("src") { node.dirty(NodeDamage::OtherNodeDamage); } }, @@ -2529,7 +2674,10 @@ impl VirtualMethods for Element { match name { &local_name!("id") => AttrValue::from_atomic(value.into()), &local_name!("class") => AttrValue::from_serialized_tokenlist(value.into()), - _ => self.super_type().unwrap().parse_plain_attribute(name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(name, value), } } @@ -2644,29 +2792,32 @@ impl<'a> SelectorsElement for DomRoot<Element> { } fn prev_sibling_element(&self) -> Option<DomRoot<Element>> { - self.node.preceding_siblings().filter_map(DomRoot::downcast).next() + self.node + .preceding_siblings() + .filter_map(DomRoot::downcast) + .next() } fn next_sibling_element(&self) -> Option<DomRoot<Element>> { - self.node.following_siblings().filter_map(DomRoot::downcast).next() + self.node + .following_siblings() + .filter_map(DomRoot::downcast) + .next() } - fn attr_matches(&self, - ns: &NamespaceConstraint<&Namespace>, - local_name: &LocalName, - operation: &AttrSelectorOperation<&String>) - -> bool { + fn attr_matches( + &self, + ns: &NamespaceConstraint<&Namespace>, + local_name: &LocalName, + operation: &AttrSelectorOperation<&String>, + ) -> bool { match *ns { - NamespaceConstraint::Specific(ref ns) => { - self.get_attribute(ns, local_name) - .map_or(false, |attr| attr.value().eval_selector(operation)) - } - NamespaceConstraint::Any => { - self.attrs.borrow().iter().any(|attr| { - attr.local_name() == local_name && - attr.value().eval_selector(operation) - }) - } + NamespaceConstraint::Specific(ref ns) => self + .get_attribute(ns, local_name) + .map_or(false, |attr| attr.value().eval_selector(operation)), + NamespaceConstraint::Any => self.attrs.borrow().iter().any(|attr| { + attr.local_name() == local_name && attr.value().eval_selector(operation) + }), } } @@ -2678,9 +2829,11 @@ impl<'a> SelectorsElement for DomRoot<Element> { } fn is_empty(&self) -> bool { - self.node.children().all(|node| !node.is::<Element>() && match node.downcast::<Text>() { - None => true, - Some(text) => text.upcast::<CharacterData>().data().is_empty() + self.node.children().all(|node| { + !node.is::<Element>() && match node.downcast::<Text>() { + None => true, + Some(text) => text.upcast::<CharacterData>().data().is_empty(), + } }) } @@ -2703,26 +2856,20 @@ impl<'a> SelectorsElement for DomRoot<Element> { { match *pseudo_class { // https://github.com/servo/servo/issues/8718 - NonTSPseudoClass::Link | - NonTSPseudoClass::AnyLink => self.is_link(), + NonTSPseudoClass::Link | NonTSPseudoClass::AnyLink => self.is_link(), NonTSPseudoClass::Visited => false, - NonTSPseudoClass::ServoNonZeroBorder => { - match self.downcast::<HTMLTableElement>() { - None => false, - Some(this) => { - match this.get_border() { - None | Some(0) => false, - Some(_) => true, - } - } - } + NonTSPseudoClass::ServoNonZeroBorder => match self.downcast::<HTMLTableElement>() { + None => false, + Some(this) => match this.get_border() { + None | Some(0) => false, + Some(_) => true, + }, }, - NonTSPseudoClass::ServoCaseSensitiveTypeAttr(ref expected_value) => { - self.get_attribute(&ns!(), &local_name!("type")) - .map_or(false, |attr| attr.value().eq(expected_value)) - } + NonTSPseudoClass::ServoCaseSensitiveTypeAttr(ref expected_value) => self + .get_attribute(&ns!(), &local_name!("type")) + .map_or(false, |attr| attr.value().eq(expected_value)), // FIXME(heycam): This is wrong, since extended_filtering accepts // a string containing commas (separating each language tag in @@ -2730,8 +2877,7 @@ impl<'a> SelectorsElement for DomRoot<Element> { // storing separate <ident> or <string>s for each language tag. NonTSPseudoClass::Lang(ref lang) => extended_filtering(&*self.get_lang(), &*lang), - NonTSPseudoClass::ReadOnly => - !Element::state(self).contains(pseudo_class.state_flag()), + NonTSPseudoClass::ReadOnly => !Element::state(self).contains(pseudo_class.state_flag()), NonTSPseudoClass::Active | NonTSPseudoClass::Focus | @@ -2743,8 +2889,7 @@ impl<'a> SelectorsElement for DomRoot<Element> { NonTSPseudoClass::Indeterminate | NonTSPseudoClass::ReadWrite | NonTSPseudoClass::PlaceholderShown | - NonTSPseudoClass::Target => - Element::state(self).contains(pseudo_class.state_flag()), + NonTSPseudoClass::Target => Element::state(self).contains(pseudo_class.state_flag()), } } @@ -2753,7 +2898,9 @@ impl<'a> SelectorsElement for DomRoot<Element> { let node = self.upcast::<Node>(); match node.type_id() { // https://html.spec.whatwg.org/multipage/#selector-link - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) | + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLAnchorElement, + )) | NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAreaElement)) | NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLinkElement)) => { self.has_attribute(&local_name!("href")) @@ -2763,7 +2910,10 @@ impl<'a> SelectorsElement for DomRoot<Element> { } fn has_id(&self, id: &Atom, case_sensitivity: CaseSensitivity) -> bool { - self.id_attribute.borrow().as_ref().map_or(false, |atom| case_sensitivity.eq_atom(id, atom)) + self.id_attribute + .borrow() + .as_ref() + .map_or(false, |atom| case_sensitivity.eq_atom(id, atom)) } fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool { @@ -2779,29 +2929,34 @@ impl<'a> SelectorsElement for DomRoot<Element> { } } - impl Element { pub fn as_maybe_activatable(&self) -> Option<&Activatable> { let element = match self.upcast::<Node>().type_id() { - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => { + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLInputElement, + )) => { let element = self.downcast::<HTMLInputElement>().unwrap(); Some(element as &Activatable) }, - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) => { + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLButtonElement, + )) => { let element = self.downcast::<HTMLButtonElement>().unwrap(); Some(element as &Activatable) }, - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) => { + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLAnchorElement, + )) => { let element = self.downcast::<HTMLAnchorElement>().unwrap(); Some(element as &Activatable) }, - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLabelElement)) => { + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLLabelElement, + )) => { let element = self.downcast::<HTMLLabelElement>().unwrap(); Some(element as &Activatable) }, - _ => { - None - } + _ => None, }; element.and_then(|elem| { if elem.is_instance_activatable() { @@ -2814,11 +2969,11 @@ impl Element { pub fn as_stylesheet_owner(&self) -> Option<&StylesheetOwner> { if let Some(s) = self.downcast::<HTMLStyleElement>() { - return Some(s as &StylesheetOwner) + return Some(s as &StylesheetOwner); } if let Some(l) = self.downcast::<HTMLLinkElement>() { - return Some(l as &StylesheetOwner) + return Some(l as &StylesheetOwner); } None @@ -2827,29 +2982,37 @@ impl Element { // https://html.spec.whatwg.org/multipage/#category-submit pub fn as_maybe_validatable(&self) -> Option<&Validatable> { let element = match self.upcast::<Node>().type_id() { - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => { + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLInputElement, + )) => { let element = self.downcast::<HTMLInputElement>().unwrap(); Some(element as &Validatable) }, - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) => { + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLButtonElement, + )) => { let element = self.downcast::<HTMLButtonElement>().unwrap(); Some(element as &Validatable) }, - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLObjectElement)) => { + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLObjectElement, + )) => { let element = self.downcast::<HTMLObjectElement>().unwrap(); Some(element as &Validatable) }, - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) => { + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLSelectElement, + )) => { let element = self.downcast::<HTMLSelectElement>().unwrap(); Some(element as &Validatable) }, - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => { + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLTextAreaElement, + )) => { let element = self.downcast::<HTMLTextAreaElement>().unwrap(); Some(element as &Validatable) }, - _ => { - None - } + _ => None, }; element } @@ -2859,7 +3022,8 @@ impl Element { } pub fn set_click_in_progress(&self, click: bool) { - self.upcast::<Node>().set_flag(NodeFlags::CLICK_IN_PROGRESS, click) + self.upcast::<Node>() + .set_flag(NodeFlags::CLICK_IN_PROGRESS, click) } // https://html.spec.whatwg.org/multipage/#nearest-activatable-element @@ -2876,7 +3040,7 @@ impl Element { } } None - } + }, } } @@ -2911,16 +3075,16 @@ impl Element { } else { elem.canceled_activation(); } - } + }, // Step 6 None => { event.fire(target); - } + }, }, // Step 6 None => { event.fire(target); - } + }, } // Step 7 self.set_click_in_progress(false); @@ -2928,15 +3092,18 @@ impl Element { // https://html.spec.whatwg.org/multipage/#language pub fn get_lang(&self) -> String { - self.upcast::<Node>().inclusive_ancestors().filter_map(|node| { - node.downcast::<Element>().and_then(|el| { - el.get_attribute(&ns!(xml), &local_name!("lang")).or_else(|| { - el.get_attribute(&ns!(), &local_name!("lang")) - }).map(|attr| String::from(attr.Value())) - }) - // TODO: Check meta tags for a pragma-set default language - // TODO: Check HTTP Content-Language header - }).next().unwrap_or(String::new()) + self.upcast::<Node>() + .inclusive_ancestors() + .filter_map(|node| { + node.downcast::<Element>().and_then(|el| { + el.get_attribute(&ns!(xml), &local_name!("lang")) + .or_else(|| el.get_attribute(&ns!(), &local_name!("lang"))) + .map(|attr| String::from(attr.Value())) + }) + // TODO: Check meta tags for a pragma-set default language + // TODO: Check HTTP Content-Language header + }).next() + .unwrap_or(String::new()) } pub fn state(&self) -> ElementState { @@ -3013,7 +3180,9 @@ impl Element { } pub fn placeholder_shown_state(&self) -> bool { - self.state.get().contains(ElementState::IN_PLACEHOLDER_SHOWN_STATE) + self.state + .get() + .contains(ElementState::IN_PLACEHOLDER_SHOWN_STATE) } pub fn set_placeholder_shown_state(&self, value: bool) { @@ -3084,7 +3253,8 @@ impl Element { let node = self.upcast::<Node>(); if let Some(ref parent) = node.GetParentNode() { if parent.is::<HTMLOptGroupElement>() && - parent.downcast::<Element>().unwrap().disabled_state() { + parent.downcast::<Element>().unwrap().disabled_state() + { self.set_disabled_state(true); self.set_enabled_state(false); } @@ -3135,13 +3305,16 @@ struct TagName { impl TagName { fn new() -> TagName { - TagName { ptr: DomRefCell::new(None) } + TagName { + ptr: DomRefCell::new(None), + } } /// Retrieve a copy of the current inner value. If it is `None`, it is /// initialized with the result of `cb` first. fn or_init<F>(&self, cb: F) -> LocalName - where F: FnOnce() -> LocalName + where + F: FnOnce() -> LocalName, { match &mut *self.ptr.borrow_mut() { &mut Some(ref name) => name.clone(), @@ -3149,7 +3322,7 @@ impl TagName { let name = cb(); *ptr = Some(name.clone()); name - } + }, } } @@ -3167,7 +3340,11 @@ pub struct ElementPerformFullscreenEnter { } impl ElementPerformFullscreenEnter { - pub fn new(element: Trusted<Element>, promise: TrustedPromise, error: bool) -> Box<ElementPerformFullscreenEnter> { + pub fn new( + element: Trusted<Element>, + promise: TrustedPromise, + error: bool, + ) -> Box<ElementPerformFullscreenEnter> { Box::new(ElementPerformFullscreenEnter { element: element, promise: promise, @@ -3185,19 +3362,25 @@ impl TaskOnce for ElementPerformFullscreenEnter { // Step 7.1 if self.error || !element.fullscreen_element_ready_check() { - document.upcast::<EventTarget>().fire_event(atom!("fullscreenerror")); + document + .upcast::<EventTarget>() + .fire_event(atom!("fullscreenerror")); promise.reject_error(Error::Type(String::from("fullscreen is not connected"))); - return + return; } // TODO Step 7.2-4 // Step 7.5 element.set_fullscreen_state(true); document.set_fullscreen_element(Some(&element)); - document.window().reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); + document + .window() + .reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); // Step 7.6 - document.upcast::<EventTarget>().fire_event(atom!("fullscreenchange")); + document + .upcast::<EventTarget>() + .fire_event(atom!("fullscreenchange")); // Step 7.7 promise.resolve_native(&()); @@ -3210,7 +3393,10 @@ pub struct ElementPerformFullscreenExit { } impl ElementPerformFullscreenExit { - pub fn new(element: Trusted<Element>, promise: TrustedPromise) -> Box<ElementPerformFullscreenExit> { + pub fn new( + element: Trusted<Element>, + promise: TrustedPromise, + ) -> Box<ElementPerformFullscreenExit> { Box::new(ElementPerformFullscreenExit { element: element, promise: promise, @@ -3227,12 +3413,16 @@ impl TaskOnce for ElementPerformFullscreenExit { // Step 9.6 element.set_fullscreen_state(false); - document.window().reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); + document + .window() + .reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); document.set_fullscreen_element(None); // Step 9.8 - document.upcast::<EventTarget>().fire_event(atom!("fullscreenchange")); + document + .upcast::<EventTarget>() + .fire_event(atom!("fullscreenchange")); // Step 9.10 self.promise.root().resolve_native(&()); @@ -3257,16 +3447,14 @@ pub fn set_cross_origin_attribute(element: &Element, value: Option<DOMString>) { Some(val) => element.set_string_attribute(&local_name!("crossorigin"), val), None => { element.remove_attribute(&ns!(), &local_name!("crossorigin")); - } + }, } } pub fn cors_setting_for_element(element: &Element) -> Option<CorsSettings> { - reflect_cross_origin_attribute(element).map_or(None, |attr| { - match &*attr { - "anonymous" => Some(CorsSettings::Anonymous), - "use-credentials" => Some(CorsSettings::UseCredentials), - _ => unreachable!() - } + reflect_cross_origin_attribute(element).map_or(None, |attr| match &*attr { + "anonymous" => Some(CorsSettings::Anonymous), + "use-credentials" => Some(CorsSettings::UseCredentials), + _ => unreachable!(), }) } diff --git a/components/script/dom/errorevent.rs b/components/script/dom/errorevent.rs index 2571040aaac..3056175f89f 100644 --- a/components/script/dom/errorevent.rs +++ b/components/script/dom/errorevent.rs @@ -40,30 +40,33 @@ impl ErrorEvent { filename: DomRefCell::new(DOMString::new()), lineno: Cell::new(0), colno: Cell::new(0), - error: Heap::default() + error: Heap::default(), } } pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<ErrorEvent> { - reflect_dom_object(Box::new(ErrorEvent::new_inherited()), - global, - ErrorEventBinding::Wrap) + reflect_dom_object( + Box::new(ErrorEvent::new_inherited()), + global, + ErrorEventBinding::Wrap, + ) } - pub fn new(global: &GlobalScope, - type_: Atom, - bubbles: EventBubbles, - cancelable: EventCancelable, - message: DOMString, - filename: DOMString, - lineno: u32, - colno: u32, - error: HandleValue) -> DomRoot<ErrorEvent> { + pub fn new( + global: &GlobalScope, + type_: Atom, + bubbles: EventBubbles, + cancelable: EventCancelable, + message: DOMString, + filename: DOMString, + lineno: u32, + colno: u32, + error: HandleValue, + ) -> DomRoot<ErrorEvent> { let ev = ErrorEvent::new_uninitialized(global); { let event = ev.upcast::<Event>(); - event.init_event(type_, bool::from(bubbles), - bool::from(cancelable)); + event.init_event(type_, bool::from(bubbles), bool::from(cancelable)); *ev.message.borrow_mut() = message; *ev.filename.borrow_mut() = filename; ev.lineno.set(lineno); @@ -73,10 +76,11 @@ impl ErrorEvent { ev } - pub fn Constructor(global: &GlobalScope, - type_: DOMString, - init: RootedTraceableBox<ErrorEventBinding::ErrorEventInit>) - -> Fallible<DomRoot<ErrorEvent>>{ + pub fn Constructor( + global: &GlobalScope, + type_: DOMString, + init: RootedTraceableBox<ErrorEventBinding::ErrorEventInit>, + ) -> Fallible<DomRoot<ErrorEvent>> { let msg = match init.message.as_ref() { Some(message) => message.clone(), None => DOMString::new(), @@ -96,18 +100,18 @@ impl ErrorEvent { let cancelable = EventCancelable::from(init.parent.cancelable); let event = ErrorEvent::new( - global, - Atom::from(type_), - bubbles, - cancelable, - msg, - file_name, - line_num, - col_num, - init.error.handle()); + global, + Atom::from(type_), + bubbles, + cancelable, + msg, + file_name, + line_num, + col_num, + init.error.handle(), + ); Ok(event) } - } impl ErrorEventMethods for ErrorEvent { diff --git a/components/script/dom/event.rs b/components/script/dom/event.rs index 71b456e24cc..46150cee78c 100644 --- a/components/script/dom/event.rs +++ b/components/script/dom/event.rs @@ -65,23 +65,25 @@ impl Event { } pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<Event> { - reflect_dom_object(Box::new(Event::new_inherited()), - global, - EventBinding::Wrap) + reflect_dom_object(Box::new(Event::new_inherited()), global, EventBinding::Wrap) } - pub fn new(global: &GlobalScope, - type_: Atom, - bubbles: EventBubbles, - cancelable: EventCancelable) -> DomRoot<Event> { + pub fn new( + global: &GlobalScope, + type_: Atom, + bubbles: EventBubbles, + cancelable: EventCancelable, + ) -> DomRoot<Event> { let event = Event::new_uninitialized(global); event.init_event(type_, bool::from(bubbles), bool::from(cancelable)); event } - pub fn Constructor(global: &GlobalScope, - type_: DOMString, - init: &EventBinding::EventInit) -> Fallible<DomRoot<Event>> { + pub fn Constructor( + global: &GlobalScope, + type_: DOMString, + init: &EventBinding::EventInit, + ) -> Fallible<DomRoot<Event>> { let bubbles = EventBubbles::from(init.bubbles); let cancelable = EventCancelable::from(init.cancelable); Ok(Event::new(global, Atom::from(type_), bubbles, cancelable)) @@ -110,7 +112,9 @@ impl Event { // https://dom.spec.whatwg.org/#event-listener-removed let mut event_path = self.construct_event_path(&target); event_path.push(DomRoot::from_ref(target)); - event_path.iter().any(|target| target.has_listeners_for(type_)) + event_path + .iter() + .any(|target| target.has_listeners_for(type_)) } // https://dom.spec.whatwg.org/#event-path @@ -122,8 +126,10 @@ impl Event { for ancestor in target_node.ancestors() { event_path.push(DomRoot::from_ref(ancestor.upcast::<EventTarget>())); } - let top_most_ancestor_or_target = - event_path.last().cloned().unwrap_or(DomRoot::from_ref(target)); + let top_most_ancestor_or_target = event_path + .last() + .cloned() + .unwrap_or(DomRoot::from_ref(target)); if let Some(document) = DomRoot::downcast::<Document>(top_most_ancestor_or_target) { if self.type_() != atom!("load") && document.browsing_context().is_some() { event_path.push(DomRoot::from_ref(document.window().upcast())); @@ -134,10 +140,11 @@ impl Event { } // https://dom.spec.whatwg.org/#concept-event-dispatch - pub fn dispatch(&self, - target: &EventTarget, - target_override: Option<&EventTarget>) - -> EventStatus { + pub fn dispatch( + &self, + target: &EventTarget, + target_override: Option<&EventTarget>, + ) -> EventStatus { assert!(!self.dispatching()); assert!(self.initialized()); assert_eq!(self.phase.get(), EventPhase::None); @@ -184,7 +191,7 @@ impl Event { pub fn status(&self) -> EventStatus { match self.DefaultPrevented() { true => EventStatus::Canceled, - false => EventStatus::NotCanceled + false => EventStatus::NotCanceled, } } @@ -296,11 +303,8 @@ impl EventMethods for Event { } // https://dom.spec.whatwg.org/#dom-event-initevent - fn InitEvent(&self, - type_: DOMString, - bubbles: bool, - cancelable: bool) { - self.init_event(Atom::from(type_), bubbles, cancelable) + fn InitEvent(&self, type_: DOMString, bubbles: bool, cancelable: bool) { + self.init_event(Atom::from(type_), bubbles, cancelable) } // https://dom.spec.whatwg.org/#dom-event-istrusted @@ -312,14 +316,14 @@ impl EventMethods for Event { #[derive(Clone, Copy, MallocSizeOf, PartialEq)] pub enum EventBubbles { Bubbles, - DoesNotBubble + DoesNotBubble, } impl From<bool> for EventBubbles { fn from(boolean: bool) -> Self { match boolean { true => EventBubbles::Bubbles, - false => EventBubbles::DoesNotBubble + false => EventBubbles::DoesNotBubble, } } } @@ -328,7 +332,7 @@ impl From<EventBubbles> for bool { fn from(bubbles: EventBubbles) -> Self { match bubbles { EventBubbles::Bubbles => true, - EventBubbles::DoesNotBubble => false + EventBubbles::DoesNotBubble => false, } } } @@ -336,14 +340,14 @@ impl From<EventBubbles> for bool { #[derive(Clone, Copy, MallocSizeOf, PartialEq)] pub enum EventCancelable { Cancelable, - NotCancelable + NotCancelable, } impl From<bool> for EventCancelable { fn from(boolean: bool) -> Self { match boolean { true => EventCancelable::Cancelable, - false => EventCancelable::NotCancelable + false => EventCancelable::NotCancelable, } } } @@ -352,7 +356,7 @@ impl From<EventCancelable> for bool { fn from(bubbles: EventCancelable) -> Self { match bubbles { EventCancelable::Cancelable => true, - EventCancelable::NotCancelable => false + EventCancelable::NotCancelable => false, } } } @@ -361,10 +365,10 @@ impl From<EventCancelable> for bool { #[repr(u16)] #[derive(MallocSizeOf)] pub enum EventPhase { - None = EventConstants::NONE, + None = EventConstants::NONE, Capturing = EventConstants::CAPTURING_PHASE, - AtTarget = EventConstants::AT_TARGET, - Bubbling = EventConstants::BUBBLING_PHASE, + AtTarget = EventConstants::AT_TARGET, + Bubbling = EventConstants::BUBBLING_PHASE, } /// An enum to indicate whether the default action of an event is allowed. @@ -392,7 +396,7 @@ pub enum EventDefault { #[derive(PartialEq)] pub enum EventStatus { Canceled, - NotCanceled + NotCanceled, } // https://dom.spec.whatwg.org/#concept-event-fire @@ -483,10 +487,12 @@ fn dispatch_to_listeners(event: &Event, target: &EventTarget, event_path: &[&Eve } // https://dom.spec.whatwg.org/#concept-event-listener-invoke -fn invoke(window: Option<&Window>, - object: &EventTarget, - event: &Event, - specific_listener_phase: Option<ListenerPhase>) { +fn invoke( + window: Option<&Window>, + object: &EventTarget, + event: &Event, + specific_listener_phase: Option<ListenerPhase>, +) { // Step 1. assert!(!event.stop_propagation.get()); @@ -503,11 +509,12 @@ fn invoke(window: Option<&Window>, } // https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke -fn inner_invoke(window: Option<&Window>, - object: &EventTarget, - event: &Event, - listeners: &[CompiledEventListener]) - -> bool { +fn inner_invoke( + window: Option<&Window>, + object: &EventTarget, + event: &Event, + listeners: &[CompiledEventListener], +) -> bool { // Step 1. let mut found = false; diff --git a/components/script/dom/eventsource.rs b/components/script/dom/eventsource.rs index 072a3dd0080..574b39e0623 100644 --- a/components/script/dom/eventsource.rs +++ b/components/script/dom/eventsource.rs @@ -51,7 +51,7 @@ struct GenerationId(u32); enum ReadyState { Connecting = 0, Open = 1, - Closed = 2 + Closed = 2, } #[dom_struct] @@ -72,7 +72,7 @@ enum ParserState { Field, Comment, Value, - Eol + Eol, } struct EventSourceContext { @@ -177,12 +177,12 @@ impl EventSourceContext { "data" => { self.data.push_str(&self.value); self.data.push('\n'); - } + }, "id" => mem::swap(&mut self.last_event_id, &mut self.value), "retry" => if let Ok(time) = u64::from_str(&self.value) { self.event_source.root().reconnection_time.set(time); }, - _ => () + _ => (), } self.field.clear(); @@ -215,13 +215,24 @@ impl EventSourceContext { }; // Steps 4-5 let event = { - let _ac = JSAutoCompartment::new(event_source.global().get_cx(), - event_source.reflector().get_jsobject().get()); + let _ac = JSAutoCompartment::new( + event_source.global().get_cx(), + event_source.reflector().get_jsobject().get(), + ); rooted!(in(event_source.global().get_cx()) let mut data = UndefinedValue()); - unsafe { self.data.to_jsval(event_source.global().get_cx(), data.handle_mut()) }; - MessageEvent::new(&*event_source.global(), type_, false, false, data.handle(), - DOMString::from(self.origin.clone()), - event_source.last_event_id.borrow().clone()) + unsafe { + self.data + .to_jsval(event_source.global().get_cx(), data.handle_mut()) + }; + MessageEvent::new( + &*event_source.global(), + type_, + false, + false, + data.handle(), + DOMString::from(self.origin.clone()), + event_source.last_event_id.borrow().clone(), + ) }; // Step 7 self.event_type.clear(); @@ -255,31 +266,31 @@ impl EventSourceContext { if let Some(&' ') = stream.peek() { stream.next(); } - } + }, ('\n', &ParserState::Value) => { self.parser_state = ParserState::Eol; self.process_field(); - } + }, ('\r', &ParserState::Value) => { if let Some(&'\n') = stream.peek() { continue; } self.parser_state = ParserState::Eol; self.process_field(); - } + }, ('\n', &ParserState::Field) => { self.parser_state = ParserState::Eol; self.process_field(); - } + }, ('\r', &ParserState::Field) => { if let Some(&'\n') = stream.peek() { continue; } self.parser_state = ParserState::Eol; self.process_field(); - } + }, ('\n', &ParserState::Eol) => self.dispatch_event(), ('\r', &ParserState::Eol) => { @@ -287,7 +298,7 @@ impl EventSourceContext { continue; } self.dispatch_event(); - } + }, ('\n', &ParserState::Comment) => self.parser_state = ParserState::Eol, ('\r', &ParserState::Comment) => { @@ -295,14 +306,14 @@ impl EventSourceContext { continue; } self.parser_state = ParserState::Eol; - } + }, (_, &ParserState::Field) => self.field.push(ch), (_, &ParserState::Value) => self.value.push(ch), (_, &ParserState::Eol) => { self.parser_state = ParserState::Field; self.field.push(ch); - } + }, (_, &ParserState::Comment) => (), } } @@ -323,7 +334,7 @@ impl FetchResponseListener for EventSourceContext { Ok(fm) => { let meta = match fm { FetchMetadata::Unfiltered(m) => m, - FetchMetadata::Filtered { unsafe_, .. } => unsafe_ + FetchMetadata::Filtered { unsafe_, .. } => unsafe_, }; match meta.content_type { None => self.fail_the_connection(), @@ -331,14 +342,14 @@ impl FetchResponseListener for EventSourceContext { Mime(TopLevel::Text, SubLevel::EventStream, _) => { self.origin = meta.final_url.origin().unicode_serialization(); self.announce_the_connection(); - } - _ => self.fail_the_connection() - } + }, + _ => self.fail_the_connection(), + }, } - } + }, Err(_) => { self.reestablish_the_connection(); - } + }, } } @@ -350,7 +361,7 @@ impl FetchResponseListener for EventSourceContext { Some((result, remaining_input)) => { self.parse(result.unwrap_or("\u{FFFD}").chars()); input = remaining_input; - } + }, } } @@ -358,18 +369,25 @@ impl FetchResponseListener for EventSourceContext { match utf8::decode(&input) { Ok(s) => { self.parse(s.chars()); - return - } - Err(utf8::DecodeError::Invalid { valid_prefix, remaining_input, .. }) => { + return; + }, + Err(utf8::DecodeError::Invalid { + valid_prefix, + remaining_input, + .. + }) => { self.parse(valid_prefix.chars()); self.parse("\u{FFFD}".chars()); input = remaining_input; - } - Err(utf8::DecodeError::Incomplete { valid_prefix, incomplete_suffix }) => { + }, + Err(utf8::DecodeError::Incomplete { + valid_prefix, + incomplete_suffix, + }) => { self.parse(valid_prefix.chars()); self.incomplete_utf8 = Some(incomplete_suffix); - return - } + return; + }, } } } @@ -400,14 +418,16 @@ impl EventSource { ready_state: Cell::new(ReadyState::Connecting), with_credentials: with_credentials, - canceller: DomRefCell::new(Default::default()) + canceller: DomRefCell::new(Default::default()), } } fn new(global: &GlobalScope, url: ServoUrl, with_credentials: bool) -> DomRoot<EventSource> { - reflect_dom_object(Box::new(EventSource::new_inherited(url, with_credentials)), - global, - Wrap) + reflect_dom_object( + Box::new(EventSource::new_inherited(url, with_credentials)), + global, + Wrap, + ) } // https://html.spec.whatwg.org/multipage/#sse-processing-model:fail-the-connection-3 @@ -438,19 +458,25 @@ impl EventSource { } // https://html.spec.whatwg.org/multipage/#dom-eventsource - pub fn Constructor(global: &GlobalScope, - url: DOMString, - event_source_init: &EventSourceInit) -> Fallible<DomRoot<EventSource>> { + pub fn Constructor( + global: &GlobalScope, + url: DOMString, + event_source_init: &EventSourceInit, + ) -> Fallible<DomRoot<EventSource>> { // TODO: Step 2 relevant settings object // Step 3 let base_url = global.api_base_url(); let url_record = match base_url.join(&*url) { Ok(u) => u, // Step 4 - Err(_) => return Err(Error::Syntax) + Err(_) => return Err(Error::Syntax), }; // Step 1, 5 - let ev = EventSource::new(global, url_record.clone(), event_source_init.withCredentials); + let ev = EventSource::new( + global, + url_record.clone(), + event_source_init.withCredentials, + ); global.track_event_source(&ev); // Steps 6-7 let cors_attribute_state = if event_source_init.withCredentials { @@ -475,7 +501,9 @@ impl EventSource { ..RequestInit::default() }; // Step 10 - request.headers.set(Accept(vec![qitem(mime!(Text / EventStream))])); + request + .headers + .set(Accept(vec![qitem(mime!(Text / EventStream))])); // Step 11 request.cache_mode = CacheMode::NoStore; // Step 12 @@ -501,14 +529,21 @@ impl EventSource { let listener = NetworkListener { context: Arc::new(Mutex::new(context)), task_source: global.networking_task_source(), - canceller: Some(global.task_canceller(TaskSourceName::Networking)) + canceller: Some(global.task_canceller(TaskSourceName::Networking)), }; - ROUTER.add_route(action_receiver.to_opaque(), Box::new(move |message| { - listener.notify_fetch(message.to().unwrap()); - })); + ROUTER.add_route( + action_receiver.to_opaque(), + Box::new(move |message| { + listener.notify_fetch(message.to().unwrap()); + }), + ); let cancel_receiver = ev.canceller.borrow_mut().initialize(); - global.core_resource_thread().send( - CoreResourceMsg::Fetch(request, FetchChannels::ResponseMsg(action_sender, Some(cancel_receiver)))).unwrap(); + global + .core_resource_thread() + .send(CoreResourceMsg::Fetch( + request, + FetchChannels::ResponseMsg(action_sender, Some(cancel_receiver)), + )).unwrap(); // Step 13 Ok(ev) } @@ -578,10 +613,16 @@ impl EventSourceTimeoutCallback { let mut request = event_source.request(); // Step 5.3 if !event_source.last_event_id.borrow().is_empty() { - request.headers.set(LastEventId(String::from(event_source.last_event_id.borrow().clone()))); + request.headers.set(LastEventId(String::from( + event_source.last_event_id.borrow().clone(), + ))); } // Step 5.4 - global.core_resource_thread().send( - CoreResourceMsg::Fetch(request, FetchChannels::ResponseMsg(self.action_sender, None))).unwrap(); + global + .core_resource_thread() + .send(CoreResourceMsg::Fetch( + request, + FetchChannels::ResponseMsg(self.action_sender, None), + )).unwrap(); } } diff --git a/components/script/dom/eventtarget.rs b/components/script/dom/eventtarget.rs index 3d028a00cdb..e012f2f13ff 100644 --- a/components/script/dom/eventtarget.rs +++ b/components/script/dom/eventtarget.rs @@ -52,17 +52,11 @@ use std::rc::Rc; #[derive(Clone, JSTraceable, MallocSizeOf, PartialEq)] pub enum CommonEventHandler { - EventHandler( - #[ignore_malloc_size_of = "Rc"] - Rc<EventHandlerNonNull>), + EventHandler(#[ignore_malloc_size_of = "Rc"] Rc<EventHandlerNonNull>), - ErrorEventHandler( - #[ignore_malloc_size_of = "Rc"] - Rc<OnErrorEventHandlerNonNull>), + ErrorEventHandler(#[ignore_malloc_size_of = "Rc"] Rc<OnErrorEventHandlerNonNull>), - BeforeUnloadEventHandler( - #[ignore_malloc_size_of = "Rc"] - Rc<OnBeforeUnloadEventHandlerNonNull>), + BeforeUnloadEventHandler(#[ignore_malloc_size_of = "Rc"] Rc<OnBeforeUnloadEventHandlerNonNull>), } impl CommonEventHandler { @@ -101,8 +95,11 @@ impl InlineEventListener { /// Get a compiled representation of this event handler, compiling it from its /// raw source if necessary. /// <https://html.spec.whatwg.org/multipage/#getting-the-current-value-of-the-event-handler> - fn get_compiled_handler(&mut self, owner: &EventTarget, ty: &Atom) - -> Option<CommonEventHandler> { + fn get_compiled_handler( + &mut self, + owner: &EventTarget, + ty: &Atom, + ) -> Option<CommonEventHandler> { match mem::replace(self, InlineEventListener::Null) { InlineEventListener::Null => None, InlineEventListener::Uncompiled(handler) => { @@ -111,11 +108,11 @@ impl InlineEventListener { *self = InlineEventListener::Compiled(compiled.clone()); } result - } + }, InlineEventListener::Compiled(handler) => { *self = InlineEventListener::Compiled(handler.clone()); Some(handler) - } + }, } } } @@ -127,14 +124,18 @@ enum EventListenerType { } impl EventListenerType { - fn get_compiled_listener(&mut self, owner: &EventTarget, ty: &Atom) - -> Option<CompiledEventListener> { + fn get_compiled_listener( + &mut self, + owner: &EventTarget, + ty: &Atom, + ) -> Option<CompiledEventListener> { match self { - &mut EventListenerType::Inline(ref mut inline) => - inline.get_compiled_handler(owner, ty) - .map(CompiledEventListener::Handler), - &mut EventListenerType::Additive(ref listener) => - Some(CompiledEventListener::Listener(listener.clone())), + &mut EventListenerType::Inline(ref mut inline) => inline + .get_compiled_handler(owner, ty) + .map(CompiledEventListener::Handler), + &mut EventListenerType::Additive(ref listener) => { + Some(CompiledEventListener::Listener(listener.clone())) + }, } } } @@ -149,10 +150,12 @@ pub enum CompiledEventListener { impl CompiledEventListener { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#the-event-handler-processing-algorithm - pub fn call_or_handle_event<T: DomObject>(&self, - object: &T, - event: &Event, - exception_handle: ExceptionHandling) { + pub fn call_or_handle_event<T: DomObject>( + &self, + object: &T, + event: &Event, + exception_handle: ExceptionHandling, + ) { // Step 3 match *self { CompiledEventListener::Listener(ref listener) => { @@ -164,35 +167,46 @@ impl CompiledEventListener { if let Some(event) = event.downcast::<ErrorEvent>() { let cx = object.global().get_cx(); rooted!(in(cx) let error = unsafe { event.Error(cx) }); - let return_value = handler.Call_(object, - EventOrString::String(event.Message()), - Some(event.Filename()), - Some(event.Lineno()), - Some(event.Colno()), - Some(error.handle()), - exception_handle); + let return_value = handler.Call_( + object, + EventOrString::String(event.Message()), + Some(event.Filename()), + Some(event.Lineno()), + Some(event.Colno()), + Some(error.handle()), + exception_handle, + ); // Step 4 if let Ok(return_value) = return_value { rooted!(in(cx) let return_value = return_value); - if return_value.handle().is_boolean() && return_value.handle().to_boolean() == true { + if return_value.handle().is_boolean() && + return_value.handle().to_boolean() == true + { event.upcast::<Event>().PreventDefault(); } } return; } - let _ = handler.Call_(object, EventOrString::Event(DomRoot::from_ref(event)), - None, None, None, None, exception_handle); - } + let _ = handler.Call_( + object, + EventOrString::Event(DomRoot::from_ref(event)), + None, + None, + None, + None, + exception_handle, + ); + }, CommonEventHandler::BeforeUnloadEventHandler(ref handler) => { if let Some(event) = event.downcast::<BeforeUnloadEvent>() { // Step 5 - if let Ok(value) = handler.Call_(object, - event.upcast::<Event>(), - exception_handle) { + if let Ok(value) = + handler.Call_(object, event.upcast::<Event>(), exception_handle) + { let rv = event.ReturnValue(); - if let Some(v) = value { + if let Some(v) = value { if rv.is_empty() { event.SetReturnValue(v); } @@ -201,9 +215,10 @@ impl CompiledEventListener { } } else { // Step 5, "Otherwise" clause - let _ = handler.Call_(object, event.upcast::<Event>(), exception_handle); + let _ = + handler.Call_(object, event.upcast::<Event>(), exception_handle); } - } + }, CommonEventHandler::EventHandler(ref handler) => { if let Ok(value) = handler.Call_(object, event, exception_handle) { @@ -213,16 +228,18 @@ impl CompiledEventListener { //Step 4 let should_cancel = match event.type_() { - atom!("mouseover") => value.is_boolean() && value.to_boolean() == true, - _ => value.is_boolean() && value.to_boolean() == false + atom!("mouseover") => { + value.is_boolean() && value.to_boolean() == true + }, + _ => value.is_boolean() && value.to_boolean() == false, }; if should_cancel { event.PreventDefault(); } } - } + }, } - } + }, } } } @@ -231,7 +248,7 @@ impl CompiledEventListener { /// A listener in a collection of event listeners. struct EventListenerEntry { phase: ListenerPhase, - listener: EventListenerType + listener: EventListenerType, } #[derive(JSTraceable, MallocSizeOf)] @@ -253,7 +270,11 @@ impl DerefMut for EventListeners { impl EventListeners { // https://html.spec.whatwg.org/multipage/#getting-the-current-value-of-the-event-handler - fn get_inline_listener(&mut self, owner: &EventTarget, ty: &Atom) -> Option<CommonEventHandler> { + fn get_inline_listener( + &mut self, + owner: &EventTarget, + ty: &Atom, + ) -> Option<CommonEventHandler> { for entry in &mut self.0 { if let EventListenerType::Inline(ref mut inline) = entry.listener { // Step 1.1-1.8 and Step 2 @@ -266,16 +287,22 @@ impl EventListeners { } // https://html.spec.whatwg.org/multipage/#getting-the-current-value-of-the-event-handler - fn get_listeners(&mut self, phase: Option<ListenerPhase>, owner: &EventTarget, ty: &Atom) - -> Vec<CompiledEventListener> { - self.0.iter_mut().filter_map(|entry| { - if phase.is_none() || Some(entry.phase) == phase { - // Step 1.1-1.8, 2 - entry.listener.get_compiled_listener(owner, ty) - } else { - None - } - }).collect() + fn get_listeners( + &mut self, + phase: Option<ListenerPhase>, + owner: &EventTarget, + ty: &Atom, + ) -> Vec<CompiledEventListener> { + self.0 + .iter_mut() + .filter_map(|entry| { + if phase.is_none() || Some(entry.phase) == phase { + // Step 1.1-1.8, 2 + entry.listener.get_compiled_listener(owner, ty) + } else { + None + } + }).collect() } fn has_listeners(&self) -> bool { @@ -300,36 +327,34 @@ impl EventTarget { } fn new(global: &GlobalScope) -> DomRoot<EventTarget> { - reflect_dom_object(Box::new(EventTarget::new_inherited()), - global, - Wrap) + reflect_dom_object(Box::new(EventTarget::new_inherited()), global, Wrap) } pub fn Constructor(global: &GlobalScope) -> Fallible<DomRoot<EventTarget>> { Ok(EventTarget::new(global)) } - pub fn has_listeners_for(&self, - type_: &Atom) - -> bool { + pub fn has_listeners_for(&self, type_: &Atom) -> bool { match self.handlers.borrow().get(type_) { Some(listeners) => listeners.has_listeners(), - None => false + None => false, } } - pub fn get_listeners_for(&self, - type_: &Atom, - specific_phase: Option<ListenerPhase>) - -> Vec<CompiledEventListener> { - self.handlers.borrow_mut().get_mut(type_).map_or(vec![], |listeners| { - listeners.get_listeners(specific_phase, self, type_) - }) - } - - pub fn dispatch_event_with_target(&self, - target: &EventTarget, - event: &Event) -> EventStatus { + pub fn get_listeners_for( + &self, + type_: &Atom, + specific_phase: Option<ListenerPhase>, + ) -> Vec<CompiledEventListener> { + self.handlers + .borrow_mut() + .get_mut(type_) + .map_or(vec![], |listeners| { + listeners.get_listeners(specific_phase, self, type_) + }) + } + + pub fn dispatch_event_with_target(&self, target: &EventTarget, event: &Event) -> EventStatus { if let Some(window) = target.global().downcast::<Window>() { if window.has_document() { assert!(window.Document().can_invoke_script()); @@ -353,27 +378,23 @@ impl EventTarget { } /// <https://html.spec.whatwg.org/multipage/#event-handler-attributes:event-handlers-11> - fn set_inline_event_listener(&self, - ty: Atom, - listener: Option<InlineEventListener>) { + fn set_inline_event_listener(&self, ty: Atom, listener: Option<InlineEventListener>) { let mut handlers = self.handlers.borrow_mut(); let entries = match handlers.entry(ty) { Occupied(entry) => entry.into_mut(), - Vacant(entry) => entry.insert(EventListeners(vec!())), + Vacant(entry) => entry.insert(EventListeners(vec![])), }; - let idx = entries.iter().position(|ref entry| { - match entry.listener { - EventListenerType::Inline(_) => true, - _ => false, - } + let idx = entries.iter().position(|ref entry| match entry.listener { + EventListenerType::Inline(_) => true, + _ => false, }); match idx { Some(idx) => { entries[idx].listener = EventListenerType::Inline(listener.unwrap_or(InlineEventListener::Null)); - } + }, None => { if let Some(listener) = listener { entries.push(EventListenerEntry { @@ -381,37 +402,44 @@ impl EventTarget { listener: EventListenerType::Inline(listener), }); } - } + }, } } fn get_inline_event_listener(&self, ty: &Atom) -> Option<CommonEventHandler> { let mut handlers = self.handlers.borrow_mut(); - handlers.get_mut(ty).and_then(|entry| entry.get_inline_listener(self, ty)) + handlers + .get_mut(ty) + .and_then(|entry| entry.get_inline_listener(self, ty)) } /// Store the raw uncompiled event handler for on-demand compilation later. /// <https://html.spec.whatwg.org/multipage/#event-handler-attributes:event-handler-content-attributes-3> - pub fn set_event_handler_uncompiled(&self, - url: ServoUrl, - line: usize, - ty: &str, - source: DOMString) { + pub fn set_event_handler_uncompiled( + &self, + url: ServoUrl, + line: usize, + ty: &str, + source: DOMString, + ) { let handler = InternalRawUncompiledHandler { source: source, line: line, url: url, }; - self.set_inline_event_listener(Atom::from(ty), - Some(InlineEventListener::Uncompiled(handler))); + self.set_inline_event_listener( + Atom::from(ty), + Some(InlineEventListener::Uncompiled(handler)), + ); } // https://html.spec.whatwg.org/multipage/#getting-the-current-value-of-the-event-handler #[allow(unsafe_code)] - fn get_compiled_event_handler(&self, - handler: InternalRawUncompiledHandler, - ty: &Atom) - -> Option<CommonEventHandler> { + fn get_compiled_event_handler( + &self, + handler: InternalRawUncompiledHandler, + ty: &Atom, + ) -> Option<CommonEventHandler> { // Step 1.1 let element = self.downcast::<Element>(); let document = match element { @@ -436,11 +464,13 @@ impl EventTarget { let name = CString::new(&**ty).unwrap(); static mut ARG_NAMES: [*const c_char; 1] = [b"event\0" as *const u8 as *const c_char]; - static mut ERROR_ARG_NAMES: [*const c_char; 5] = [b"event\0" as *const u8 as *const c_char, - b"source\0" as *const u8 as *const c_char, - b"lineno\0" as *const u8 as *const c_char, - b"colno\0" as *const u8 as *const c_char, - b"error\0" as *const u8 as *const c_char]; + static mut ERROR_ARG_NAMES: [*const c_char; 5] = [ + b"event\0" as *const u8 as *const c_char, + b"source\0" as *const u8 as *const c_char, + b"lineno\0" as *const u8 as *const c_char, + b"colno\0" as *const u8 as *const c_char, + b"error\0" as *const u8 as *const c_char, + ]; // step 10 let is_error = ty == &atom!("error") && self.is::<Window>(); let args = unsafe { @@ -460,15 +490,17 @@ impl EventTarget { let _ac = JSAutoCompartment::new(cx, window.reflector().get_jsobject().get()); rooted!(in(cx) let mut handler = ptr::null_mut::<JSFunction>()); let rv = unsafe { - CompileFunction(cx, - scopechain.ptr, - options.ptr, - name.as_ptr(), - args.len() as u32, - args.as_ptr(), - body.as_ptr(), - body.len() as size_t, - handler.handle_mut().into()) + CompileFunction( + cx, + scopechain.ptr, + options.ptr, + name.as_ptr(), + args.len() as u32, + args.as_ptr(), + body.as_ptr(), + body.len() as size_t, + handler.handle_mut().into(), + ) }; if !rv || handler.get().is_null() { // Step 1.8.2 @@ -486,56 +518,48 @@ impl EventTarget { assert!(!funobj.is_null()); // Step 1.14 if is_error { - Some(CommonEventHandler::ErrorEventHandler( - unsafe { OnErrorEventHandlerNonNull::new(cx, funobj) }, - )) + Some(CommonEventHandler::ErrorEventHandler(unsafe { + OnErrorEventHandlerNonNull::new(cx, funobj) + })) } else { if ty == &atom!("beforeunload") { - Some(CommonEventHandler::BeforeUnloadEventHandler( - unsafe { OnBeforeUnloadEventHandlerNonNull::new(cx, funobj) }, - )) + Some(CommonEventHandler::BeforeUnloadEventHandler(unsafe { + OnBeforeUnloadEventHandlerNonNull::new(cx, funobj) + })) } else { - Some(CommonEventHandler::EventHandler( - unsafe { EventHandlerNonNull::new(cx, funobj) }, - )) + Some(CommonEventHandler::EventHandler(unsafe { + EventHandlerNonNull::new(cx, funobj) + })) } } } #[allow(unsafe_code)] - pub fn set_event_handler_common<T: CallbackContainer>( - &self, - ty: &str, - listener: Option<Rc<T>>, - ) + pub fn set_event_handler_common<T: CallbackContainer>(&self, ty: &str, listener: Option<Rc<T>>) where T: CallbackContainer, { let cx = self.global().get_cx(); let event_listener = listener.map(|listener| { - InlineEventListener::Compiled(CommonEventHandler::EventHandler( - unsafe { EventHandlerNonNull::new(cx, listener.callback()) }, - )) + InlineEventListener::Compiled(CommonEventHandler::EventHandler(unsafe { + EventHandlerNonNull::new(cx, listener.callback()) + })) }); self.set_inline_event_listener(Atom::from(ty), event_listener); } #[allow(unsafe_code)] - pub fn set_error_event_handler<T: CallbackContainer>( - &self, - ty: &str, - listener: Option<Rc<T>>, - ) + pub fn set_error_event_handler<T: CallbackContainer>(&self, ty: &str, listener: Option<Rc<T>>) where T: CallbackContainer, { let cx = self.global().get_cx(); let event_listener = listener.map(|listener| { - InlineEventListener::Compiled(CommonEventHandler::ErrorEventHandler( - unsafe { OnErrorEventHandlerNonNull::new(cx, listener.callback()) } - )) + InlineEventListener::Compiled(CommonEventHandler::ErrorEventHandler(unsafe { + OnErrorEventHandlerNonNull::new(cx, listener.callback()) + })) }); self.set_inline_event_listener(Atom::from(ty), event_listener); } @@ -545,16 +569,15 @@ impl EventTarget { &self, ty: &str, listener: Option<Rc<T>>, - ) - where + ) where T: CallbackContainer, { let cx = self.global().get_cx(); let event_listener = listener.map(|listener| { - InlineEventListener::Compiled(CommonEventHandler::BeforeUnloadEventHandler( - unsafe { OnBeforeUnloadEventHandlerNonNull::new(cx, listener.callback()) } - )) + InlineEventListener::Compiled(CommonEventHandler::BeforeUnloadEventHandler(unsafe { + OnBeforeUnloadEventHandlerNonNull::new(cx, listener.callback()) + })) }); self.set_inline_event_listener(Atom::from(ty), event_listener); } @@ -564,8 +587,9 @@ impl EventTarget { let cx = self.global().get_cx(); let listener = self.get_inline_event_listener(&Atom::from(ty)); unsafe { - listener.map(|listener| - CallbackContainer::new(cx, listener.parent().callback_holder().get())) + listener.map(|listener| { + CallbackContainer::new(cx, listener.parent().callback_holder().get()) + }) } } @@ -575,38 +599,39 @@ impl EventTarget { // https://dom.spec.whatwg.org/#concept-event-fire pub fn fire_event(&self, name: Atom) -> DomRoot<Event> { - self.fire_event_with_params(name, - EventBubbles::DoesNotBubble, - EventCancelable::NotCancelable) + self.fire_event_with_params( + name, + EventBubbles::DoesNotBubble, + EventCancelable::NotCancelable, + ) } // https://dom.spec.whatwg.org/#concept-event-fire pub fn fire_bubbling_event(&self, name: Atom) -> DomRoot<Event> { - self.fire_event_with_params(name, - EventBubbles::Bubbles, - EventCancelable::NotCancelable) + self.fire_event_with_params(name, EventBubbles::Bubbles, EventCancelable::NotCancelable) } // https://dom.spec.whatwg.org/#concept-event-fire pub fn fire_cancelable_event(&self, name: Atom) -> DomRoot<Event> { - self.fire_event_with_params(name, - EventBubbles::DoesNotBubble, - EventCancelable::Cancelable) + self.fire_event_with_params( + name, + EventBubbles::DoesNotBubble, + EventCancelable::Cancelable, + ) } // https://dom.spec.whatwg.org/#concept-event-fire pub fn fire_bubbling_cancelable_event(&self, name: Atom) -> DomRoot<Event> { - self.fire_event_with_params(name, - EventBubbles::Bubbles, - EventCancelable::Cancelable) + self.fire_event_with_params(name, EventBubbles::Bubbles, EventCancelable::Cancelable) } // https://dom.spec.whatwg.org/#concept-event-fire - pub fn fire_event_with_params(&self, - name: Atom, - bubbles: EventBubbles, - cancelable: EventCancelable) - -> DomRoot<Event> { + pub fn fire_event_with_params( + &self, + name: Atom, + bubbles: EventBubbles, + cancelable: EventCancelable, + ) -> DomRoot<Event> { let event = Event::new(&self.global(), name, bubbles, cancelable); event.fire(self); event @@ -625,7 +650,7 @@ impl EventTarget { let mut handlers = self.handlers.borrow_mut(); let entry = match handlers.entry(Atom::from(ty)) { Occupied(entry) => entry.into_mut(), - Vacant(entry) => entry.insert(EventListeners(vec!())), + Vacant(entry) => entry.insert(EventListeners(vec![])), }; let phase = if options.parent.capture { @@ -635,7 +660,7 @@ impl EventTarget { }; let new_entry = EventListenerEntry { phase: phase, - listener: EventListenerType::Additive(listener) + listener: EventListenerType::Additive(listener), }; if !entry.contains(&new_entry) { entry.push(new_entry); @@ -663,7 +688,7 @@ impl EventTarget { }; let old_entry = EventListenerEntry { phase: phase, - listener: EventListenerType::Additive(listener.clone()) + listener: EventListenerType::Additive(listener.clone()), }; if let Some(position) = entry.iter().position(|e| *e == old_entry) { entry.remove(position); @@ -701,7 +726,7 @@ impl EventTargetMethods for EventTarget { event.set_trusted(false); Ok(match self.dispatch_event(event) { EventStatus::Canceled => false, - EventStatus::NotCanceled => true + EventStatus::NotCanceled => true, }) } } @@ -715,11 +740,9 @@ impl VirtualMethods for EventTarget { impl From<AddEventListenerOptionsOrBoolean> for AddEventListenerOptions { fn from(options: AddEventListenerOptionsOrBoolean) -> Self { match options { - AddEventListenerOptionsOrBoolean::AddEventListenerOptions(options) => { - options - }, - AddEventListenerOptionsOrBoolean::Boolean(capture) => { - Self { parent: EventListenerOptions { capture } } + AddEventListenerOptionsOrBoolean::AddEventListenerOptions(options) => options, + AddEventListenerOptionsOrBoolean::Boolean(capture) => Self { + parent: EventListenerOptions { capture }, }, } } @@ -728,12 +751,8 @@ impl From<AddEventListenerOptionsOrBoolean> for AddEventListenerOptions { impl From<EventListenerOptionsOrBoolean> for EventListenerOptions { fn from(options: EventListenerOptionsOrBoolean) -> Self { match options { - EventListenerOptionsOrBoolean::EventListenerOptions(options) => { - options - }, - EventListenerOptionsOrBoolean::Boolean(capture) => { - Self { capture } - }, + EventListenerOptionsOrBoolean::EventListenerOptions(options) => options, + EventListenerOptionsOrBoolean::Boolean(capture) => Self { capture }, } } } diff --git a/components/script/dom/extendableevent.rs b/components/script/dom/extendableevent.rs index e1db24ffb01..4f7462746c2 100644 --- a/components/script/dom/extendableevent.rs +++ b/components/script/dom/extendableevent.rs @@ -20,25 +20,26 @@ use servo_atoms::Atom; #[dom_struct] pub struct ExtendableEvent { event: Event, - extensions_allowed: bool + extensions_allowed: bool, } impl ExtendableEvent { pub fn new_inherited() -> ExtendableEvent { ExtendableEvent { event: Event::new_inherited(), - extensions_allowed: true + extensions_allowed: true, } } - pub fn new(worker: &ServiceWorkerGlobalScope, - type_: Atom, - bubbles: bool, - cancelable: bool) - -> DomRoot<ExtendableEvent> { + pub fn new( + worker: &ServiceWorkerGlobalScope, + type_: Atom, + bubbles: bool, + cancelable: bool, + ) -> DomRoot<ExtendableEvent> { let ev = reflect_dom_object( Box::new(ExtendableEvent::new_inherited()), worker, - ExtendableEventBinding::Wrap + ExtendableEventBinding::Wrap, ); { let event = ev.upcast::<Event>(); @@ -47,13 +48,17 @@ impl ExtendableEvent { ev } - pub fn Constructor(worker: &ServiceWorkerGlobalScope, - type_: DOMString, - init: &ExtendableEventBinding::ExtendableEventInit) -> Fallible<DomRoot<ExtendableEvent>> { - Ok(ExtendableEvent::new(worker, - Atom::from(type_), - init.parent.bubbles, - init.parent.cancelable)) + pub fn Constructor( + worker: &ServiceWorkerGlobalScope, + type_: DOMString, + init: &ExtendableEventBinding::ExtendableEventInit, + ) -> Fallible<DomRoot<ExtendableEvent>> { + Ok(ExtendableEvent::new( + worker, + Atom::from(type_), + init.parent.bubbles, + init.parent.cancelable, + )) } // https://w3c.github.io/ServiceWorker/#wait-until-method diff --git a/components/script/dom/extendablemessageevent.rs b/components/script/dom/extendablemessageevent.rs index 110fe7b9c17..0e3119db1f5 100644 --- a/components/script/dom/extendablemessageevent.rs +++ b/components/script/dom/extendablemessageevent.rs @@ -30,10 +30,15 @@ pub struct ExtendableMessageEvent { } impl ExtendableMessageEvent { - pub fn new(global: &GlobalScope, type_: Atom, - bubbles: bool, cancelable: bool, - data: HandleValue, origin: DOMString, lastEventId: DOMString) - -> DomRoot<ExtendableMessageEvent> { + pub fn new( + global: &GlobalScope, + type_: Atom, + bubbles: bool, + cancelable: bool, + data: HandleValue, + origin: DOMString, + lastEventId: DOMString, + ) -> DomRoot<ExtendableMessageEvent> { let ev = Box::new(ExtendableMessageEvent { event: ExtendableEvent::new_inherited(), data: Heap::default(), @@ -50,29 +55,36 @@ impl ExtendableMessageEvent { ev } - pub fn Constructor(worker: &ServiceWorkerGlobalScope, - type_: DOMString, - init: RootedTraceableBox<ExtendableMessageEventBinding::ExtendableMessageEventInit>) - -> Fallible<DomRoot<ExtendableMessageEvent>> { + pub fn Constructor( + worker: &ServiceWorkerGlobalScope, + type_: DOMString, + init: RootedTraceableBox<ExtendableMessageEventBinding::ExtendableMessageEventInit>, + ) -> Fallible<DomRoot<ExtendableMessageEvent>> { let global = worker.upcast::<GlobalScope>(); - let ev = ExtendableMessageEvent::new(global, - Atom::from(type_), - init.parent.parent.bubbles, - init.parent.parent.cancelable, - init.data.handle(), - init.origin.clone().unwrap(), - init.lastEventId.clone().unwrap()); + let ev = ExtendableMessageEvent::new( + global, + Atom::from(type_), + init.parent.parent.bubbles, + init.parent.parent.cancelable, + init.data.handle(), + init.origin.clone().unwrap(), + init.lastEventId.clone().unwrap(), + ); Ok(ev) } } impl ExtendableMessageEvent { - pub fn dispatch_jsval(target: &EventTarget, - scope: &GlobalScope, - message: HandleValue) { + pub fn dispatch_jsval(target: &EventTarget, scope: &GlobalScope, message: HandleValue) { let Extendablemessageevent = ExtendableMessageEvent::new( - scope, atom!("message"), false, false, message, - DOMString::new(), DOMString::new()); + scope, + atom!("message"), + false, + false, + message, + DOMString::new(), + DOMString::new(), + ); Extendablemessageevent.upcast::<Event>().fire(target); } } diff --git a/components/script/dom/file.rs b/components/script/dom/file.rs index 942fbb1a055..47fd4920bb6 100644 --- a/components/script/dom/file.rs +++ b/components/script/dom/file.rs @@ -26,8 +26,12 @@ pub struct File { impl File { #[allow(unrooted_must_root)] - fn new_inherited(blob_impl: BlobImpl, name: DOMString, - modified: Option<i64>, type_string: &str) -> File { + fn new_inherited( + blob_impl: BlobImpl, + name: DOMString, + modified: Option<i64>, + type_string: &str, + ) -> File { File { blob: Blob::new_inherited(blob_impl, type_string.to_owned()), name: name, @@ -37,33 +41,51 @@ impl File { None => { let time = time::get_time(); time.sec * 1000 + (time.nsec / 1000000) as i64 - } + }, }, } } #[allow(unrooted_must_root)] - pub fn new(global: &GlobalScope, blob_impl: BlobImpl, - name: DOMString, modified: Option<i64>, typeString: &str) -> DomRoot<File> { - reflect_dom_object(Box::new(File::new_inherited(blob_impl, name, modified, typeString)), - global, - FileBinding::Wrap) + pub fn new( + global: &GlobalScope, + blob_impl: BlobImpl, + name: DOMString, + modified: Option<i64>, + typeString: &str, + ) -> DomRoot<File> { + reflect_dom_object( + Box::new(File::new_inherited(blob_impl, name, modified, typeString)), + global, + FileBinding::Wrap, + ) } // Construct from selected file message from file manager thread pub fn new_from_selected(window: &Window, selected: SelectedFile) -> DomRoot<File> { - let name = DOMString::from(selected.filename.to_str().expect("File name encoding error")); + let name = DOMString::from( + selected + .filename + .to_str() + .expect("File name encoding error"), + ); - File::new(window.upcast(), BlobImpl::new_from_file(selected.id, selected.filename, selected.size), - name, Some(selected.modified as i64), &selected.type_string) + File::new( + window.upcast(), + BlobImpl::new_from_file(selected.id, selected.filename, selected.size), + name, + Some(selected.modified as i64), + &selected.type_string, + ) } // https://w3c.github.io/FileAPI/#file-constructor - pub fn Constructor(global: &GlobalScope, - fileBits: Vec<ArrayBufferOrArrayBufferViewOrBlobOrString>, - filename: DOMString, - filePropertyBag: &FileBinding::FilePropertyBag) - -> Fallible<DomRoot<File>> { + pub fn Constructor( + global: &GlobalScope, + fileBits: Vec<ArrayBufferOrArrayBufferViewOrBlobOrString>, + filename: DOMString, + filePropertyBag: &FileBinding::FilePropertyBag, + ) -> Fallible<DomRoot<File>> { let bytes: Vec<u8> = match blob_parts_to_bytes(fileBits) { Ok(bytes) => bytes, Err(_) => return Err(Error::InvalidCharacter), @@ -76,11 +98,13 @@ impl File { // NOTE: Following behaviour might be removed in future, // see https://github.com/w3c/FileAPI/issues/41 let replaced_filename = DOMString::from_string(filename.replace("/", ":")); - Ok(File::new(global, - BlobImpl::new_from_bytes(bytes), - replaced_filename, - modified, - typeString)) + Ok(File::new( + global, + BlobImpl::new_from_bytes(bytes), + replaced_filename, + modified, + typeString, + )) } pub fn name(&self) -> &DOMString { diff --git a/components/script/dom/filelist.rs b/components/script/dom/filelist.rs index 48dd5fdb9ca..92d39e5b539 100644 --- a/components/script/dom/filelist.rs +++ b/components/script/dom/filelist.rs @@ -15,7 +15,7 @@ use std::slice::Iter; #[dom_struct] pub struct FileList { reflector_: Reflector, - list: Vec<Dom<File>> + list: Vec<Dom<File>>, } impl FileList { @@ -23,15 +23,19 @@ impl FileList { fn new_inherited(files: Vec<Dom<File>>) -> FileList { FileList { reflector_: Reflector::new(), - list: files + list: files, } } #[allow(unrooted_must_root)] pub fn new(window: &Window, files: Vec<DomRoot<File>>) -> DomRoot<FileList> { - reflect_dom_object(Box::new(FileList::new_inherited(files.iter().map(|r| Dom::from_ref(&**r)).collect())), - window, - FileListBinding::Wrap) + reflect_dom_object( + Box::new(FileList::new_inherited( + files.iter().map(|r| Dom::from_ref(&**r)).collect(), + )), + window, + FileListBinding::Wrap, + ) } pub fn iter_files(&self) -> Iter<Dom<File>> { diff --git a/components/script/dom/filereader.rs b/components/script/dom/filereader.rs index 6b88c645bbd..c816c943303 100644 --- a/components/script/dom/filereader.rs +++ b/components/script/dom/filereader.rs @@ -466,8 +466,7 @@ impl FileReader { task_source, canceller, ) - }) - .expect("Thread spawning failed"); + }).expect("Thread spawning failed"); Ok(()) } diff --git a/components/script/dom/focusevent.rs b/components/script/dom/focusevent.rs index 7966e887b4c..ce751df8754 100644 --- a/components/script/dom/focusevent.rs +++ b/components/script/dom/focusevent.rs @@ -32,39 +32,50 @@ impl FocusEvent { } pub fn new_uninitialized(window: &Window) -> DomRoot<FocusEvent> { - reflect_dom_object(Box::new(FocusEvent::new_inherited()), - window, - FocusEventBinding::Wrap) + reflect_dom_object( + Box::new(FocusEvent::new_inherited()), + window, + FocusEventBinding::Wrap, + ) } - pub fn new(window: &Window, - type_: DOMString, - can_bubble: EventBubbles, - cancelable: EventCancelable, - view: Option<&Window>, - detail: i32, - related_target: Option<&EventTarget>) -> DomRoot<FocusEvent> { + pub fn new( + window: &Window, + type_: DOMString, + can_bubble: EventBubbles, + cancelable: EventCancelable, + view: Option<&Window>, + detail: i32, + related_target: Option<&EventTarget>, + ) -> DomRoot<FocusEvent> { let ev = FocusEvent::new_uninitialized(window); - ev.upcast::<UIEvent>().InitUIEvent(type_, - bool::from(can_bubble), - bool::from(cancelable), - view, detail); + ev.upcast::<UIEvent>().InitUIEvent( + type_, + bool::from(can_bubble), + bool::from(cancelable), + view, + detail, + ); ev.related_target.set(related_target); ev } - pub fn Constructor(window: &Window, - type_: DOMString, - init: &FocusEventBinding::FocusEventInit) -> Fallible<DomRoot<FocusEvent>> { + pub fn Constructor( + window: &Window, + type_: DOMString, + init: &FocusEventBinding::FocusEventInit, + ) -> Fallible<DomRoot<FocusEvent>> { let bubbles = EventBubbles::from(init.parent.parent.bubbles); let cancelable = EventCancelable::from(init.parent.parent.cancelable); - let event = FocusEvent::new(window, - type_, - bubbles, - cancelable, - init.parent.view.r(), - init.parent.detail, - init.relatedTarget.r()); + let event = FocusEvent::new( + window, + type_, + bubbles, + cancelable, + init.parent.view.r(), + init.parent.detail, + init.relatedTarget.r(), + ); Ok(event) } } diff --git a/components/script/dom/formdata.rs b/components/script/dom/formdata.rs index d856a6e26f7..1ec80600ba4 100644 --- a/components/script/dom/formdata.rs +++ b/components/script/dom/formdata.rs @@ -36,7 +36,9 @@ impl FormData { for datum in form.get_form_dataset(None) { match hashmap.entry(LocalName::from(datum.name.as_ref())) { Occupied(entry) => entry.into_mut().push(datum), - Vacant(entry) => { entry.insert(vec!(datum)); } + Vacant(entry) => { + entry.insert(vec![datum]); + }, } } } @@ -48,11 +50,17 @@ impl FormData { } pub fn new(form: Option<&HTMLFormElement>, global: &GlobalScope) -> DomRoot<FormData> { - reflect_dom_object(Box::new(FormData::new_inherited(form)), - global, FormDataWrap) + reflect_dom_object( + Box::new(FormData::new_inherited(form)), + global, + FormDataWrap, + ) } - pub fn Constructor(global: &GlobalScope, form: Option<&HTMLFormElement>) -> Fallible<DomRoot<FormData>> { + pub fn Constructor( + global: &GlobalScope, + form: Option<&HTMLFormElement>, + ) -> Fallible<DomRoot<FormData>> { // TODO: Construct form data set for form if it is supplied Ok(FormData::new(form, global)) } @@ -70,7 +78,9 @@ impl FormDataMethods for FormData { let mut data = self.data.borrow_mut(); match data.entry(LocalName::from(name.0)) { Occupied(entry) => entry.into_mut().push(datum), - Vacant(entry) => { entry.insert(vec!(datum)); } + Vacant(entry) => { + entry.insert(vec![datum]); + }, } } @@ -87,7 +97,9 @@ impl FormDataMethods for FormData { match data.entry(LocalName::from(name.0)) { Occupied(entry) => entry.into_mut().push(datum), - Vacant(entry) => { entry.insert(vec!(datum)); }, + Vacant(entry) => { + entry.insert(vec![datum]); + }, } } @@ -98,24 +110,33 @@ impl FormDataMethods for FormData { // https://xhr.spec.whatwg.org/#dom-formdata-get fn Get(&self, name: USVString) -> Option<FileOrUSVString> { - self.data.borrow() - .get(&LocalName::from(name.0)) - .map(|entry| match entry[0].value { - FormDatumValue::String(ref s) => FileOrUSVString::USVString(USVString(s.to_string())), - FormDatumValue::File(ref b) => FileOrUSVString::File(DomRoot::from_ref(&*b)), - }) + self.data + .borrow() + .get(&LocalName::from(name.0)) + .map(|entry| match entry[0].value { + FormDatumValue::String(ref s) => { + FileOrUSVString::USVString(USVString(s.to_string())) + }, + FormDatumValue::File(ref b) => FileOrUSVString::File(DomRoot::from_ref(&*b)), + }) } // https://xhr.spec.whatwg.org/#dom-formdata-getall fn GetAll(&self, name: USVString) -> Vec<FileOrUSVString> { - self.data.borrow() - .get(&LocalName::from(name.0)) - .map_or(vec![], |data| - data.iter().map(|item| match item.value { - FormDatumValue::String(ref s) => FileOrUSVString::USVString(USVString(s.to_string())), - FormDatumValue::File(ref b) => FileOrUSVString::File(DomRoot::from_ref(&*b)), + self.data + .borrow() + .get(&LocalName::from(name.0)) + .map_or(vec![], |data| { + data.iter() + .map(|item| match item.value { + FormDatumValue::String(ref s) => { + FileOrUSVString::USVString(USVString(s.to_string())) + }, + FormDatumValue::File(ref b) => { + FileOrUSVString::File(DomRoot::from_ref(&*b)) + }, }).collect() - ) + }) } // https://xhr.spec.whatwg.org/#dom-formdata-has @@ -125,26 +146,32 @@ impl FormDataMethods for FormData { // https://xhr.spec.whatwg.org/#dom-formdata-set fn Set(&self, name: USVString, str_value: USVString) { - self.data.borrow_mut().insert(LocalName::from(name.0.clone()), vec![FormDatum { - ty: DOMString::from("string"), - name: DOMString::from(name.0), - value: FormDatumValue::String(DOMString::from(str_value.0)), - }]); + self.data.borrow_mut().insert( + LocalName::from(name.0.clone()), + vec![FormDatum { + ty: DOMString::from("string"), + name: DOMString::from(name.0), + value: FormDatumValue::String(DOMString::from(str_value.0)), + }], + ); } #[allow(unrooted_must_root)] // https://xhr.spec.whatwg.org/#dom-formdata-set fn Set_(&self, name: USVString, blob: &Blob, filename: Option<USVString>) { - self.data.borrow_mut().insert(LocalName::from(name.0.clone()), vec![FormDatum { - ty: DOMString::from("file"), - name: DOMString::from(name.0), - value: FormDatumValue::File(DomRoot::from_ref(&*self.create_an_entry(blob, filename))), - }]); + self.data.borrow_mut().insert( + LocalName::from(name.0.clone()), + vec![FormDatum { + ty: DOMString::from("file"), + name: DOMString::from(name.0), + value: FormDatumValue::File(DomRoot::from_ref( + &*self.create_an_entry(blob, filename), + )), + }], + ); } - } - impl FormData { // https://xhr.spec.whatwg.org/#create-an-entry // Steps 3-4. @@ -157,11 +184,19 @@ impl FormData { let bytes = blob.get_bytes().unwrap_or(vec![]); - File::new(&self.global(), BlobImpl::new_from_bytes(bytes), name, None, &blob.type_string()) + File::new( + &self.global(), + BlobImpl::new_from_bytes(bytes), + name, + None, + &blob.type_string(), + ) } pub fn datums(&self) -> Vec<FormDatum> { - self.data.borrow().values() + self.data + .borrow() + .values() .flat_map(|value| value.iter()) .map(|value| value.clone()) .collect() @@ -173,16 +208,21 @@ impl Iterable for FormData { type Value = FileOrUSVString; fn get_iterable_length(&self) -> u32 { - self.data.borrow().values().map(|value| value.len()).sum::<usize>() as u32 + self.data + .borrow() + .values() + .map(|value| value.len()) + .sum::<usize>() as u32 } fn get_value_at_index(&self, n: u32) -> FileOrUSVString { let data = self.data.borrow(); - let value = &data.values() - .flat_map(|value| value.iter()) - .nth(n as usize) - .unwrap() - .value; + let value = &data + .values() + .flat_map(|value| value.iter()) + .nth(n as usize) + .unwrap() + .value; match *value { FormDatumValue::String(ref s) => FileOrUSVString::USVString(USVString(s.to_string())), FormDatumValue::File(ref b) => FileOrUSVString::File(DomRoot::from_ref(&*b)), @@ -191,10 +231,11 @@ impl Iterable for FormData { fn get_key_at_index(&self, n: u32) -> USVString { let data = self.data.borrow(); - let value = &data.iter() - .flat_map(|(key, value)| iter::repeat(key).take(value.len())) - .nth(n as usize) - .unwrap(); + let value = &data + .iter() + .flat_map(|(key, value)| iter::repeat(key).take(value.len())) + .nth(n as usize) + .unwrap(); USVString(value.to_string()) } } diff --git a/components/script/dom/gainnode.rs b/components/script/dom/gainnode.rs index 1b4859e28e5..ea81ac58535 100644 --- a/components/script/dom/gainnode.rs +++ b/components/script/dom/gainnode.rs @@ -31,9 +31,10 @@ impl GainNode { context: &BaseAudioContext, options: &GainOptions, ) -> Fallible<GainNode> { - let node_options = options.parent - .unwrap_or(2, ChannelCountMode::Max, - ChannelInterpretation::Speakers); + let node_options = + options + .parent + .unwrap_or(2, ChannelCountMode::Max, ChannelInterpretation::Speakers); let node = AudioNode::new_inherited( AudioNodeInit::GainNode(options.into()), context, @@ -64,7 +65,11 @@ impl GainNode { options: &GainOptions, ) -> Fallible<DomRoot<GainNode>> { let node = GainNode::new_inherited(window, context, options)?; - Ok(reflect_dom_object(Box::new(node), window, GainNodeBinding::Wrap)) + Ok(reflect_dom_object( + Box::new(node), + window, + GainNodeBinding::Wrap, + )) } pub fn Constructor( diff --git a/components/script/dom/gamepad.rs b/components/script/dom/gamepad.rs index 769b1ee548f..d4858de99f8 100644 --- a/components/script/dom/gamepad.rs +++ b/components/script/dom/gamepad.rs @@ -37,20 +37,22 @@ pub struct Gamepad { pose: Option<Dom<VRPose>>, #[ignore_malloc_size_of = "Defined in rust-webvr"] hand: WebVRGamepadHand, - display_id: u32 + display_id: u32, } impl Gamepad { - fn new_inherited(gamepad_id: u32, - id: String, - index: i32, - connected: bool, - timestamp: f64, - mapping_type: String, - buttons: &GamepadButtonList, - pose: Option<&VRPose>, - hand: WebVRGamepadHand, - display_id: u32) -> Gamepad { + fn new_inherited( + gamepad_id: u32, + id: String, + index: i32, + connected: bool, + timestamp: f64, + mapping_type: String, + buttons: &GamepadButtonList, + pose: Option<&VRPose>, + hand: WebVRGamepadHand, + display_id: u32, + ) -> Gamepad { Self { reflector_: Reflector::new(), gamepad_id: gamepad_id, @@ -63,15 +65,17 @@ impl Gamepad { buttons: Dom::from_ref(buttons), pose: pose.map(Dom::from_ref), hand: hand, - display_id: display_id + display_id: display_id, } } #[allow(unsafe_code)] - pub fn new_from_vr(global: &GlobalScope, - index: i32, - data: &WebVRGamepadData, - state: &WebVRGamepadState) -> DomRoot<Gamepad> { + pub fn new_from_vr( + global: &GlobalScope, + index: i32, + data: &WebVRGamepadData, + state: &WebVRGamepadState, + ) -> DomRoot<Gamepad> { let buttons = GamepadButtonList::new_from_vr(&global, &state.buttons); let pose = VRPose::new(&global, &state.pose); @@ -86,10 +90,10 @@ impl Gamepad { &buttons, Some(&pose), data.hand.clone(), - data.display_id + data.display_id, )), global, - GamepadBinding::Wrap + GamepadBinding::Wrap, ); let cx = global.get_cx(); @@ -145,7 +149,7 @@ impl GamepadMethods for Gamepad { let value = match self.hand { WebVRGamepadHand::Unknown => "", WebVRGamepadHand::Left => "left", - WebVRGamepadHand::Right => "right" + WebVRGamepadHand::Right => "right", }; value.into() } @@ -204,6 +208,8 @@ impl Gamepad { pub fn notify_event(&self, event_type: GamepadEventType) { let event = GamepadEvent::new_with_type(&self.global(), event_type, &self); - event.upcast::<Event>().fire(self.global().as_window().upcast::<EventTarget>()); + event + .upcast::<Event>() + .fire(self.global().as_window().upcast::<EventTarget>()); } } diff --git a/components/script/dom/gamepadbutton.rs b/components/script/dom/gamepadbutton.rs index fb5182b7cda..df28f9e6a8e 100644 --- a/components/script/dom/gamepadbutton.rs +++ b/components/script/dom/gamepadbutton.rs @@ -30,9 +30,11 @@ impl GamepadButton { } pub fn new(global: &GlobalScope, pressed: bool, touched: bool) -> DomRoot<GamepadButton> { - reflect_dom_object(Box::new(GamepadButton::new_inherited(pressed, touched)), - global, - GamepadButtonBinding::Wrap) + reflect_dom_object( + Box::new(GamepadButton::new_inherited(pressed, touched)), + global, + GamepadButtonBinding::Wrap, + ) } } diff --git a/components/script/dom/gamepadbuttonlist.rs b/components/script/dom/gamepadbuttonlist.rs index 24afa3b1bfe..22e79c98100 100644 --- a/components/script/dom/gamepadbuttonlist.rs +++ b/components/script/dom/gamepadbuttonlist.rs @@ -15,7 +15,7 @@ use webvr_traits::WebVRGamepadButton; #[dom_struct] pub struct GamepadButtonList { reflector_: Reflector, - list: Vec<Dom<GamepadButton>> + list: Vec<Dom<GamepadButton>>, } impl GamepadButtonList { @@ -27,13 +27,18 @@ impl GamepadButtonList { } } - pub fn new_from_vr(global: &GlobalScope, buttons: &[WebVRGamepadButton]) -> DomRoot<GamepadButtonList> { + pub fn new_from_vr( + global: &GlobalScope, + buttons: &[WebVRGamepadButton], + ) -> DomRoot<GamepadButtonList> { rooted_vec!(let list <- buttons.iter() .map(|btn| GamepadButton::new(&global, btn.pressed, btn.touched))); - reflect_dom_object(Box::new(GamepadButtonList::new_inherited(list.r())), - global, - GamepadButtonListBinding::Wrap) + reflect_dom_object( + Box::new(GamepadButtonList::new_inherited(list.r())), + global, + GamepadButtonListBinding::Wrap, + ) } pub fn sync_from_vr(&self, vr_buttons: &[WebVRGamepadButton]) { @@ -51,7 +56,9 @@ impl GamepadButtonListMethods for GamepadButtonList { // https://w3c.github.io/gamepad/#dom-gamepad-buttons fn Item(&self, index: u32) -> Option<DomRoot<GamepadButton>> { - self.list.get(index as usize).map(|button| DomRoot::from_ref(&**button)) + self.list + .get(index as usize) + .map(|button| DomRoot::from_ref(&**button)) } // https://w3c.github.io/gamepad/#dom-gamepad-buttons diff --git a/components/script/dom/gamepadevent.rs b/components/script/dom/gamepadevent.rs index f3badfdb8c4..b8bd371f088 100644 --- a/components/script/dom/gamepadevent.rs +++ b/components/script/dom/gamepadevent.rs @@ -25,7 +25,7 @@ pub struct GamepadEvent { pub enum GamepadEventType { Connected, - Disconnected + Disconnected, } impl GamepadEvent { @@ -36,14 +36,17 @@ impl GamepadEvent { } } - pub fn new(global: &GlobalScope, - type_: Atom, - bubbles: bool, - cancelable: bool, - gamepad: &Gamepad) - -> DomRoot<GamepadEvent> { + pub fn new( + global: &GlobalScope, + type_: Atom, + bubbles: bool, + cancelable: bool, + gamepad: &Gamepad, + ) -> DomRoot<GamepadEvent> { let ev = reflect_dom_object( - Box::new(GamepadEvent::new_inherited(&gamepad)), global, GamepadEventBinding::Wrap + Box::new(GamepadEvent::new_inherited(&gamepad)), + global, + GamepadEventBinding::Wrap, ); { let event = ev.upcast::<Event>(); @@ -52,30 +55,32 @@ impl GamepadEvent { ev } - pub fn new_with_type(global: &GlobalScope, event_type: GamepadEventType, gamepad: &Gamepad) - -> DomRoot<GamepadEvent> { + pub fn new_with_type( + global: &GlobalScope, + event_type: GamepadEventType, + gamepad: &Gamepad, + ) -> DomRoot<GamepadEvent> { let name = match event_type { GamepadEventType::Connected => "gamepadconnected", - GamepadEventType::Disconnected => "gamepaddisconnected" + GamepadEventType::Disconnected => "gamepaddisconnected", }; - GamepadEvent::new(&global, - name.into(), - false, - false, - &gamepad) + GamepadEvent::new(&global, name.into(), false, false, &gamepad) } // https://w3c.github.io/gamepad/#gamepadevent-interface - pub fn Constructor(window: &Window, - type_: DOMString, - init: &GamepadEventBinding::GamepadEventInit) - -> Fallible<DomRoot<GamepadEvent>> { - Ok(GamepadEvent::new(&window.global(), - Atom::from(type_), - init.parent.bubbles, - init.parent.cancelable, - &init.gamepad)) + pub fn Constructor( + window: &Window, + type_: DOMString, + init: &GamepadEventBinding::GamepadEventInit, + ) -> Fallible<DomRoot<GamepadEvent>> { + Ok(GamepadEvent::new( + &window.global(), + Atom::from(type_), + init.parent.bubbles, + init.parent.cancelable, + &init.gamepad, + )) } } diff --git a/components/script/dom/gamepadlist.rs b/components/script/dom/gamepadlist.rs index f767d001343..1e48e7560ea 100644 --- a/components/script/dom/gamepadlist.rs +++ b/components/script/dom/gamepadlist.rs @@ -15,26 +15,33 @@ use dom_struct::dom_struct; #[dom_struct] pub struct GamepadList { reflector_: Reflector, - list: DomRefCell<Vec<Dom<Gamepad>>> + list: DomRefCell<Vec<Dom<Gamepad>>>, } impl GamepadList { fn new_inherited(list: &[&Gamepad]) -> GamepadList { GamepadList { reflector_: Reflector::new(), - list: DomRefCell::new(list.iter().map(|g| Dom::from_ref(&**g)).collect()) + list: DomRefCell::new(list.iter().map(|g| Dom::from_ref(&**g)).collect()), } } pub fn new(global: &GlobalScope, list: &[&Gamepad]) -> DomRoot<GamepadList> { - reflect_dom_object(Box::new(GamepadList::new_inherited(list)), - global, - GamepadListBinding::Wrap) + reflect_dom_object( + Box::new(GamepadList::new_inherited(list)), + global, + GamepadListBinding::Wrap, + ) } pub fn add_if_not_exists(&self, gamepads: &[DomRoot<Gamepad>]) { for gamepad in gamepads { - if !self.list.borrow().iter().any(|g| g.gamepad_id() == gamepad.gamepad_id()) { + if !self + .list + .borrow() + .iter() + .any(|g| g.gamepad_id() == gamepad.gamepad_id()) + { self.list.borrow_mut().push(Dom::from_ref(&*gamepad)); // Ensure that the gamepad has the correct index gamepad.update_index(self.list.borrow().len() as i32 - 1); @@ -51,7 +58,10 @@ impl GamepadListMethods for GamepadList { // https://w3c.github.io/gamepad/#dom-navigator-getgamepads fn Item(&self, index: u32) -> Option<DomRoot<Gamepad>> { - self.list.borrow().get(index as usize).map(|gamepad| DomRoot::from_ref(&**gamepad)) + self.list + .borrow() + .get(index as usize) + .map(|gamepad| DomRoot::from_ref(&**gamepad)) } // https://w3c.github.io/gamepad/#dom-navigator-getgamepads diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index b2429948874..62eae2dedae 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -65,9 +65,7 @@ use timers::{IsInterval, OneshotTimerCallback, OneshotTimerHandle}; use timers::{OneshotTimers, TimerCallback}; #[derive(JSTraceable)] -pub struct AutoCloseWorker( - Arc<AtomicBool>, -); +pub struct AutoCloseWorker(Arc<AtomicBool>); impl Drop for AutoCloseWorker { fn drop(&mut self) { @@ -175,7 +173,9 @@ impl GlobalScope { } pub fn track_worker(&self, closing_worker: Arc<AtomicBool>) { - self.list_auto_close_worker.borrow_mut().push(AutoCloseWorker(closing_worker)); + self.list_auto_close_worker + .borrow_mut() + .push(AutoCloseWorker(closing_worker)); } pub fn track_event_source(&self, event_source: &EventSource) { @@ -184,15 +184,16 @@ impl GlobalScope { pub fn close_event_sources(&self) -> bool { let mut canceled_any_fetch = false; - self.event_source_tracker.for_each(|event_source: DomRoot<EventSource>| { - match event_source.ReadyState() { - 2 => {}, - _ => { - event_source.cancel(); - canceled_any_fetch = true; - } - } - }); + self.event_source_tracker + .for_each( + |event_source: DomRoot<EventSource>| match event_source.ReadyState() { + 2 => {}, + _ => { + event_source.cancel(); + canceled_any_fetch = true; + }, + }, + ); canceled_any_fetch } @@ -268,9 +269,11 @@ impl GlobalScope { } pub fn time_end(&self, label: &str) -> Result<u64, ()> { - self.console_timers.borrow_mut().remove(label).ok_or(()).map(|start| { - timestamp_in_ms(get_time()) - start - }) + self.console_timers + .borrow_mut() + .remove(label) + .ok_or(()) + .map(|start| timestamp_in_ms(get_time()) - start) } /// Get an `&IpcSender<ScriptToDevtoolsControlMsg>` to send messages @@ -383,7 +386,6 @@ impl GlobalScope { dedicated.forward_error_to_worker_object(error_info); } } - } /// Get the `&ResourceThreads` for this global scope. @@ -444,15 +446,19 @@ impl GlobalScope { } /// Evaluate JS code on this global scope. - pub fn evaluate_js_on_global_with_result( - &self, code: &str, rval: MutableHandleValue) -> bool { + pub fn evaluate_js_on_global_with_result(&self, code: &str, rval: MutableHandleValue) -> bool { self.evaluate_script_on_global_with_result(code, "", rval, 1) } /// Evaluate a JS script on this global scope. #[allow(unsafe_code)] pub fn evaluate_script_on_global_with_result( - &self, code: &str, filename: &str, rval: MutableHandleValue, line_number: u32) -> bool { + &self, + code: &str, + filename: &str, + rval: MutableHandleValue, + line_number: u32, + ) -> bool { let metadata = time::TimerMetadata { url: if filename.is_empty() { self.get_url().as_str().into() @@ -478,9 +484,13 @@ impl GlobalScope { debug!("evaluating Dom string"); let result = unsafe { - Evaluate2(cx, options.ptr, code.as_ptr(), - code.len() as libc::size_t, - rval) + Evaluate2( + cx, + options.ptr, + code.as_ptr(), + code.len() as libc::size_t, + rval, + ) }; if !result { @@ -490,14 +500,17 @@ impl GlobalScope { maybe_resume_unwind(); result - } + }, ) } pub fn schedule_callback( - &self, callback: OneshotTimerCallback, duration: MsDuration) - -> OneshotTimerHandle { - self.timers.schedule_callback(callback, duration, self.timer_source()) + &self, + callback: OneshotTimerCallback, + duration: MsDuration, + ) -> OneshotTimerHandle { + self.timers + .schedule_callback(callback, duration, self.timer_source()) } pub fn unschedule_callback(&self, handle: OneshotTimerHandle) { @@ -505,14 +518,20 @@ impl GlobalScope { } pub fn set_timeout_or_interval( - &self, - callback: TimerCallback, - arguments: Vec<HandleValue>, - timeout: i32, - is_interval: IsInterval) - -> i32 { + &self, + callback: TimerCallback, + arguments: Vec<HandleValue>, + timeout: i32, + is_interval: IsInterval, + ) -> i32 { self.timers.set_timeout_or_interval( - self, callback, arguments, timeout, is_interval, self.timer_source()) + self, + callback, + arguments, + timeout, + is_interval, + self.timer_source(), + ) } pub fn clear_timeout_or_interval(&self, handle: i32) { @@ -566,7 +585,8 @@ impl GlobalScope { /// Perform a microtask checkpoint. pub fn perform_a_microtask_checkpoint(&self) { - self.microtask_queue.checkpoint(|_| Some(DomRoot::from_ref(self))); + self.microtask_queue + .checkpoint(|_| Some(DomRoot::from_ref(self))); } /// Enqueue a microtask for subsequent execution. @@ -668,7 +688,6 @@ impl GlobalScope { } unreachable!(); } - } fn timestamp_in_ms(time: Timespec) -> u64 { @@ -680,6 +699,9 @@ fn timestamp_in_ms(time: Timespec) -> u64 { unsafe fn global_scope_from_global(global: *mut JSObject) -> DomRoot<GlobalScope> { assert!(!global.is_null()); let clasp = get_object_class(global); - assert_ne!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)), 0); + assert_ne!( + ((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)), + 0 + ); root_from_object(global).unwrap() } diff --git a/components/script/dom/hashchangeevent.rs b/components/script/dom/hashchangeevent.rs index 98314305fd4..e32c64a779f 100644 --- a/components/script/dom/hashchangeevent.rs +++ b/components/script/dom/hashchangeevent.rs @@ -33,21 +33,26 @@ impl HashChangeEvent { } pub fn new_uninitialized(window: &Window) -> DomRoot<HashChangeEvent> { - reflect_dom_object(Box::new(HashChangeEvent::new_inherited(String::new(), String::new())), - window, - HashChangeEventBinding::Wrap) + reflect_dom_object( + Box::new(HashChangeEvent::new_inherited(String::new(), String::new())), + window, + HashChangeEventBinding::Wrap, + ) } - pub fn new(window: &Window, - type_: Atom, - bubbles: bool, - cancelable: bool, - old_url: String, - new_url: String) - -> DomRoot<HashChangeEvent> { - let ev = reflect_dom_object(Box::new(HashChangeEvent::new_inherited(old_url, new_url)), - window, - HashChangeEventBinding::Wrap); + pub fn new( + window: &Window, + type_: Atom, + bubbles: bool, + cancelable: bool, + old_url: String, + new_url: String, + ) -> DomRoot<HashChangeEvent> { + let ev = reflect_dom_object( + Box::new(HashChangeEvent::new_inherited(old_url, new_url)), + window, + HashChangeEventBinding::Wrap, + ); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); @@ -55,16 +60,19 @@ impl HashChangeEvent { ev } - pub fn Constructor(window: &Window, - type_: DOMString, - init: &HashChangeEventBinding::HashChangeEventInit) - -> Fallible<DomRoot<HashChangeEvent>> { - Ok(HashChangeEvent::new(window, - Atom::from(type_), - init.parent.bubbles, - init.parent.cancelable, - init.oldURL.0.clone(), - init.newURL.0.clone())) + pub fn Constructor( + window: &Window, + type_: DOMString, + init: &HashChangeEventBinding::HashChangeEventInit, + ) -> Fallible<DomRoot<HashChangeEvent>> { + Ok(HashChangeEvent::new( + window, + Atom::from(type_), + init.parent.bubbles, + init.parent.cancelable, + init.oldURL.0.clone(), + init.newURL.0.clone(), + )) } } diff --git a/components/script/dom/headers.rs b/components/script/dom/headers.rs index b351e2b7f13..9ff08e7c07a 100644 --- a/components/script/dom/headers.rs +++ b/components/script/dom/headers.rs @@ -22,7 +22,7 @@ pub struct Headers { reflector_: Reflector, guard: Cell<Guard>, #[ignore_malloc_size_of = "Defined in hyper"] - header_list: DomRefCell<HyperHeaders> + header_list: DomRefCell<HyperHeaders>, } // https://fetch.spec.whatwg.org/#concept-headers-guard @@ -49,8 +49,10 @@ impl Headers { } // https://fetch.spec.whatwg.org/#dom-headers - pub fn Constructor(global: &GlobalScope, init: Option<HeadersInit>) - -> Fallible<DomRoot<Headers>> { + pub fn Constructor( + global: &GlobalScope, + init: Option<HeadersInit>, + ) -> Fallible<DomRoot<Headers>> { let dom_headers_new = Headers::new(global); dom_headers_new.fill(init)?; Ok(dom_headers_new) @@ -74,7 +76,9 @@ impl HeadersMethods for Headers { return Ok(()); } // Step 5 - if self.guard.get() == Guard::RequestNoCors && !is_cors_safelisted_request_header(&valid_name, &valid_value) { + if self.guard.get() == Guard::RequestNoCors && + !is_cors_safelisted_request_header(&valid_name, &valid_value) + { return Ok(()); } // Step 6 @@ -88,7 +92,9 @@ impl HeadersMethods for Headers { combined_value.push(b','); } combined_value.extend(valid_value.iter().cloned()); - self.header_list.borrow_mut().set_raw(valid_name, vec![combined_value]); + self.header_list + .borrow_mut() + .set_raw(valid_name, vec![combined_value]); Ok(()) } @@ -106,9 +112,10 @@ impl HeadersMethods for Headers { } // Step 4 if self.guard.get() == Guard::RequestNoCors && - !is_cors_safelisted_request_header(&valid_name, &b"invalid".to_vec()) { - return Ok(()); - } + !is_cors_safelisted_request_header(&valid_name, &b"invalid".to_vec()) + { + return Ok(()); + } // Step 5 if self.guard.get() == Guard::Response && is_forbidden_response_header(&valid_name) { return Ok(()); @@ -122,9 +129,11 @@ impl HeadersMethods for Headers { fn Get(&self, name: ByteString) -> Fallible<Option<ByteString>> { // Step 1 let valid_name = &validate_name(name)?; - Ok(self.header_list.borrow().get_raw(&valid_name).map(|v| { - ByteString::new(v[0].clone()) - })) + Ok(self + .header_list + .borrow() + .get_raw(&valid_name) + .map(|v| ByteString::new(v[0].clone()))) } // https://fetch.spec.whatwg.org/#dom-headers-has @@ -151,7 +160,9 @@ impl HeadersMethods for Headers { return Ok(()); } // Step 5 - if self.guard.get() == Guard::RequestNoCors && !is_cors_safelisted_request_header(&valid_name, &valid_value) { + if self.guard.get() == Guard::RequestNoCors && + !is_cors_safelisted_request_header(&valid_name, &valid_value) + { return Ok(()); } // Step 6 @@ -160,7 +171,9 @@ impl HeadersMethods for Headers { } // Step 7 // https://fetch.spec.whatwg.org/#concept-header-list-set - self.header_list.borrow_mut().set_raw(valid_name, vec![valid_value]); + self.header_list + .borrow_mut() + .set_raw(valid_name, vec![valid_value]); Ok(()) } } @@ -174,7 +187,7 @@ impl Headers { for header in h.header_list.borrow().iter() { self.Append( ByteString::new(Vec::from(header.name())), - ByteString::new(Vec::from(header.value_string().into_bytes())) + ByteString::new(Vec::from(header.value_string().into_bytes())), )?; } Ok(()) @@ -242,7 +255,10 @@ impl Headers { // https://fetch.spec.whatwg.org/#concept-header-extract-mime-type pub fn extract_mime_type(&self) -> Vec<u8> { - self.header_list.borrow().get_raw("content-type").map_or(vec![], |v| v[0].clone()) + self.header_list + .borrow() + .get_raw("content-type") + .map_or(vec![], |v| v[0].clone()) } pub fn sort_header_list(&self) -> Vec<(String, String)> { @@ -290,14 +306,12 @@ fn is_cors_safelisted_request_content_type(value: &[u8]) -> bool { let value_mime_result: Result<Mime, _> = value_string.parse(); match value_mime_result { Err(_) => false, - Ok(value_mime) => { - match value_mime { - Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, _) | - Mime(TopLevel::Multipart, SubLevel::FormData, _) | - Mime(TopLevel::Text, SubLevel::Plain, _) => true, - _ => false, - } - } + Ok(value_mime) => match value_mime { + Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, _) | + Mime(TopLevel::Multipart, SubLevel::FormData, _) | + Mime(TopLevel::Text, SubLevel::Plain, _) => true, + _ => false, + }, } } @@ -306,9 +320,7 @@ fn is_cors_safelisted_request_content_type(value: &[u8]) -> bool { // https://fetch.spec.whatwg.org/#cors-safelisted-request-header fn is_cors_safelisted_request_header(name: &str, value: &[u8]) -> bool { match name { - "accept" | - "accept-language" | - "content-language" => true, + "accept" | "accept-language" | "content-language" => true, "content-type" => is_cors_safelisted_request_content_type(value), _ => false, } @@ -317,28 +329,41 @@ fn is_cors_safelisted_request_header(name: &str, value: &[u8]) -> bool { // https://fetch.spec.whatwg.org/#forbidden-response-header-name fn is_forbidden_response_header(name: &str) -> bool { match name { - "set-cookie" | - "set-cookie2" => true, + "set-cookie" | "set-cookie2" => true, _ => false, } } // https://fetch.spec.whatwg.org/#forbidden-header-name pub fn is_forbidden_header_name(name: &str) -> bool { - let disallowed_headers = - ["accept-charset", "accept-encoding", - "access-control-request-headers", - "access-control-request-method", - "connection", "content-length", - "cookie", "cookie2", "date", "dnt", - "expect", "host", "keep-alive", "origin", - "referer", "te", "trailer", "transfer-encoding", - "upgrade", "via"]; + let disallowed_headers = [ + "accept-charset", + "accept-encoding", + "access-control-request-headers", + "access-control-request-method", + "connection", + "content-length", + "cookie", + "cookie2", + "date", + "dnt", + "expect", + "host", + "keep-alive", + "origin", + "referer", + "te", + "trailer", + "transfer-encoding", + "upgrade", + "via", + ]; let disallowed_header_prefixes = ["sec-", "proxy-"]; - disallowed_headers.iter().any(|header| *header == name) || - disallowed_header_prefixes.iter().any(|prefix| name.starts_with(prefix)) + disallowed_headers.iter().any(|header| *header == name) || disallowed_header_prefixes + .iter() + .any(|prefix| name.starts_with(prefix)) } // There is some unresolved confusion over the definition of a name and a value. @@ -364,8 +389,7 @@ pub fn is_forbidden_header_name(name: &str) -> bool { // [2] https://tools.ietf.org/html/rfc7230#section-3.2 // [3] https://tools.ietf.org/html/rfc7230#section-3.2.6 // [4] https://www.rfc-editor.org/errata_search.php?rfc=7230 -fn validate_name_and_value(name: ByteString, value: ByteString) - -> Fallible<(String, Vec<u8>)> { +fn validate_name_and_value(name: ByteString, value: ByteString) -> Fallible<(String, Vec<u8>)> { let valid_name = validate_name(name)?; if !is_field_content(&value) { return Err(Error::Type("Value is not valid".to_string())); @@ -386,7 +410,10 @@ fn validate_name(name: ByteString) -> Fallible<String> { // Removes trailing and leading HTTP whitespace bytes. // https://fetch.spec.whatwg.org/#concept-header-value-normalize pub fn normalize_value(value: ByteString) -> ByteString { - match (index_of_first_non_whitespace(&value), index_of_last_non_whitespace(&value)) { + match ( + index_of_first_non_whitespace(&value), + index_of_last_non_whitespace(&value), + ) { (Some(begin), Some(end)) => ByteString::new(value[begin..end + 1].to_owned()), _ => ByteString::new(vec![]), } diff --git a/components/script/dom/history.rs b/components/script/dom/history.rs index 939cf9a8c20..ee5c38e8c89 100644 --- a/components/script/dom/history.rs +++ b/components/script/dom/history.rs @@ -57,9 +57,11 @@ impl History { } pub fn new(window: &Window) -> DomRoot<History> { - reflect_dom_object(Box::new(History::new_inherited(window)), - window, - HistoryBinding::Wrap) + reflect_dom_object( + Box::new(History::new_inherited(window)), + window, + HistoryBinding::Wrap, + ) } } @@ -69,7 +71,11 @@ impl History { return Err(Error::Security); } let msg = ScriptMsg::TraverseHistory(direction); - let _ = self.window.upcast::<GlobalScope>().script_to_constellation_chan().send(msg); + let _ = self + .window + .upcast::<GlobalScope>() + .script_to_constellation_chan() + .send(msg); Ok(()) } @@ -83,7 +89,7 @@ impl History { document.set_url(url.clone()); // Step 6 - let hash_changed = old_url.fragment() != url.fragment(); + let hash_changed = old_url.fragment() != url.fragment(); // Step 8 if let Some(fragment) = url.fragment() { @@ -96,7 +102,8 @@ impl History { let serialized_data = match state_id { Some(state_id) => { let (tx, rx) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); - let _ = self.window + let _ = self + .window .upcast::<GlobalScope>() .resource_threads() .send(CoreResourceMsg::GetHistoryState(state_id, tx)); @@ -109,12 +116,13 @@ impl History { Some(serialized_data) => { let global_scope = self.window.upcast::<GlobalScope>(); rooted!(in(global_scope.get_cx()) let mut state = UndefinedValue()); - StructuredCloneData::Vector(serialized_data).read(&global_scope, state.handle_mut()); + StructuredCloneData::Vector(serialized_data) + .read(&global_scope, state.handle_mut()); self.state.set(state.get()); }, None => { self.state.set(NullValue()); - } + }, } // TODO: Queue events on DOM Manipulation task source if non-blocking flag is set. @@ -123,7 +131,7 @@ impl History { PopStateEvent::dispatch_jsval( self.window.upcast::<EventTarget>(), &*self.window, - unsafe { HandleValue::from_raw(self.state.handle()) } + unsafe { HandleValue::from_raw(self.state.handle()) }, ); } @@ -135,13 +143,17 @@ impl History { false, false, old_url.into_string(), - url.into_string()); - event.upcast::<Event>().fire(self.window.upcast::<EventTarget>()); + url.into_string(), + ); + event + .upcast::<Event>() + .fire(self.window.upcast::<EventTarget>()); } } pub fn remove_states(&self, states: Vec<HistoryStateId>) { - let _ = self.window + let _ = self + .window .upcast::<GlobalScope>() .resource_threads() .send(CoreResourceMsg::RemoveHistoryStates(states)); @@ -149,12 +161,14 @@ impl History { // https://html.spec.whatwg.org/multipage/#dom-history-pushstate // https://html.spec.whatwg.org/multipage/#dom-history-replacestate - fn push_or_replace_state(&self, - cx: *mut JSContext, - data: HandleValue, - _title: DOMString, - url: Option<USVString>, - push_or_replace: PushOrReplace) -> ErrorResult { + fn push_or_replace_state( + &self, + cx: *mut JSContext, + data: HandleValue, + _title: DOMString, + url: Option<USVString>, + push_or_replace: PushOrReplace, + ) -> ErrorResult { // Step 1 let document = self.window.Document(); @@ -186,10 +200,10 @@ impl History { // Step 6.4 if new_url.scheme() != document_url.scheme() || - new_url.host() != document_url.host() || - new_url.port() != document_url.port() || - new_url.username() != document_url.username() || - new_url.password() != document_url.password() + new_url.host() != document_url.host() || + new_url.port() != document_url.port() || + new_url.username() != document_url.username() || + new_url.password() != document_url.password() { return Err(Error::Security); } @@ -202,9 +216,7 @@ impl History { new_url }, // Step 7 - None => { - document.url() - } + None => document.url(), }; // Step 8 @@ -213,7 +225,11 @@ impl History { let state_id = HistoryStateId::new(); self.state_id.set(Some(state_id)); let msg = ScriptMsg::PushHistoryState(state_id, new_url.clone()); - let _ = self.window.upcast::<GlobalScope>().script_to_constellation_chan().send(msg); + let _ = self + .window + .upcast::<GlobalScope>() + .script_to_constellation_chan() + .send(msg); state_id }, PushOrReplace::Replace => { @@ -226,16 +242,18 @@ impl History { }, }; let msg = ScriptMsg::ReplaceHistoryState(state_id, new_url.clone()); - let _ = self.window.upcast::<GlobalScope>().script_to_constellation_chan().send(msg); + let _ = self + .window + .upcast::<GlobalScope>() + .script_to_constellation_chan() + .send(msg); state_id }, }; - let _ = self.window - .upcast::<GlobalScope>() - .resource_threads() - .send(CoreResourceMsg::SetHistoryState(state_id, serialized_data.clone())); - + let _ = self.window.upcast::<GlobalScope>().resource_threads().send( + CoreResourceMsg::SetHistoryState(state_id, serialized_data.clone()), + ); // TODO: Step 9 Update current entry to represent a GET request // https://github.com/servo/servo/issues/19156 @@ -273,10 +291,14 @@ impl HistoryMethods for History { if !self.window.Document().is_fully_active() { return Err(Error::Security); } - let (sender, recv) = - channel(self.global().time_profiler_chan().clone()).expect("Failed to create channel to send jsh length."); + let (sender, recv) = channel(self.global().time_profiler_chan().clone()) + .expect("Failed to create channel to send jsh length."); let msg = ScriptMsg::JointSessionHistoryLength(sender); - let _ = self.window.upcast::<GlobalScope>().script_to_constellation_chan().send(msg); + let _ = self + .window + .upcast::<GlobalScope>() + .script_to_constellation_chan() + .send(msg); Ok(recv.recv().unwrap()) } @@ -305,21 +327,25 @@ impl HistoryMethods for History { // https://html.spec.whatwg.org/multipage/#dom-history-pushstate #[allow(unsafe_code)] - unsafe fn PushState(&self, - cx: *mut JSContext, - data: HandleValue, - title: DOMString, - url: Option<USVString>) -> ErrorResult { + unsafe fn PushState( + &self, + cx: *mut JSContext, + data: HandleValue, + title: DOMString, + url: Option<USVString>, + ) -> ErrorResult { self.push_or_replace_state(cx, data, title, url, PushOrReplace::Push) } // https://html.spec.whatwg.org/multipage/#dom-history-replacestate #[allow(unsafe_code)] - unsafe fn ReplaceState(&self, - cx: *mut JSContext, - data: HandleValue, - title: DOMString, - url: Option<USVString>) -> ErrorResult { + unsafe fn ReplaceState( + &self, + cx: *mut JSContext, + data: HandleValue, + title: DOMString, + url: Option<USVString>, + ) -> ErrorResult { self.push_or_replace_state(cx, data, title, url, PushOrReplace::Replace) } } diff --git a/components/script/dom/htmlanchorelement.rs b/components/script/dom/htmlanchorelement.rs index 657ed992441..f813a4026f4 100644 --- a/components/script/dom/htmlanchorelement.rs +++ b/components/script/dom/htmlanchorelement.rs @@ -40,29 +40,38 @@ pub struct HTMLAnchorElement { } impl HTMLAnchorElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLAnchorElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLAnchorElement { HTMLAnchorElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document), + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), rel_list: Default::default(), url: DomRefCell::new(None), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLAnchorElement> { - Node::reflect_node(Box::new(HTMLAnchorElement::new_inherited(local_name, prefix, document)), - document, - HTMLAnchorElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLAnchorElement> { + Node::reflect_node( + Box::new(HTMLAnchorElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLAnchorElementBinding::Wrap, + ) } // https://html.spec.whatwg.org/multipage/#concept-hyperlink-url-set fn set_url(&self) { - let attribute = self.upcast::<Element>().get_attribute(&ns!(), &local_name!("href")); + let attribute = self + .upcast::<Element>() + .get_attribute(&ns!(), &local_name!("href")); *self.url.borrow_mut() = attribute.and_then(|attribute| { let document = document_from_node(self); document.base_url().join(&attribute.value()).ok() @@ -83,7 +92,8 @@ impl HTMLAnchorElement { // https://html.spec.whatwg.org/multipage/#update-href fn update_href(&self, url: DOMString) { - self.upcast::<Element>().set_string_attribute(&local_name!("href"), url); + self.upcast::<Element>() + .set_string_attribute(&local_name!("href"), url); } } @@ -95,7 +105,10 @@ impl VirtualMethods for HTMLAnchorElement { fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()), - _ => self.super_type().unwrap().parse_plain_attribute(name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(name, value), } } } @@ -116,12 +129,14 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { // https://html.spec.whatwg.org/multipage/#dom-a-rel fn SetRel(&self, rel: DOMString) { - self.upcast::<Element>().set_tokenlist_attribute(&local_name!("rel"), rel); + self.upcast::<Element>() + .set_tokenlist_attribute(&local_name!("rel"), rel); } // https://html.spec.whatwg.org/multipage/#dom-a-rellist fn RelList(&self) -> DomRoot<DOMTokenList> { - self.rel_list.or_init(|| DOMTokenList::new(self.upcast(), &local_name!("rel"))) + self.rel_list + .or_init(|| DOMTokenList::new(self.upcast(), &local_name!("rel"))) } // https://html.spec.whatwg.org/multipage/#dom-a-coords @@ -165,7 +180,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { Some(ref url) => { // Steps 3-4. UrlHelper::Hash(url) - } + }, } } @@ -183,7 +198,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { Some(url) => { UrlHelper::SetHash(url, value); DOMString::from(url.as_str()) - } + }, }; // Step 6. self.update_href(url); @@ -204,7 +219,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { // Steps 4-5. UrlHelper::Host(url) } - } + }, } } @@ -222,7 +237,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { Some(url) => { UrlHelper::SetHost(url, value); DOMString::from(url.as_str()) - } + }, }; // Step 5. self.update_href(url); @@ -239,7 +254,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { Some(ref url) => { // Step 4. UrlHelper::Hostname(url) - } + }, } } @@ -257,7 +272,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { Some(url) => { UrlHelper::SetHostname(url, value); DOMString::from(url.as_str()) - } + }, }; // Step 5. self.update_href(url); @@ -270,7 +285,10 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { USVString(match *self.url.borrow() { None => { - match self.upcast::<Element>().get_attribute(&ns!(), &local_name!("href")) { + match self + .upcast::<Element>() + .get_attribute(&ns!(), &local_name!("href")) + { // Step 3. None => String::new(), // Step 4. @@ -284,8 +302,8 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { // https://html.spec.whatwg.org/multipage/#dom-hyperlink-href fn SetHref(&self, value: USVString) { - self.upcast::<Element>().set_string_attribute(&local_name!("href"), - DOMString::from_string(value.0)); + self.upcast::<Element>() + .set_string_attribute(&local_name!("href"), DOMString::from_string(value.0)); self.set_url(); } @@ -315,13 +333,13 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { // Step 3. None => USVString(String::new()), // Steps 3-4. - Some(ref url) => UrlHelper::Password(url) + Some(ref url) => UrlHelper::Password(url), } } // https://html.spec.whatwg.org/multipage/#dom-hyperlink-password fn SetPassword(&self, value: USVString) { - // Step 1. + // Step 1. self.reinitialize_url(); // Step 2. @@ -333,7 +351,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { Some(url) => { UrlHelper::SetPassword(url, value); DOMString::from(url.as_str()) - } + }, }; // Step 5. self.update_href(url); @@ -341,14 +359,14 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { // https://html.spec.whatwg.org/multipage/#dom-hyperlink-pathname fn Pathname(&self) -> USVString { - // Step 1. + // Step 1. self.reinitialize_url(); match *self.url.borrow() { // Step 3. None => USVString(String::new()), // Steps 4-5. - Some(ref url) => UrlHelper::Pathname(url) + Some(ref url) => UrlHelper::Pathname(url), } } @@ -366,7 +384,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { Some(url) => { UrlHelper::SetPathname(url, value); DOMString::from(url.as_str()) - } + }, }; // Step 6. self.update_href(url); @@ -381,7 +399,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { // Step 3. None => USVString(String::new()), // Step 4. - Some(ref url) => UrlHelper::Port(url) + Some(ref url) => UrlHelper::Port(url), } } @@ -392,15 +410,17 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { // Step 3. let url = match self.url.borrow_mut().as_mut() { - Some(ref url) if url.host().is_none() || - url.cannot_be_a_base() || - url.scheme() == "file" => return, + Some(ref url) + if url.host().is_none() || url.cannot_be_a_base() || url.scheme() == "file" => + { + return + }, None => return, // Step 4. Some(url) => { UrlHelper::SetPort(url, value); DOMString::from(url.as_str()) - } + }, }; // Step 5. self.update_href(url); @@ -415,7 +435,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { // Step 2. None => USVString(":".to_owned()), // Step 3. - Some(ref url) => UrlHelper::Protocol(url) + Some(ref url) => UrlHelper::Protocol(url), } } @@ -431,7 +451,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { Some(url) => { UrlHelper::SetProtocol(url, value); DOMString::from(url.as_str()) - } + }, }; // Step 4. self.update_href(url); @@ -446,7 +466,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { // Step 2. None => USVString(String::new()), // Step 3. - Some(ref url) => UrlHelper::Search(url) + Some(ref url) => UrlHelper::Search(url), } } @@ -465,7 +485,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { Some(url) => { UrlHelper::SetSearch(url, value); DOMString::from(url.as_str()) - } + }, }; // Step 6. self.update_href(url); @@ -480,7 +500,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { // Step 2. None => USVString(String::new()), // Step 3. - Some(ref url) => UrlHelper::Username(url) + Some(ref url) => UrlHelper::Username(url), } } @@ -498,7 +518,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { Some(url) => { UrlHelper::SetUsername(url, value); DOMString::from(url.as_str()) - } + }, }; // Step 5. self.update_href(url); @@ -524,15 +544,12 @@ impl Activatable for HTMLAnchorElement { self.upcast::<Element>().has_attribute(&local_name!("href")) } - //TODO:https://html.spec.whatwg.org/multipage/#the-a-element - fn pre_click_activation(&self) { - } + fn pre_click_activation(&self) {} //TODO:https://html.spec.whatwg.org/multipage/#the-a-element // https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps - fn canceled_activation(&self) { - } + fn canceled_activation(&self) {} //https://html.spec.whatwg.org/multipage/#the-a-element:activation-behaviour fn activation_behavior(&self, event: &Event, target: &EventTarget) { @@ -550,10 +567,11 @@ impl Activatable for HTMLAnchorElement { if target.is::<HTMLImageElement>() && element.has_attribute(&local_name!("ismap")) { let target_node = element.upcast::<Node>(); let rect = target_node.bounding_content_box_or_zero(); - ismap_suffix = Some( - format!("?{},{}", mouse_event.ClientX().to_f32().unwrap() - rect.origin.x.to_f32_px(), - mouse_event.ClientY().to_f32().unwrap() - rect.origin.y.to_f32_px()) - ) + ismap_suffix = Some(format!( + "?{},{}", + mouse_event.ClientX().to_f32().unwrap() - rect.origin.x.to_f32_px(), + mouse_event.ClientY().to_f32().unwrap() - rect.origin.y.to_f32_px() + )) } } @@ -570,12 +588,22 @@ impl Activatable for HTMLAnchorElement { } //TODO:https://html.spec.whatwg.org/multipage/#the-a-element - fn implicit_submission(&self, _ctrl_key: bool, _shift_key: bool, _alt_key: bool, _meta_key: bool) { + fn implicit_submission( + &self, + _ctrl_key: bool, + _shift_key: bool, + _alt_key: bool, + _meta_key: bool, + ) { } } /// <https://html.spec.whatwg.org/multipage/#following-hyperlinks-2> -pub fn follow_hyperlink(subject: &Element, hyperlink_suffix: Option<String>, referrer_policy: Option<ReferrerPolicy>) { +pub fn follow_hyperlink( + subject: &Element, + hyperlink_suffix: Option<String>, + referrer_policy: Option<ReferrerPolicy>, +) { // Step 1: TODO: If subject cannot navigate, then return. // Step 2, done in Step 7. @@ -600,8 +628,8 @@ pub fn follow_hyperlink(subject: &Element, hyperlink_suffix: Option<String>, ref // Step 7. let (maybe_chosen, replace) = match target_attribute_value { - Some(name) => source.choose_browsing_context(name.Value(), noopener), - None => (Some(window.window_proxy()), false) + Some(name) => source.choose_browsing_context(name.Value(), noopener), + None => (Some(window.window_proxy()), false), }; let chosen = match maybe_chosen { Some(proxy) => proxy, diff --git a/components/script/dom/htmlareaelement.rs b/components/script/dom/htmlareaelement.rs index e7120a20e08..303b72a55f2 100644 --- a/components/script/dom/htmlareaelement.rs +++ b/components/script/dom/htmlareaelement.rs @@ -27,12 +27,20 @@ use std::f32; use std::str; use style::attr::AttrValue; -#[derive(PartialEq)] -#[derive(Debug)] +#[derive(Debug, PartialEq)] pub enum Area { - Circle { left: f32, top: f32, radius: f32 }, - Rectangle { top_left: (f32, f32), bottom_right: (f32, f32) }, - Polygon { points: Vec<f32> }, + Circle { + left: f32, + top: f32, + radius: f32, + }, + Rectangle { + top_left: (f32, f32), + bottom_right: (f32, f32), + }, + Polygon { + points: Vec<f32>, + }, } pub enum Shape { @@ -45,7 +53,7 @@ pub enum Shape { // https://html.spec.whatwg.org/multipage/#image-map-processing-model impl Area { pub fn parse(coord: &str, target: Shape) -> Option<Area> { - let points_count = match target { + let points_count = match target { Shape::Circle => 3, Shape::Rectangle => 4, Shape::Polygon => 0, @@ -59,7 +67,7 @@ impl Area { while index < size { let val = num[index]; match val { - b',' | b';' | b' ' | b'\t' | b'\n' | 0x0C | b'\r' => {}, + b',' | b';' | b' ' | b'\t' | b'\n' | 0x0C | b'\r' => {}, _ => break, } @@ -101,7 +109,10 @@ impl Area { } // Convert String to float - match str::from_utf8(&array).ok().and_then(|s| s.parse::<f32>().ok()) { + match str::from_utf8(&array) + .ok() + .and_then(|s| s.parse::<f32>().ok()) + { Some(v) => number_list.push(v), None => number_list.push(0.0), }; @@ -124,10 +135,10 @@ impl Area { None } else { Some(Area::Circle { - left: number_list[0], - top: number_list[1], - radius: number_list[2] - }) + left: number_list[0], + top: number_list[1], + radius: number_list[2], + }) } } else { None @@ -145,9 +156,9 @@ impl Area { } Some(Area::Rectangle { - top_left: (number_list[0], number_list[1]), - bottom_right: (number_list[2], number_list[3]) - }) + top_left: (number_list[0], number_list[1]), + bottom_right: (number_list[2], number_list[3]), + }) } else { None } @@ -159,7 +170,9 @@ impl Area { // Drop last element if there are odd number of coordinates number_list.remove(final_size - 1); } - Some(Area::Polygon { points: number_list }) + Some(Area::Polygon { + points: number_list, + }) } else { None } @@ -170,14 +183,17 @@ impl Area { pub fn hit_test(&self, p: &Point2D<f32>) -> bool { match *self { Area::Circle { left, top, radius } => { - (p.x - left) * (p.x - left) + - (p.y - top) * (p.y - top) - - radius * radius <= 0.0 + (p.x - left) * (p.x - left) + (p.y - top) * (p.y - top) - radius * radius <= 0.0 }, - Area::Rectangle { top_left, bottom_right } => { - p.x <= bottom_right.0 && p.x >= top_left.0 && - p.y <= bottom_right.1 && p.y >= top_left.1 + Area::Rectangle { + top_left, + bottom_right, + } => { + p.x <= bottom_right.0 && + p.x >= top_left.0 && + p.y <= bottom_right.1 && + p.y >= top_left.1 }, //TODO polygon hit_test @@ -187,28 +203,30 @@ impl Area { pub fn absolute_coords(&self, p: Point2D<f32>) -> Area { match *self { - Area::Rectangle { top_left, bottom_right } => { - Area::Rectangle { - top_left: (top_left.0 + p.x, top_left.1 + p.y), - bottom_right: (bottom_right.0 + p.x, bottom_right.1 + p.y) - } + Area::Rectangle { + top_left, + bottom_right, + } => Area::Rectangle { + top_left: (top_left.0 + p.x, top_left.1 + p.y), + bottom_right: (bottom_right.0 + p.x, bottom_right.1 + p.y), }, - Area::Circle { left, top, radius } => { - Area::Circle { - left: (left + p.x), - top: (top + p.y), - radius: radius - } + Area::Circle { left, top, radius } => Area::Circle { + left: (left + p.x), + top: (top + p.y), + radius: radius, }, Area::Polygon { ref points } => { -// let new_points = Vec::new(); - let iter = points.iter().enumerate().map(|(index, point)| { - match index % 2 { + // let new_points = Vec::new(); + let iter = points + .iter() + .enumerate() + .map(|(index, point)| match index % 2 { 0 => point + p.x as f32, _ => point + p.y as f32, - } - }); - Area::Polygon { points: iter.collect::<Vec<_>>() } + }); + Area::Polygon { + points: iter.collect::<Vec<_>>(), + } }, } } @@ -221,7 +239,11 @@ pub struct HTMLAreaElement { } impl HTMLAreaElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLAreaElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLAreaElement { HTMLAreaElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), rel_list: Default::default(), @@ -229,18 +251,22 @@ impl HTMLAreaElement { } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLAreaElement> { - Node::reflect_node(Box::new(HTMLAreaElement::new_inherited(local_name, prefix, document)), - document, - HTMLAreaElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLAreaElement> { + Node::reflect_node( + Box::new(HTMLAreaElement::new_inherited(local_name, prefix, document)), + document, + HTMLAreaElementBinding::Wrap, + ) } pub fn get_shape_from_coords(&self) -> Option<Area> { - let elem = self.upcast::<Element>(); - let shape = elem.get_string_attribute(&"shape".into()); - let shp: Shape = match_ignore_ascii_case! { &shape, + let elem = self.upcast::<Element>(); + let shape = elem.get_string_attribute(&"shape".into()); + let shp: Shape = match_ignore_ascii_case! { &shape, "circle" => Shape::Circle, "circ" => Shape::Circle, "rectangle" => Shape::Rectangle, @@ -266,7 +292,10 @@ impl VirtualMethods for HTMLAreaElement { fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()), - _ => self.super_type().unwrap().parse_plain_attribute(name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(name, value), } } } @@ -274,9 +303,8 @@ impl VirtualMethods for HTMLAreaElement { impl HTMLAreaElementMethods for HTMLAreaElement { // https://html.spec.whatwg.org/multipage/#dom-area-rellist fn RelList(&self) -> DomRoot<DOMTokenList> { - self.rel_list.or_init(|| { - DOMTokenList::new(self.upcast(), &local_name!("rel")) - }) + self.rel_list + .or_init(|| DOMTokenList::new(self.upcast(), &local_name!("rel"))) } } @@ -290,14 +318,17 @@ impl Activatable for HTMLAreaElement { self.as_element().has_attribute(&local_name!("href")) } - fn pre_click_activation(&self) { - } + fn pre_click_activation(&self) {} - fn canceled_activation(&self) { - } + fn canceled_activation(&self) {} - fn implicit_submission(&self, _ctrl_key: bool, _shift_key: bool, - _alt_key: bool, _meta_key: bool) { + fn implicit_submission( + &self, + _ctrl_key: bool, + _shift_key: bool, + _alt_key: bool, + _meta_key: bool, + ) { } fn activation_behavior(&self, _event: &Event, _target: &EventTarget) { diff --git a/components/script/dom/htmlaudioelement.rs b/components/script/dom/htmlaudioelement.rs index ed33f124819..354e138089b 100644 --- a/components/script/dom/htmlaudioelement.rs +++ b/components/script/dom/htmlaudioelement.rs @@ -12,25 +12,32 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLAudioElement { - htmlmediaelement: HTMLMediaElement + htmlmediaelement: HTMLMediaElement, } impl HTMLAudioElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLAudioElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLAudioElement { HTMLAudioElement { - htmlmediaelement: - HTMLMediaElement::new_inherited(local_name, prefix, document) + htmlmediaelement: HTMLMediaElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLAudioElement> { - Node::reflect_node(Box::new(HTMLAudioElement::new_inherited(local_name, prefix, document)), - document, - HTMLAudioElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLAudioElement> { + Node::reflect_node( + Box::new(HTMLAudioElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLAudioElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlbaseelement.rs b/components/script/dom/htmlbaseelement.rs index 54909e57e30..fbda8679239 100644 --- a/components/script/dom/htmlbaseelement.rs +++ b/components/script/dom/htmlbaseelement.rs @@ -19,30 +19,42 @@ use servo_url::ServoUrl; #[dom_struct] pub struct HTMLBaseElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLBaseElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLBaseElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLBaseElement { HTMLBaseElement { - htmlelement: HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLBaseElement> { - Node::reflect_node(Box::new(HTMLBaseElement::new_inherited(local_name, prefix, document)), - document, - HTMLBaseElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLBaseElement> { + Node::reflect_node( + Box::new(HTMLBaseElement::new_inherited(local_name, prefix, document)), + document, + HTMLBaseElementBinding::Wrap, + ) } /// <https://html.spec.whatwg.org/multipage/#frozen-base-url> pub fn frozen_base_url(&self) -> ServoUrl { - let href = self.upcast::<Element>().get_attribute(&ns!(), &local_name!("href")) - .expect("The frozen base url is only defined for base elements \ - that have a base url."); + let href = self + .upcast::<Element>() + .get_attribute(&ns!(), &local_name!("href")) + .expect( + "The frozen base url is only defined for base elements \ + that have a base url.", + ); let document = document_from_node(self); let base = document.fallback_base_url(); let parsed = base.join(&href.value()); @@ -70,7 +82,9 @@ impl HTMLBaseElementMethods for HTMLBaseElement { let document = document_from_node(self); // Step 2. - let attr = self.upcast::<Element>().get_attribute(&ns!(), &local_name!("href")); + let attr = self + .upcast::<Element>() + .get_attribute(&ns!(), &local_name!("href")); let value = attr.as_ref().map(|attr| attr.value()); let url = value.as_ref().map_or("", |value| &**value); @@ -81,7 +95,7 @@ impl HTMLBaseElementMethods for HTMLBaseElement { Err(_) => { // Step 4. url.into() - } + }, Ok(url_record) => { // Step 5. url_record.into_string().into() diff --git a/components/script/dom/htmlbodyelement.rs b/components/script/dom/htmlbodyelement.rs index 7d921d57ce8..da0c641e5c3 100644 --- a/components/script/dom/htmlbodyelement.rs +++ b/components/script/dom/htmlbodyelement.rs @@ -32,19 +32,27 @@ pub struct HTMLBodyElement { } impl HTMLBodyElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) - -> HTMLBodyElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLBodyElement { HTMLBodyElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) - -> DomRoot<HTMLBodyElement> { - Node::reflect_node(Box::new(HTMLBodyElement::new_inherited(local_name, prefix, document)), - document, - HTMLBodyElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLBodyElement> { + Node::reflect_node( + Box::new(HTMLBodyElement::new_inherited(local_name, prefix, document)), + document, + HTMLBodyElementBinding::Wrap, + ) } /// <https://drafts.csswg.org/cssom-view/#the-html-body-element> @@ -52,10 +60,10 @@ impl HTMLBodyElement { let self_node = self.upcast::<Node>(); let root_elem = self.upcast::<Element>().root_element(); let root_node = root_elem.upcast::<Node>(); - root_node.is_parent_of(self_node) && - self_node.preceding_siblings().all(|n| !n.is::<HTMLBodyElement>()) + root_node.is_parent_of(self_node) && self_node + .preceding_siblings() + .all(|n| !n.is::<HTMLBodyElement>()) } - } impl HTMLBodyElementMethods for HTMLBodyElement { @@ -76,11 +84,10 @@ impl HTMLBodyElementMethods for HTMLBodyElement { // https://html.spec.whatwg.org/multipage/#dom-body-background fn SetBackground(&self, input: DOMString) { - let value = AttrValue::from_resolved_url( - &document_from_node(self).base_url(), - input.into(), - ); - self.upcast::<Element>().set_attribute(&local_name!("background"), value); + let value = + AttrValue::from_resolved_url(&document_from_node(self).base_url(), input.into()); + self.upcast::<Element>() + .set_attribute(&local_name!("background"), value); } // https://html.spec.whatwg.org/multipage/#windoweventhandlers @@ -135,7 +142,9 @@ impl VirtualMethods for HTMLBodyElement { return true; } - self.super_type().unwrap().attribute_affects_presentational_hints(attr) + self.super_type() + .unwrap() + .attribute_affects_presentational_hints(attr) } fn bind_to_tree(&self, tree_in_doc: bool) { @@ -144,7 +153,7 @@ impl VirtualMethods for HTMLBodyElement { } if !tree_in_doc { - return + return; } let window = window_from_node(self); @@ -158,15 +167,16 @@ impl VirtualMethods for HTMLBodyElement { fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match *name { - local_name!("bgcolor") | - local_name!("text") => AttrValue::from_legacy_color(value.into()), + local_name!("bgcolor") | local_name!("text") => { + AttrValue::from_legacy_color(value.into()) + }, local_name!("background") => { - AttrValue::from_resolved_url( - &document_from_node(self).base_url(), - value.into(), - ) + AttrValue::from_resolved_url(&document_from_node(self).base_url(), value.into()) }, - _ => self.super_type().unwrap().parse_plain_attribute(name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(name, value), } } @@ -177,23 +187,34 @@ impl VirtualMethods for HTMLBodyElement { // https://html.spec.whatwg.org/multipage/ // #event-handlers-on-elements,-document-objects,-and-window-objects:event-handlers-3 match name { - &local_name!("onfocus") | &local_name!("onload") | &local_name!("onscroll") | - &local_name!("onafterprint") | &local_name!("onbeforeprint") | - &local_name!("onbeforeunload") | &local_name!("onhashchange") | - &local_name!("onlanguagechange") | &local_name!("onmessage") | - &local_name!("onoffline") | &local_name!("ononline") | - &local_name!("onpagehide") | &local_name!("onpageshow") | - &local_name!("onpopstate") | &local_name!("onstorage") | - &local_name!("onresize") | &local_name!("onunload") | &local_name!("onerror") - => { - let evtarget = window.upcast::<EventTarget>(); // forwarded event - let source_line = 1; //TODO(#9604) obtain current JS execution line - evtarget.set_event_handler_uncompiled(window.get_url(), - source_line, - &name[2..], - DOMString::from((**attr.value()).to_owned())); - false - } + &local_name!("onfocus") | + &local_name!("onload") | + &local_name!("onscroll") | + &local_name!("onafterprint") | + &local_name!("onbeforeprint") | + &local_name!("onbeforeunload") | + &local_name!("onhashchange") | + &local_name!("onlanguagechange") | + &local_name!("onmessage") | + &local_name!("onoffline") | + &local_name!("ononline") | + &local_name!("onpagehide") | + &local_name!("onpageshow") | + &local_name!("onpopstate") | + &local_name!("onstorage") | + &local_name!("onresize") | + &local_name!("onunload") | + &local_name!("onerror") => { + let evtarget = window.upcast::<EventTarget>(); // forwarded event + let source_line = 1; //TODO(#9604) obtain current JS execution line + evtarget.set_event_handler_uncompiled( + window.get_url(), + source_line, + &name[2..], + DOMString::from((**attr.value()).to_owned()), + ); + false + }, _ => true, // HTMLElement::attribute_mutated will take care of this. } }, diff --git a/components/script/dom/htmlbrelement.rs b/components/script/dom/htmlbrelement.rs index 02845543e53..87e5c024901 100644 --- a/components/script/dom/htmlbrelement.rs +++ b/components/script/dom/htmlbrelement.rs @@ -16,18 +16,26 @@ pub struct HTMLBRElement { } impl HTMLBRElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLBRElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLBRElement { HTMLBRElement { - htmlelement: HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLBRElement> { - Node::reflect_node(Box::new(HTMLBRElement::new_inherited(local_name, prefix, document)), - document, - HTMLBRElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLBRElement> { + Node::reflect_node( + Box::new(HTMLBRElement::new_inherited(local_name, prefix, document)), + document, + HTMLBRElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlbuttonelement.rs b/components/script/dom/htmlbuttonelement.rs index be2b26d2085..d404c13ff9d 100755 --- a/components/script/dom/htmlbuttonelement.rs +++ b/components/script/dom/htmlbuttonelement.rs @@ -29,13 +29,12 @@ use std::cell::Cell; use std::default::Default; use style::element_state::ElementState; -#[derive(Clone, Copy, JSTraceable, PartialEq)] -#[derive(MallocSizeOf)] +#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq )] enum ButtonType { Submit, Reset, Button, - Menu + Menu, } #[dom_struct] @@ -46,25 +45,36 @@ pub struct HTMLButtonElement { } impl HTMLButtonElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLButtonElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLButtonElement { HTMLButtonElement { - htmlelement: - HTMLElement::new_inherited_with_state(ElementState::IN_ENABLED_STATE, - local_name, prefix, document), + htmlelement: HTMLElement::new_inherited_with_state( + ElementState::IN_ENABLED_STATE, + local_name, + prefix, + document, + ), button_type: Cell::new(ButtonType::Submit), form_owner: Default::default(), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLButtonElement> { - Node::reflect_node(Box::new(HTMLButtonElement::new_inherited(local_name, prefix, document)), - document, - HTMLButtonElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLButtonElement> { + Node::reflect_node( + Box::new(HTMLButtonElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLButtonElementBinding::Wrap, + ) } } @@ -99,10 +109,12 @@ impl HTMLButtonElementMethods for HTMLButtonElement { make_setter!(SetFormAction, "formaction"); // https://html.spec.whatwg.org/multipage/#dom-fs-formenctype - make_enumerated_getter!(FormEnctype, - "formenctype", - "application/x-www-form-urlencoded", - "text/plain" | "multipart/form-data"); + make_enumerated_getter!( + FormEnctype, + "formenctype", + "application/x-www-form-urlencoded", + "text/plain" | "multipart/form-data" + ); // https://html.spec.whatwg.org/multipage/#dom-fs-formenctype make_setter!(SetFormEnctype, "formenctype"); @@ -152,10 +164,10 @@ impl HTMLButtonElement { // Step 3.1: only run steps if this is the submitter if let Some(FormSubmitter::ButtonElement(submitter)) = submitter { if submitter != self { - return None + return None; } } else { - return None + return None; } // Step 3.2 let ty = self.Type(); @@ -171,7 +183,7 @@ impl HTMLButtonElement { Some(FormDatum { ty: ty, name: name, - value: FormDatumValue::String(self.Value()) + value: FormDatumValue::String(self.Value()), }) } } @@ -187,7 +199,7 @@ impl VirtualMethods for HTMLButtonElement { &local_name!("disabled") => { let el = self.upcast::<Element>(); match mutation { - AttributeMutation::Set(Some(_)) => {} + AttributeMutation::Set(Some(_)) => {}, AttributeMutation::Set(None) => { el.set_disabled_state(true); el.set_enabled_state(false); @@ -196,28 +208,26 @@ impl VirtualMethods for HTMLButtonElement { el.set_disabled_state(false); el.set_enabled_state(true); el.check_ancestors_disabled_state_for_form_control(); - } + }, } }, - &local_name!("type") => { - match mutation { - AttributeMutation::Set(_) => { - let value = match &**attr.value() { - "reset" => ButtonType::Reset, - "button" => ButtonType::Button, - "menu" => ButtonType::Menu, - _ => ButtonType::Submit, - }; - self.button_type.set(value); - } - AttributeMutation::Removed => { - self.button_type.set(ButtonType::Submit); - } - } + &local_name!("type") => match mutation { + AttributeMutation::Set(_) => { + let value = match &**attr.value() { + "reset" => ButtonType::Reset, + "button" => ButtonType::Button, + "menu" => ButtonType::Menu, + _ => ButtonType::Submit, + }; + self.button_type.set(value); + }, + AttributeMutation::Removed => { + self.button_type.set(ButtonType::Submit); + }, }, &local_name!("form") => { self.form_attribute_mutated(mutation); - } + }, _ => {}, } } @@ -227,7 +237,8 @@ impl VirtualMethods for HTMLButtonElement { s.bind_to_tree(tree_in_doc); } - self.upcast::<Element>().check_ancestors_disabled_state_for_form_control(); + self.upcast::<Element>() + .check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { @@ -235,7 +246,10 @@ impl VirtualMethods for HTMLButtonElement { let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); - if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { + if node + .ancestors() + .any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) + { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); @@ -280,12 +294,10 @@ impl Activatable for HTMLButtonElement { // https://html.spec.whatwg.org/multipage/#run-pre-click-activation-steps // https://html.spec.whatwg.org/multipage/#the-button-element:activation-behavior - fn pre_click_activation(&self) { - } + fn pre_click_activation(&self) {} // https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps - fn canceled_activation(&self) { - } + fn canceled_activation(&self) {} // https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps fn activation_behavior(&self, _event: &Event, _target: &EventTarget) { @@ -295,16 +307,18 @@ impl Activatable for HTMLButtonElement { ButtonType::Submit => { // TODO: is document owner fully active? if let Some(owner) = self.form_owner() { - owner.submit(SubmittedFrom::NotFromForm, - FormSubmitter::ButtonElement(self.clone())); + owner.submit( + SubmittedFrom::NotFromForm, + FormSubmitter::ButtonElement(self.clone()), + ); } - } + }, ButtonType::Reset => { // TODO: is document owner fully active? if let Some(owner) = self.form_owner() { owner.reset(ResetFrom::NotFromForm); } - } + }, _ => (), } } @@ -318,14 +332,19 @@ impl Activatable for HTMLButtonElement { if owner.is_none() || self.upcast::<Element>().click_in_progress() { return; } - node.query_selector_iter(DOMString::from("button[type=submit]")).unwrap() + node.query_selector_iter(DOMString::from("button[type=submit]")) + .unwrap() .filter_map(DomRoot::downcast::<HTMLButtonElement>) .find(|r| r.form_owner() == owner) - .map(|s| synthetic_click_activation(s.as_element(), - ctrl_key, - shift_key, - alt_key, - meta_key, - ActivationSource::NotFromClick)); + .map(|s| { + synthetic_click_activation( + s.as_element(), + ctrl_key, + shift_key, + alt_key, + meta_key, + ActivationSource::NotFromClick, + ) + }); } } diff --git a/components/script/dom/htmlcanvaselement.rs b/components/script/dom/htmlcanvaselement.rs index 7bc6a233e66..00b04db7ee8 100644 --- a/components/script/dom/htmlcanvaselement.rs +++ b/components/script/dom/htmlcanvaselement.rs @@ -61,9 +61,11 @@ pub struct HTMLCanvasElement { } impl HTMLCanvasElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLCanvasElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLCanvasElement { HTMLCanvasElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), context: DomRefCell::new(None), @@ -71,12 +73,18 @@ impl HTMLCanvasElement { } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLCanvasElement> { - Node::reflect_node(Box::new(HTMLCanvasElement::new_inherited(local_name, prefix, document)), - document, - HTMLCanvasElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLCanvasElement> { + Node::reflect_node( + Box::new(HTMLCanvasElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLCanvasElementBinding::Wrap, + ) } fn recreate_contexts(&self) { @@ -124,13 +132,15 @@ impl LayoutHTMLCanvasElementHelpers for LayoutDom<HTMLCanvasElement> { Some(&CanvasContext::WebGL2(ref context)) => { context.to_layout().canvas_data_source() }, - None => { - HTMLCanvasDataSource::Image(None) - } + None => HTMLCanvasDataSource::Image(None), }; - let width_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("width")); - let height_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("height")); + let width_attr = canvas + .upcast::<Element>() + .get_attr_for_layout(&ns!(), &local_name!("width")); + let height_attr = canvas + .upcast::<Element>() + .get_attr_for_layout(&ns!(), &local_name!("height")); HTMLCanvasData { source: source, width: width_attr.map_or(DEFAULT_WIDTH, |val| val.as_uint()), @@ -164,7 +174,8 @@ impl LayoutHTMLCanvasElementHelpers for LayoutDom<HTMLCanvasElement> { fn get_canvas_id_for_layout(&self) -> CanvasId { unsafe { let canvas = &*self.unsafe_get(); - if let &Some(CanvasContext::Context2d(ref context)) = canvas.context.borrow_for_layout() { + if let &Some(CanvasContext::Context2d(ref context)) = canvas.context.borrow_for_layout() + { context.to_layout().get_canvas_id() } else { CanvasId(0) @@ -173,7 +184,6 @@ impl LayoutHTMLCanvasElementHelpers for LayoutDom<HTMLCanvasElement> { } } - impl HTMLCanvasElement { pub fn context(&self) -> Option<Ref<CanvasContext>> { ref_filter_map::ref_filter_map(self.context.borrow(), |ctx| ctx.as_ref()) @@ -220,7 +230,7 @@ impl HTMLCanvasElement { options: HandleValue, ) -> Option<DomRoot<WebGL2RenderingContext>> { if !PREFS.is_webgl2_enabled() { - return None + return None; } if let Some(ctx) = self.context() { return match *ctx { @@ -241,7 +251,7 @@ impl HTMLCanvasElement { match *self.context.borrow() { Some(CanvasContext::WebGL(ref context)) => Some(DomRoot::from_ref(&*context)), Some(CanvasContext::WebGL2(ref context)) => Some(context.base_context()), - _ => None + _ => None, } } @@ -255,11 +265,11 @@ impl HTMLCanvasElement { Ok(ConversionResult::Failure(ref error)) => { throw_type_error(cx, &error); None - } + }, _ => { debug!("Unexpected error on conversion of WebGLContextAttributes"); None - } + }, } } @@ -271,13 +281,17 @@ impl HTMLCanvasElement { let size = self.get_size(); if size.width == 0 || size.height == 0 { - return None + return None; } let data = match self.context.borrow().as_ref() { Some(&CanvasContext::Context2d(ref context)) => { - let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); - let msg = CanvasMsg::FromScript(FromScriptMsg::SendPixels(sender), context.get_canvas_id()); + let (sender, receiver) = + ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); + let msg = CanvasMsg::FromScript( + FromScriptMsg::SendPixels(sender), + context.get_canvas_id(), + ); context.get_ipc_renderer().send(msg).unwrap(); receiver.recv().unwrap()?.into() @@ -319,19 +333,16 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement { options: HandleValue, ) -> Option<RenderingContext> { match &*id { - "2d" => { - self.get_or_init_2d_context() - .map(RenderingContext::CanvasRenderingContext2D) - } - "webgl" | "experimental-webgl" => { - self.get_or_init_webgl_context(cx, options) - .map(RenderingContext::WebGLRenderingContext) - } - "webgl2" | "experimental-webgl2" => { - self.get_or_init_webgl2_context(cx, options) - .map(RenderingContext::WebGL2RenderingContext) - } - _ => None + "2d" => self + .get_or_init_2d_context() + .map(RenderingContext::CanvasRenderingContext2D), + "webgl" | "experimental-webgl" => self + .get_or_init_webgl_context(cx, options) + .map(RenderingContext::WebGLRenderingContext), + "webgl2" | "experimental-webgl2" => self + .get_or_init_webgl2_context(cx, options) + .map(RenderingContext::WebGL2RenderingContext), + _ => None, } } @@ -358,27 +369,31 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement { // Step 3. let raw_data = match *self.context.borrow() { Some(CanvasContext::Context2d(ref context)) => { - let image_data = context.GetImageData(Finite::wrap(0f64), Finite::wrap(0f64), - Finite::wrap(self.Width() as f64), - Finite::wrap(self.Height() as f64))?; + let image_data = context.GetImageData( + Finite::wrap(0f64), + Finite::wrap(0f64), + Finite::wrap(self.Width() as f64), + Finite::wrap(self.Height() as f64), + )?; image_data.get_data_array() - } + }, Some(CanvasContext::WebGL(ref context)) => { match context.get_image_data(self.Width(), self.Height()) { Some(data) => data, None => return Ok(USVString("data:,".into())), } - } - Some(CanvasContext::WebGL2(ref context)) => { - match context.base_context().get_image_data(self.Width(), self.Height()) { - Some(data) => data, - None => return Ok(USVString("data:,".into())), - } - } + }, + Some(CanvasContext::WebGL2(ref context)) => match context + .base_context() + .get_image_data(self.Width(), self.Height()) + { + Some(data) => data, + None => return Ok(USVString("data:,".into())), + }, None => { // Each pixel is fully-transparent black. vec![0; (self.Width() * self.Height() * 4) as usize] - } + }, }; // Only handle image/png for now. @@ -387,7 +402,9 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement { let mut encoded = Vec::new(); { let encoder: PNGEncoder<&mut Vec<u8>> = PNGEncoder::new(&mut encoded); - encoder.encode(&raw_data, self.Width(), self.Height(), ColorType::RGBA(8)).unwrap(); + encoder + .encode(&raw_data, self.Width(), self.Height(), ColorType::RGBA(8)) + .unwrap(); } let encoded = base64::encode(&encoded); @@ -412,7 +429,10 @@ impl VirtualMethods for HTMLCanvasElement { match name { &local_name!("width") => AttrValue::from_u32(value.into(), DEFAULT_WIDTH), &local_name!("height") => AttrValue::from_u32(value.into(), DEFAULT_HEIGHT), - _ => self.super_type().unwrap().parse_plain_attribute(name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(name, value), } } } @@ -438,13 +458,15 @@ pub mod utils { pub fn request_image_from_cache(window: &Window, url: ServoUrl) -> ImageResponse { let image_cache = window.image_cache(); - let response = - image_cache.find_image_or_metadata(url.into(), - UsePlaceholder::No, - CanRequestImages::No); + let response = image_cache.find_image_or_metadata( + url.into(), + UsePlaceholder::No, + CanRequestImages::No, + ); match response { - Ok(ImageOrMetadataAvailable::ImageAvailable(image, url)) => - ImageResponse::Loaded(image, url), + Ok(ImageOrMetadataAvailable::ImageAvailable(image, url)) => { + ImageResponse::Loaded(image, url) + }, _ => ImageResponse::None, } } diff --git a/components/script/dom/htmlcollection.rs b/components/script/dom/htmlcollection.rs index 5d3f01a03a0..d94607635e4 100644 --- a/components/script/dom/htmlcollection.rs +++ b/components/script/dom/htmlcollection.rs @@ -19,7 +19,7 @@ use servo_atoms::Atom; use std::cell::Cell; use style::str::split_html_space_chars; -pub trait CollectionFilter : JSTraceable { +pub trait CollectionFilter: JSTraceable { fn filter<'a>(&self, elem: &'a Element, root: &'a Node) -> bool; } @@ -46,7 +46,9 @@ impl OptionU32 { } fn none() -> OptionU32 { - OptionU32 { bits: u32::max_value() } + OptionU32 { + bits: u32::max_value(), + } } } @@ -94,13 +96,23 @@ impl HTMLCollection { } #[allow(unrooted_must_root)] - pub fn new(window: &Window, root: &Node, filter: Box<CollectionFilter + 'static>) -> DomRoot<HTMLCollection> { - reflect_dom_object(Box::new(HTMLCollection::new_inherited(root, filter)), - window, HTMLCollectionBinding::Wrap) + pub fn new( + window: &Window, + root: &Node, + filter: Box<CollectionFilter + 'static>, + ) -> DomRoot<HTMLCollection> { + reflect_dom_object( + Box::new(HTMLCollection::new_inherited(root, filter)), + window, + HTMLCollectionBinding::Wrap, + ) } - pub fn create(window: &Window, root: &Node, - filter: Box<CollectionFilter + 'static>) -> DomRoot<HTMLCollection> { + pub fn create( + window: &Window, + root: &Node, + filter: Box<CollectionFilter + 'static>, + ) -> DomRoot<HTMLCollection> { HTMLCollection::new(window, root, filter) } @@ -117,7 +129,11 @@ impl HTMLCollection { } } - fn set_cached_cursor(&self, index: u32, element: Option<DomRoot<Element>>) -> Option<DomRoot<Element>> { + fn set_cached_cursor( + &self, + index: u32, + element: Option<DomRoot<Element>>, + ) -> Option<DomRoot<Element>> { if let Some(element) = element { self.cached_cursor_index.set(OptionU32::some(index)); self.cached_cursor_element.set(Some(&element)); @@ -128,8 +144,11 @@ impl HTMLCollection { } // https://dom.spec.whatwg.org/#concept-getelementsbytagname - pub fn by_qualified_name(window: &Window, root: &Node, qualified_name: LocalName) - -> DomRoot<HTMLCollection> { + pub fn by_qualified_name( + window: &Window, + root: &Node, + qualified_name: LocalName, + ) -> DomRoot<HTMLCollection> { // case 1 if qualified_name == local_name!("*") { #[derive(JSTraceable, MallocSizeOf)] @@ -149,9 +168,11 @@ impl HTMLCollection { } impl CollectionFilter for HtmlDocumentFilter { fn filter(&self, elem: &Element, root: &Node) -> bool { - if root.is_in_html_doc() && elem.namespace() == &ns!(html) { // case 2 + if root.is_in_html_doc() && elem.namespace() == &ns!(html) { + // case 2 HTMLCollection::match_element(elem, &self.ascii_lower_qualified_name) - } else { // case 2 and 3 + } else { + // case 2 and 3 HTMLCollection::match_element(elem, &self.qualified_name) } } @@ -167,60 +188,75 @@ impl HTMLCollection { fn match_element(elem: &Element, qualified_name: &LocalName) -> bool { match elem.prefix().as_ref() { None => elem.local_name() == qualified_name, - Some(prefix) => qualified_name.starts_with(&**prefix) && - qualified_name.find(":") == Some(prefix.len()) && - qualified_name.ends_with(&**elem.local_name()), + Some(prefix) => { + qualified_name.starts_with(&**prefix) && + qualified_name.find(":") == Some(prefix.len()) && + qualified_name.ends_with(&**elem.local_name()) + }, } } - pub fn by_tag_name_ns(window: &Window, root: &Node, tag: DOMString, - maybe_ns: Option<DOMString>) -> DomRoot<HTMLCollection> { + pub fn by_tag_name_ns( + window: &Window, + root: &Node, + tag: DOMString, + maybe_ns: Option<DOMString>, + ) -> DomRoot<HTMLCollection> { let local = LocalName::from(tag); let ns = namespace_from_domstring(maybe_ns); let qname = QualName::new(None, ns, local); HTMLCollection::by_qual_tag_name(window, root, qname) } - pub fn by_qual_tag_name(window: &Window, root: &Node, qname: QualName) -> DomRoot<HTMLCollection> { + pub fn by_qual_tag_name( + window: &Window, + root: &Node, + qname: QualName, + ) -> DomRoot<HTMLCollection> { #[derive(JSTraceable, MallocSizeOf)] struct TagNameNSFilter { - qname: QualName + qname: QualName, } impl CollectionFilter for TagNameNSFilter { fn filter(&self, elem: &Element, _root: &Node) -> bool { - ((self.qname.ns == namespace_url!("*")) || (self.qname.ns == *elem.namespace())) && - ((self.qname.local == local_name!("*")) || (self.qname.local == *elem.local_name())) + ((self.qname.ns == namespace_url!("*")) || (self.qname.ns == *elem.namespace())) && + ((self.qname.local == local_name!("*")) || + (self.qname.local == *elem.local_name())) } } - let filter = TagNameNSFilter { - qname: qname - }; + let filter = TagNameNSFilter { qname: qname }; HTMLCollection::create(window, root, Box::new(filter)) } - pub fn by_class_name(window: &Window, root: &Node, classes: DOMString) - -> DomRoot<HTMLCollection> { + pub fn by_class_name( + window: &Window, + root: &Node, + classes: DOMString, + ) -> DomRoot<HTMLCollection> { let class_atoms = split_html_space_chars(&classes).map(Atom::from).collect(); HTMLCollection::by_atomic_class_name(window, root, class_atoms) } - pub fn by_atomic_class_name(window: &Window, root: &Node, classes: Vec<Atom>) - -> DomRoot<HTMLCollection> { + pub fn by_atomic_class_name( + window: &Window, + root: &Node, + classes: Vec<Atom>, + ) -> DomRoot<HTMLCollection> { #[derive(JSTraceable, MallocSizeOf)] struct ClassNameFilter { - classes: Vec<Atom> + classes: Vec<Atom>, } impl CollectionFilter for ClassNameFilter { fn filter(&self, elem: &Element, _root: &Node) -> bool { let case_sensitivity = document_from_node(elem) .quirks_mode() .classes_and_ids_case_sensitivity(); - self.classes.iter().all(|class| elem.has_class(class, case_sensitivity)) + self.classes + .iter() + .all(|class| elem.has_class(class, case_sensitivity)) } } - let filter = ClassNameFilter { - classes: classes - }; + let filter = ClassNameFilter { classes: classes }; HTMLCollection::create(window, root, Box::new(filter)) } @@ -235,21 +271,29 @@ impl HTMLCollection { HTMLCollection::create(window, root, Box::new(ElementChildFilter)) } - pub fn elements_iter_after<'a>(&'a self, after: &'a Node) -> impl Iterator<Item=DomRoot<Element>> + 'a { + pub fn elements_iter_after<'a>( + &'a self, + after: &'a Node, + ) -> impl Iterator<Item = DomRoot<Element>> + 'a { // Iterate forwards from a node. - after.following_nodes(&self.root) + after + .following_nodes(&self.root) .filter_map(DomRoot::downcast) .filter(move |element| self.filter.filter(&element, &self.root)) } - pub fn elements_iter<'a>(&'a self) -> impl Iterator<Item=DomRoot<Element>> + 'a { + pub fn elements_iter<'a>(&'a self) -> impl Iterator<Item = DomRoot<Element>> + 'a { // Iterate forwards from the root. self.elements_iter_after(&*self.root) } - pub fn elements_iter_before<'a>(&'a self, before: &'a Node) -> impl Iterator<Item=DomRoot<Element>> + 'a { + pub fn elements_iter_before<'a>( + &'a self, + before: &'a Node, + ) -> impl Iterator<Item = DomRoot<Element>> + 'a { // Iterate backwards from a node. - before.preceding_nodes(&self.root) + before + .preceding_nodes(&self.root) .filter_map(DomRoot::downcast) .filter(move |element| self.filter.filter(&element, &self.root)) } @@ -322,7 +366,8 @@ impl HTMLCollectionMethods for HTMLCollection { // Step 2. self.elements_iter().find(|elem| { elem.get_string_attribute(&local_name!("id")) == key || - (elem.namespace() == &ns!(html) && elem.get_string_attribute(&local_name!("name")) == key) + (elem.namespace() == &ns!(html) && + elem.get_string_attribute(&local_name!("name")) == key) }) } @@ -350,7 +395,10 @@ impl HTMLCollectionMethods for HTMLCollection { } // Step 2.2 let name_attr = elem.get_string_attribute(&local_name!("name")); - if !name_attr.is_empty() && !result.contains(&name_attr) && *elem.namespace() == ns!(html) { + if !name_attr.is_empty() && + !result.contains(&name_attr) && + *elem.namespace() == ns!(html) + { result.push(name_attr) } } diff --git a/components/script/dom/htmldataelement.rs b/components/script/dom/htmldataelement.rs index 98aa078993c..07a2d0f2442 100644 --- a/components/script/dom/htmldataelement.rs +++ b/components/script/dom/htmldataelement.rs @@ -14,25 +14,31 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLDataElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLDataElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLDataElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLDataElement { HTMLDataElement { - htmlelement: HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLDataElement> { - Node::reflect_node(Box::new(HTMLDataElement::new_inherited(local_name, prefix, document)), - document, - HTMLDataElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLDataElement> { + Node::reflect_node( + Box::new(HTMLDataElement::new_inherited(local_name, prefix, document)), + document, + HTMLDataElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmldatalistelement.rs b/components/script/dom/htmldatalistelement.rs index 43e2eaa4928..e99a9324520 100644 --- a/components/script/dom/htmldatalistelement.rs +++ b/components/script/dom/htmldatalistelement.rs @@ -17,26 +17,33 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLDataListElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLDataListElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLDataListElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLDataListElement { HTMLDataListElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLDataListElement> { - Node::reflect_node(Box::new(HTMLDataListElement::new_inherited(local_name, prefix, document)), - document, - HTMLDataListElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLDataListElement> { + Node::reflect_node( + Box::new(HTMLDataListElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLDataListElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmldetailselement.rs b/components/script/dom/htmldetailselement.rs index 61ef9b4a0d0..b764b0174ca 100644 --- a/components/script/dom/htmldetailselement.rs +++ b/components/script/dom/htmldetailselement.rs @@ -22,27 +22,34 @@ use task_source::TaskSource; #[dom_struct] pub struct HTMLDetailsElement { htmlelement: HTMLElement, - toggle_counter: Cell<u32> + toggle_counter: Cell<u32>, } impl HTMLDetailsElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLDetailsElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLDetailsElement { HTMLDetailsElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document), - toggle_counter: Cell::new(0) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), + toggle_counter: Cell::new(0), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLDetailsElement> { - Node::reflect_node(Box::new(HTMLDetailsElement::new_inherited(local_name, prefix, document)), - document, - HTMLDetailsElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLDetailsElement> { + Node::reflect_node( + Box::new(HTMLDetailsElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLDetailsElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmldialogelement.rs b/components/script/dom/htmldialogelement.rs index 9762a6c3c97..97643bf691f 100644 --- a/components/script/dom/htmldialogelement.rs +++ b/components/script/dom/htmldialogelement.rs @@ -23,23 +23,30 @@ pub struct HTMLDialogElement { } impl HTMLDialogElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLDialogElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLDialogElement { HTMLDialogElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document), + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), return_value: DomRefCell::new(DOMString::new()), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLDialogElement> { - Node::reflect_node(Box::new(HTMLDialogElement::new_inherited(local_name, prefix, document)), - document, - HTMLDialogElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLDialogElement> { + Node::reflect_node( + Box::new(HTMLDialogElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLDialogElementBinding::Wrap, + ) } } @@ -68,7 +75,10 @@ impl HTMLDialogElementMethods for HTMLDialogElement { let win = window_from_node(self); // Step 1 & 2 - if element.remove_attribute(&ns!(), &local_name!("open")).is_none() { + if element + .remove_attribute(&ns!(), &local_name!("open")) + .is_none() + { return; } @@ -80,6 +90,7 @@ impl HTMLDialogElementMethods for HTMLDialogElement { // TODO: Step 4 implement pending dialog stack removal // Step 5 - win.dom_manipulation_task_source().queue_simple_event(target, atom!("close"), &win); + win.dom_manipulation_task_source() + .queue_simple_event(target, atom!("close"), &win); } } diff --git a/components/script/dom/htmldirectoryelement.rs b/components/script/dom/htmldirectoryelement.rs index 1665202b4ec..541a8abfa03 100644 --- a/components/script/dom/htmldirectoryelement.rs +++ b/components/script/dom/htmldirectoryelement.rs @@ -12,25 +12,32 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLDirectoryElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLDirectoryElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLDirectoryElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLDirectoryElement { HTMLDirectoryElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLDirectoryElement> { - Node::reflect_node(Box::new(HTMLDirectoryElement::new_inherited(local_name, prefix, document)), - document, - HTMLDirectoryElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLDirectoryElement> { + Node::reflect_node( + Box::new(HTMLDirectoryElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLDirectoryElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmldivelement.rs b/components/script/dom/htmldivelement.rs index 48fd3afb951..3de1af4e568 100644 --- a/components/script/dom/htmldivelement.rs +++ b/components/script/dom/htmldivelement.rs @@ -13,25 +13,31 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLDivElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLDivElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLDivElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLDivElement { HTMLDivElement { - htmlelement: HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLDivElement> { - Node::reflect_node(Box::new(HTMLDivElement::new_inherited(local_name, prefix, document)), - document, - HTMLDivElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLDivElement> { + Node::reflect_node( + Box::new(HTMLDivElement::new_inherited(local_name, prefix, document)), + document, + HTMLDivElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmldlistelement.rs b/components/script/dom/htmldlistelement.rs index 5ad4e8f27f7..b63f0225095 100644 --- a/components/script/dom/htmldlistelement.rs +++ b/components/script/dom/htmldlistelement.rs @@ -12,23 +12,32 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLDListElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLDListElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLDListElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLDListElement { HTMLDListElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLDListElement> { - Node::reflect_node(Box::new(HTMLDListElement::new_inherited(local_name, prefix, document)), - document, - HTMLDListElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLDListElement> { + Node::reflect_node( + Box::new(HTMLDListElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLDListElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlelement.rs b/components/script/dom/htmlelement.rs index e28ff1053a2..9279f8fdbe1 100644 --- a/components/script/dom/htmlelement.rs +++ b/components/script/dom/htmlelement.rs @@ -49,27 +49,44 @@ pub struct HTMLElement { } impl HTMLElement { - pub fn new_inherited(tag_name: LocalName, prefix: Option<Prefix>, - document: &Document) -> HTMLElement { + pub fn new_inherited( + tag_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLElement { HTMLElement::new_inherited_with_state(ElementState::empty(), tag_name, prefix, document) } - pub fn new_inherited_with_state(state: ElementState, tag_name: LocalName, - prefix: Option<Prefix>, document: &Document) - -> HTMLElement { + pub fn new_inherited_with_state( + state: ElementState, + tag_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLElement { HTMLElement { - element: - Element::new_inherited_with_state(state, tag_name, ns!(html), prefix, document), + element: Element::new_inherited_with_state( + state, + tag_name, + ns!(html), + prefix, + document, + ), style_decl: Default::default(), dataset: Default::default(), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<HTMLElement> { - Node::reflect_node(Box::new(HTMLElement::new_inherited(local_name, prefix, document)), - document, - HTMLElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLElement> { + Node::reflect_node( + Box::new(HTMLElement::new_inherited(local_name, prefix, document)), + document, + HTMLElementBinding::Wrap, + ) } fn is_body_or_frameset(&self) -> bool { @@ -84,13 +101,24 @@ impl HTMLElement { node.set_flag(NodeFlags::SEQUENTIALLY_FOCUSABLE, true); } else { match node.type_id() { - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) | - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) | - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLIFrameElement)) | - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) - => node.set_flag(NodeFlags::SEQUENTIALLY_FOCUSABLE, true), - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLinkElement)) | - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) => { + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLButtonElement, + )) | + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLSelectElement, + )) | + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLIFrameElement, + )) | + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLTextAreaElement, + )) => node.set_flag(NodeFlags::SEQUENTIALLY_FOCUSABLE, true), + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLLinkElement, + )) | + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLAnchorElement, + )) => { if element.has_attribute(&local_name!("href")) { node.set_flag(NodeFlags::SEQUENTIALLY_FOCUSABLE, true); } @@ -119,10 +147,12 @@ impl HTMLElementMethods for HTMLElement { fn Style(&self) -> DomRoot<CSSStyleDeclaration> { self.style_decl.or_init(|| { let global = window_from_node(self); - CSSStyleDeclaration::new(&global, - CSSStyleOwner::Element(Dom::from_ref(self.upcast())), - None, - CSSModificationAccess::ReadWrite) + CSSStyleDeclaration::new( + &global, + CSSStyleOwner::Element(Dom::from_ref(self.upcast())), + None, + CSSModificationAccess::ReadWrite, + ) }) } @@ -162,7 +192,8 @@ impl HTMLElementMethods for HTMLElement { None } } else { - self.upcast::<EventTarget>().get_event_handler_common("load") + self.upcast::<EventTarget>() + .get_event_handler_common("load") } } @@ -174,7 +205,8 @@ impl HTMLElementMethods for HTMLElement { document.window().SetOnload(listener) } } else { - self.upcast::<EventTarget>().set_event_handler_common("load", listener) + self.upcast::<EventTarget>() + .set_event_handler_common("load", listener) } } @@ -188,7 +220,8 @@ impl HTMLElementMethods for HTMLElement { None } } else { - self.upcast::<EventTarget>().get_event_handler_common("resize") + self.upcast::<EventTarget>() + .get_event_handler_common("resize") } } @@ -200,7 +233,8 @@ impl HTMLElementMethods for HTMLElement { document.window().SetOnresize(listener); } } else { - self.upcast::<EventTarget>().set_event_handler_common("resize", listener) + self.upcast::<EventTarget>() + .set_event_handler_common("resize", listener) } } @@ -214,7 +248,8 @@ impl HTMLElementMethods for HTMLElement { None } } else { - self.upcast::<EventTarget>().get_event_handler_common("blur") + self.upcast::<EventTarget>() + .get_event_handler_common("blur") } } @@ -226,7 +261,8 @@ impl HTMLElementMethods for HTMLElement { document.window().SetOnblur(listener) } } else { - self.upcast::<EventTarget>().set_event_handler_common("blur", listener) + self.upcast::<EventTarget>() + .set_event_handler_common("blur", listener) } } @@ -240,7 +276,8 @@ impl HTMLElementMethods for HTMLElement { None } } else { - self.upcast::<EventTarget>().get_event_handler_common("focus") + self.upcast::<EventTarget>() + .get_event_handler_common("focus") } } @@ -252,7 +289,8 @@ impl HTMLElementMethods for HTMLElement { document.window().SetOnfocus(listener) } } else { - self.upcast::<EventTarget>().set_event_handler_common("focus", listener) + self.upcast::<EventTarget>() + .set_event_handler_common("focus", listener) } } @@ -266,7 +304,8 @@ impl HTMLElementMethods for HTMLElement { None } } else { - self.upcast::<EventTarget>().get_event_handler_common("scroll") + self.upcast::<EventTarget>() + .get_event_handler_common("scroll") } } @@ -278,13 +317,16 @@ impl HTMLElementMethods for HTMLElement { document.window().SetOnscroll(listener) } } else { - self.upcast::<EventTarget>().set_event_handler_common("scroll", listener) + self.upcast::<EventTarget>() + .set_event_handler_common("scroll", listener) } } // https://html.spec.whatwg.org/multipage/#attr-itemtype fn Itemtypes(&self) -> Option<Vec<DOMString>> { - let atoms = self.element.get_tokenlist_attribute(&local_name!("itemtype"), ); + let atoms = self + .element + .get_tokenlist_attribute(&local_name!("itemtype")); if atoms.is_empty() { return None; @@ -300,7 +342,9 @@ impl HTMLElementMethods for HTMLElement { // https://html.spec.whatwg.org/multipage/#names:-the-itemprop-attribute fn PropertyNames(&self) -> Option<Vec<DOMString>> { - let atoms = self.element.get_tokenlist_attribute(&local_name!("itemprop"), ); + let atoms = self + .element + .get_tokenlist_attribute(&local_name!("itemprop")); if atoms.is_empty() { return None; @@ -317,12 +361,14 @@ impl HTMLElementMethods for HTMLElement { // https://html.spec.whatwg.org/multipage/#dom-click fn Click(&self) { if !self.upcast::<Element>().disabled_state() { - synthetic_click_activation(self.upcast::<Element>(), - false, - false, - false, - false, - ActivationSource::FromClick) + synthetic_click_activation( + self.upcast::<Element>(), + false, + false, + false, + false, + ActivationSource::FromClick, + ) } } @@ -418,7 +464,9 @@ impl HTMLElementMethods for HTMLElement { return node.GetTextContent().unwrap(); } - window.layout_reflow(QueryMsg::ElementInnerTextQuery(node.to_trusted_node_address())); + window.layout_reflow(QueryMsg::ElementInnerTextQuery( + node.to_trusted_node_address(), + )); DOMString::from(window.layout().element_inner_text()) } @@ -458,7 +506,7 @@ impl HTMLElementMethods for HTMLElement { }, _ => { text.push(ch); - } + }, } } @@ -471,13 +519,12 @@ impl HTMLElementMethods for HTMLElement { } } -fn append_text_node_to_fragment( - document: &Document, - fragment: &DocumentFragment, - text: String -) { +fn append_text_node_to_fragment(document: &Document, fragment: &DocumentFragment, text: String) { let text = Text::new(DOMString::from(text), document); - fragment.upcast::<Node>().AppendChild(&text.upcast()).unwrap(); + fragment + .upcast::<Node>() + .AppendChild(&text.upcast()) + .unwrap(); } // https://html.spec.whatwg.org/multipage/#attr-data-* @@ -507,7 +554,6 @@ fn to_snake_case(name: DOMString) -> DOMString { DOMString::from(attr_name) } - // https://html.spec.whatwg.org/multipage/#attr-data-* // if this attribute is in snake case with a data- prefix, // this function returns a name converted to camel case @@ -546,44 +592,51 @@ fn to_camel_case(name: &str) -> Option<DOMString> { impl HTMLElement { pub fn set_custom_attr(&self, name: DOMString, value: DOMString) -> ErrorResult { - if name.chars() - .skip_while(|&ch| ch != '\u{2d}') - .nth(1).map_or(false, |ch| ch >= 'a' && ch <= 'z') { + if name + .chars() + .skip_while(|&ch| ch != '\u{2d}') + .nth(1) + .map_or(false, |ch| ch >= 'a' && ch <= 'z') + { return Err(Error::Syntax); } - self.upcast::<Element>().set_custom_attribute(to_snake_case(name), value) + self.upcast::<Element>() + .set_custom_attribute(to_snake_case(name), value) } pub fn get_custom_attr(&self, local_name: DOMString) -> Option<DOMString> { // FIXME(ajeffrey): Convert directly from DOMString to LocalName let local_name = LocalName::from(to_snake_case(local_name)); - self.upcast::<Element>().get_attribute(&ns!(), &local_name).map(|attr| { - DOMString::from(&**attr.value()) // FIXME(ajeffrey): Convert directly from AttrValue to DOMString - }) + self.upcast::<Element>() + .get_attribute(&ns!(), &local_name) + .map(|attr| { + DOMString::from(&**attr.value()) // FIXME(ajeffrey): Convert directly from AttrValue to DOMString + }) } pub fn delete_custom_attr(&self, local_name: DOMString) { // FIXME(ajeffrey): Convert directly from DOMString to LocalName let local_name = LocalName::from(to_snake_case(local_name)); - self.upcast::<Element>().remove_attribute(&ns!(), &local_name); + self.upcast::<Element>() + .remove_attribute(&ns!(), &local_name); } // https://html.spec.whatwg.org/multipage/#category-label pub fn is_labelable_element(&self) -> bool { // Note: HTMLKeygenElement is omitted because Servo doesn't currently implement it match self.upcast::<Node>().type_id() { - NodeTypeId::Element(ElementTypeId::HTMLElement(type_id)) => - match type_id { - HTMLElementTypeId::HTMLInputElement => - self.downcast::<HTMLInputElement>().unwrap().input_type() != InputType::Hidden, - HTMLElementTypeId::HTMLButtonElement | - HTMLElementTypeId::HTMLMeterElement | - HTMLElementTypeId::HTMLOutputElement | - HTMLElementTypeId::HTMLProgressElement | - HTMLElementTypeId::HTMLSelectElement | - HTMLElementTypeId::HTMLTextAreaElement => true, - _ => false, + NodeTypeId::Element(ElementTypeId::HTMLElement(type_id)) => match type_id { + HTMLElementTypeId::HTMLInputElement => { + self.downcast::<HTMLInputElement>().unwrap().input_type() != InputType::Hidden }, + HTMLElementTypeId::HTMLButtonElement | + HTMLElementTypeId::HTMLMeterElement | + HTMLElementTypeId::HTMLOutputElement | + HTMLElementTypeId::HTMLProgressElement | + HTMLElementTypeId::HTMLSelectElement | + HTMLElementTypeId::HTMLTextAreaElement => true, + _ => false, + }, _ => false, } } @@ -597,27 +650,29 @@ impl HTMLElement { } match self.upcast::<Node>().type_id() { - NodeTypeId::Element(ElementTypeId::HTMLElement(type_id)) => - match type_id { - HTMLElementTypeId::HTMLButtonElement | - HTMLElementTypeId::HTMLFieldSetElement | - HTMLElementTypeId::HTMLInputElement | - HTMLElementTypeId::HTMLObjectElement | - HTMLElementTypeId::HTMLOutputElement | - HTMLElementTypeId::HTMLSelectElement | - HTMLElementTypeId::HTMLTextAreaElement => true, - _ => false, - }, + NodeTypeId::Element(ElementTypeId::HTMLElement(type_id)) => match type_id { + HTMLElementTypeId::HTMLButtonElement | + HTMLElementTypeId::HTMLFieldSetElement | + HTMLElementTypeId::HTMLInputElement | + HTMLElementTypeId::HTMLObjectElement | + HTMLElementTypeId::HTMLOutputElement | + HTMLElementTypeId::HTMLSelectElement | + HTMLElementTypeId::HTMLTextAreaElement => true, + _ => false, + }, _ => false, } } pub fn supported_prop_names_custom_attr(&self) -> Vec<DOMString> { let element = self.upcast::<Element>(); - element.attrs().iter().filter_map(|attr| { - let raw_name = attr.local_name(); - to_camel_case(&raw_name) - }).collect() + element + .attrs() + .iter() + .filter_map(|attr| { + let raw_name = attr.local_name(); + to_camel_case(&raw_name) + }).collect() } // https://html.spec.whatwg.org/multipage/#dom-lfe-labels @@ -629,8 +684,7 @@ impl HTMLElement { // Traverse ancestors for implicitly associated <label> elements // https://html.spec.whatwg.org/multipage/#the-label-element:attr-label-for-4 - let ancestors = - self.upcast::<Node>() + let ancestors = self.upcast::<Node>() .ancestors() .filter_map(DomRoot::downcast::<HTMLElement>) // If we reach a labelable element, we have a guarantee no ancestors above it @@ -650,11 +704,12 @@ impl HTMLElement { // Traverse entire tree for <label> elements with `for` attribute matching `id` let root_element = element.root_element(); let root_node = root_element.upcast::<Node>(); - let children = root_node.traverse_preorder() - .filter_map(DomRoot::downcast::<Element>) - .filter(|elem| elem.is::<HTMLLabelElement>()) - .filter(|elem| elem.get_string_attribute(&local_name!("for")) == id) - .map(DomRoot::upcast::<Node>); + let children = root_node + .traverse_preorder() + .filter_map(DomRoot::downcast::<Element>) + .filter(|elem| elem.is::<HTMLLabelElement>()) + .filter(|elem| elem.get_string_attribute(&local_name!("for")) == id) + .map(DomRoot::upcast::<Node>); NodeList::new_simple_list(&window, children.chain(ancestors)) } @@ -671,13 +726,15 @@ impl VirtualMethods for HTMLElement { (name, AttributeMutation::Set(_)) if name.starts_with("on") => { let evtarget = self.upcast::<EventTarget>(); let source_line = 1; //TODO(#9604) get current JS execution line - evtarget.set_event_handler_uncompiled(window_from_node(self).get_url(), - source_line, - &name[2..], - // FIXME(ajeffrey): Convert directly from AttrValue to DOMString - DOMString::from(&**attr.value())); + evtarget.set_event_handler_uncompiled( + window_from_node(self).get_url(), + source_line, + &name[2..], + // FIXME(ajeffrey): Convert directly from AttrValue to DOMString + DOMString::from(&**attr.value()), + ); }, - _ => {} + _ => {}, } } @@ -692,12 +749,10 @@ impl VirtualMethods for HTMLElement { match name { &local_name!("itemprop") => AttrValue::from_serialized_tokenlist(value.into()), &local_name!("itemtype") => AttrValue::from_serialized_tokenlist(value.into()), - _ => { - self.super_type().unwrap().parse_plain_attribute( - name, - value, - ) - }, + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(name, value), } } } diff --git a/components/script/dom/htmlembedelement.rs b/components/script/dom/htmlembedelement.rs index cf4039f5515..84266f06019 100644 --- a/components/script/dom/htmlembedelement.rs +++ b/components/script/dom/htmlembedelement.rs @@ -12,22 +12,32 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLEmbedElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLEmbedElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLEmbedElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLEmbedElement { HTMLEmbedElement { - htmlelement: HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLEmbedElement> { - Node::reflect_node(Box::new(HTMLEmbedElement::new_inherited(local_name, prefix, document)), - document, - HTMLEmbedElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLEmbedElement> { + Node::reflect_node( + Box::new(HTMLEmbedElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLEmbedElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlfieldsetelement.rs b/components/script/dom/htmlfieldsetelement.rs index cae9aa49ee5..2b9ca9539c5 100644 --- a/components/script/dom/htmlfieldsetelement.rs +++ b/components/script/dom/htmlfieldsetelement.rs @@ -28,24 +28,35 @@ pub struct HTMLFieldSetElement { } impl HTMLFieldSetElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLFieldSetElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLFieldSetElement { HTMLFieldSetElement { - htmlelement: - HTMLElement::new_inherited_with_state(ElementState::IN_ENABLED_STATE, - local_name, prefix, document), + htmlelement: HTMLElement::new_inherited_with_state( + ElementState::IN_ENABLED_STATE, + local_name, + prefix, + document, + ), form_owner: Default::default(), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLFieldSetElement> { - Node::reflect_node(Box::new(HTMLFieldSetElement::new_inherited(local_name, prefix, document)), - document, - HTMLFieldSetElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLFieldSetElement> { + Node::reflect_node( + Box::new(HTMLFieldSetElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLFieldSetElementBinding::Wrap, + ) } } @@ -116,25 +127,23 @@ impl VirtualMethods for HTMLFieldSetElement { } }); let fields = children.flat_map(|child| { - child.traverse_preorder().filter(|descendant| { - match descendant.type_id() { - NodeTypeId::Element( - ElementTypeId::HTMLElement( - HTMLElementTypeId::HTMLButtonElement)) | - NodeTypeId::Element( - ElementTypeId::HTMLElement( - HTMLElementTypeId::HTMLInputElement)) | - NodeTypeId::Element( - ElementTypeId::HTMLElement( - HTMLElementTypeId::HTMLSelectElement)) | - NodeTypeId::Element( - ElementTypeId::HTMLElement( - HTMLElementTypeId::HTMLTextAreaElement)) => { - true - }, + child + .traverse_preorder() + .filter(|descendant| match descendant.type_id() { + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLButtonElement, + )) | + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLInputElement, + )) | + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLSelectElement, + )) | + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLTextAreaElement, + )) => true, _ => false, - } - }) + }) }); if disabled_state { for field in fields { diff --git a/components/script/dom/htmlfontelement.rs b/components/script/dom/htmlfontelement.rs index 15cea89b320..f704b5fc986 100644 --- a/components/script/dom/htmlfontelement.rs +++ b/components/script/dom/htmlfontelement.rs @@ -25,21 +25,28 @@ pub struct HTMLFontElement { htmlelement: HTMLElement, } - impl HTMLFontElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLFontElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLFontElement { HTMLFontElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLFontElement> { - Node::reflect_node(Box::new(HTMLFontElement::new_inherited(local_name, prefix, document)), - document, - HTMLFontElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLFontElement> { + Node::reflect_node( + Box::new(HTMLFontElement::new_inherited(local_name, prefix, document)), + document, + HTMLFontElementBinding::Wrap, + ) } } @@ -77,7 +84,9 @@ impl VirtualMethods for HTMLFontElement { } // FIXME: Should also return true for `size` and `face` changes! - self.super_type().unwrap().attribute_affects_presentational_hints(attr) + self.super_type() + .unwrap() + .attribute_affects_presentational_hints(attr) } fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { @@ -85,7 +94,10 @@ impl VirtualMethods for HTMLFontElement { &local_name!("face") => AttrValue::from_atomic(value.into()), &local_name!("color") => AttrValue::from_legacy_color(value.into()), &local_name!("size") => parse_size(&value), - _ => self.super_type().unwrap().parse_plain_attribute(name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(name, value), } } } @@ -150,13 +162,13 @@ fn parse_size(mut input: &str) -> AttrValue { // Step 5 Some(&'+') => { - let _ = input_chars.next(); // consume the '+' + let _ = input_chars.next(); // consume the '+' ParseMode::RelativePlus - } + }, Some(&'-') => { - let _ = input_chars.next(); // consume the '-' + let _ = input_chars.next(); // consume the '-' ParseMode::RelativeMinus - } + }, Some(_) => ParseMode::Absolute, }; diff --git a/components/script/dom/htmlformcontrolscollection.rs b/components/script/dom/htmlformcontrolscollection.rs index 76398666f0f..b06810ca9fc 100644 --- a/components/script/dom/htmlformcontrolscollection.rs +++ b/components/script/dom/htmlformcontrolscollection.rs @@ -23,18 +23,25 @@ pub struct HTMLFormControlsCollection { } impl HTMLFormControlsCollection { - fn new_inherited(root: &Node, filter: Box<CollectionFilter + 'static>) -> HTMLFormControlsCollection { + fn new_inherited( + root: &Node, + filter: Box<CollectionFilter + 'static>, + ) -> HTMLFormControlsCollection { HTMLFormControlsCollection { - collection: HTMLCollection::new_inherited(root, filter) + collection: HTMLCollection::new_inherited(root, filter), } } - pub fn new(window: &Window, root: &Node, filter: Box<CollectionFilter + 'static>) - -> DomRoot<HTMLFormControlsCollection> - { - reflect_dom_object(Box::new(HTMLFormControlsCollection::new_inherited(root, filter)), - window, - HTMLFormControlsCollectionBinding::Wrap) + pub fn new( + window: &Window, + root: &Node, + filter: Box<CollectionFilter + 'static>, + ) -> DomRoot<HTMLFormControlsCollection> { + reflect_dom_object( + Box::new(HTMLFormControlsCollection::new_inherited(root, filter)), + window, + HTMLFormControlsCollectionBinding::Wrap, + ) } // FIXME: This shouldn't need to be implemented here since HTMLCollection (the parent of @@ -48,13 +55,18 @@ impl HTMLFormControlsCollectionMethods for HTMLFormControlsCollection { // https://html.spec.whatwg.org/multipage/#dom-htmlformcontrolscollection-nameditem fn NamedItem(&self, name: DOMString) -> Option<RadioNodeListOrElement> { // Step 1 - if name.is_empty() { return None; } + if name.is_empty() { + return None; + } let mut filter_map = self.collection.elements_iter().filter_map(|elem| { - if elem.get_string_attribute(&local_name!("name")) == name - || elem.get_string_attribute(&local_name!("id")) == name { + if elem.get_string_attribute(&local_name!("name")) == name || + elem.get_string_attribute(&local_name!("id")) == name + { Some(elem) - } else { None } + } else { + None + } }); if let Some(elem) = filter_map.next() { @@ -68,11 +80,14 @@ impl HTMLFormControlsCollectionMethods for HTMLFormControlsCollection { let list = once.chain(peekable.map(DomRoot::upcast)); let global = self.global(); let window = global.as_window(); - Some(RadioNodeListOrElement::RadioNodeList(RadioNodeList::new_simple_list(window, list))) + Some(RadioNodeListOrElement::RadioNodeList( + RadioNodeList::new_simple_list(window, list), + )) } // Step 3 - } else { None } - + } else { + None + } } // https://html.spec.whatwg.org/multipage/#dom-htmlformcontrolscollection-nameditem diff --git a/components/script/dom/htmlformelement.rs b/components/script/dom/htmlformelement.rs index d13ac0e5c98..96f011bbb8e 100755 --- a/components/script/dom/htmlformelement.rs +++ b/components/script/dom/htmlformelement.rs @@ -71,9 +71,11 @@ pub struct HTMLFormElement { } impl HTMLFormElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLFormElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLFormElement { HTMLFormElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), marked_for_reset: Cell::new(false), @@ -84,12 +86,16 @@ impl HTMLFormElement { } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLFormElement> { - Node::reflect_node(Box::new(HTMLFormElement::new_inherited(local_name, prefix, document)), - document, - HTMLFormElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLFormElement> { + Node::reflect_node( + Box::new(HTMLFormElement::new_inherited(local_name, prefix, document)), + document, + HTMLFormElementBinding::Wrap, + ) } } @@ -113,10 +119,12 @@ impl HTMLFormElementMethods for HTMLFormElement { make_setter!(SetAutocomplete, "autocomplete"); // https://html.spec.whatwg.org/multipage/#dom-fs-enctype - make_enumerated_getter!(Enctype, - "enctype", - "application/x-www-form-urlencoded", - "text/plain" | "multipart/form-data"); + make_enumerated_getter!( + Enctype, + "enctype", + "application/x-www-form-urlencoded", + "text/plain" | "multipart/form-data" + ); // https://html.spec.whatwg.org/multipage/#dom-fs-enctype make_setter!(SetEnctype, "enctype"); @@ -169,45 +177,45 @@ impl HTMLFormElementMethods for HTMLFormElement { fn Elements(&self) -> DomRoot<HTMLFormControlsCollection> { #[derive(JSTraceable, MallocSizeOf)] struct ElementsFilter { - form: DomRoot<HTMLFormElement> + form: DomRoot<HTMLFormElement>, } impl CollectionFilter for ElementsFilter { fn filter<'a>(&self, elem: &'a Element, _root: &'a Node) -> bool { let form_owner = match elem.upcast::<Node>().type_id() { - NodeTypeId::Element(ElementTypeId::HTMLElement(t)) => { - match t { - HTMLElementTypeId::HTMLButtonElement => { - elem.downcast::<HTMLButtonElement>().unwrap().form_owner() - } - HTMLElementTypeId::HTMLFieldSetElement => { - elem.downcast::<HTMLFieldSetElement>().unwrap().form_owner() - } - HTMLElementTypeId::HTMLInputElement => { - let input_elem = elem.downcast::<HTMLInputElement>().unwrap(); - if input_elem.input_type() == InputType::Image { - return false; - } - input_elem.form_owner() - } - HTMLElementTypeId::HTMLObjectElement => { - elem.downcast::<HTMLObjectElement>().unwrap().form_owner() - } - HTMLElementTypeId::HTMLOutputElement => { - elem.downcast::<HTMLOutputElement>().unwrap().form_owner() - } - HTMLElementTypeId::HTMLSelectElement => { - elem.downcast::<HTMLSelectElement>().unwrap().form_owner() - } - HTMLElementTypeId::HTMLTextAreaElement => { - elem.downcast::<HTMLTextAreaElement>().unwrap().form_owner() - } - _ => { - debug_assert!(!elem.downcast::<HTMLElement>().unwrap().is_listed_element() || - elem.local_name() == &local_name!("keygen")); + NodeTypeId::Element(ElementTypeId::HTMLElement(t)) => match t { + HTMLElementTypeId::HTMLButtonElement => { + elem.downcast::<HTMLButtonElement>().unwrap().form_owner() + }, + HTMLElementTypeId::HTMLFieldSetElement => { + elem.downcast::<HTMLFieldSetElement>().unwrap().form_owner() + }, + HTMLElementTypeId::HTMLInputElement => { + let input_elem = elem.downcast::<HTMLInputElement>().unwrap(); + if input_elem.input_type() == InputType::Image { return false; } - } - } + input_elem.form_owner() + }, + HTMLElementTypeId::HTMLObjectElement => { + elem.downcast::<HTMLObjectElement>().unwrap().form_owner() + }, + HTMLElementTypeId::HTMLOutputElement => { + elem.downcast::<HTMLOutputElement>().unwrap().form_owner() + }, + HTMLElementTypeId::HTMLSelectElement => { + elem.downcast::<HTMLSelectElement>().unwrap().form_owner() + }, + HTMLElementTypeId::HTMLTextAreaElement => { + elem.downcast::<HTMLTextAreaElement>().unwrap().form_owner() + }, + _ => { + debug_assert!( + !elem.downcast::<HTMLElement>().unwrap().is_listed_element() || + elem.local_name() == &local_name!("keygen") + ); + return false; + }, + }, _ => return false, }; @@ -218,7 +226,9 @@ impl HTMLFormElementMethods for HTMLFormElement { } } DomRoot::from_ref(self.elements.init_once(|| { - let filter = Box::new(ElementsFilter { form: DomRoot::from_ref(self) }); + let filter = Box::new(ElementsFilter { + form: DomRoot::from_ref(self), + }); let window = window_from_node(self); HTMLFormControlsCollection::new(&window, self.upcast(), filter) })) @@ -239,27 +249,31 @@ impl HTMLFormElementMethods for HTMLFormElement { #[derive(Clone, Copy, MallocSizeOf, PartialEq)] pub enum SubmittedFrom { FromForm, - NotFromForm + NotFromForm, } #[derive(Clone, Copy, MallocSizeOf)] pub enum ResetFrom { FromForm, - NotFromForm + NotFromForm, } - impl HTMLFormElement { // https://html.spec.whatwg.org/multipage/#picking-an-encoding-for-the-form fn pick_encoding(&self) -> &'static Encoding { // Step 2 - if self.upcast::<Element>().has_attribute(&local_name!("accept-charset")) { + if self + .upcast::<Element>() + .has_attribute(&local_name!("accept-charset")) + { // Substep 1 - let input = self.upcast::<Element>().get_string_attribute(&local_name!("accept-charset")); + let input = self + .upcast::<Element>() + .get_string_attribute(&local_name!("accept-charset")); // Substep 2, 3, 4 - let mut candidate_encodings = split_html_space_chars(&*input) - .filter_map(|c| Encoding::for_label(c.as_bytes())); + let mut candidate_encodings = + split_html_space_chars(&*input).filter_map(|c| Encoding::for_label(c.as_bytes())); // Substep 5, 6 return candidate_encodings.next().unwrap_or(UTF_8); @@ -299,9 +313,7 @@ impl HTMLFormElement { let base = doc.base_url(); // TODO: Handle browsing contexts (Step 2, 3) // Step 4 - if submit_method_flag == SubmittedFrom::NotFromForm && - !submitter.no_validate(self) - { + if submit_method_flag == SubmittedFrom::NotFromForm && !submitter.no_validate(self) { if self.interactive_validation().is_err() { // TODO: Implement event handlers on all form control elements self.upcast::<EventTarget>().fire_event(atom!("invalid")); @@ -310,7 +322,8 @@ impl HTMLFormElement { } // Step 5 if submit_method_flag == SubmittedFrom::NotFromForm { - let event = self.upcast::<EventTarget>() + let event = self + .upcast::<EventTarget>() .fire_bubbling_cancelable_event(atom!("submit")); if event.DefaultPrevented() { return; @@ -332,7 +345,7 @@ impl HTMLFormElement { // Step 10-11 let action_components = match base.join(&action) { Ok(url) => url, - Err(_) => return + Err(_) => return, }; // Step 12-15 let scheme = action_components.scheme().to_owned(); @@ -345,74 +358,94 @@ impl HTMLFormElement { let (maybe_chosen, _new) = source.choose_browsing_context(target_attribute_value, false); let chosen = match maybe_chosen { Some(proxy) => proxy, - None => return + None => return, }; let target_document = match chosen.document() { Some(doc) => doc, - None => return + None => return, }; let target_window = target_document.window(); - let mut load_data = LoadData::new(action_components, - None, - target_document.get_referrer_policy(), - Some(target_document.url())); + let mut load_data = LoadData::new( + action_components, + None, + target_document.get_referrer_policy(), + Some(target_document.url()), + ); // Step 18 match (&*scheme, method) { (_, FormMethod::FormDialog) => { // TODO: Submit dialog // https://html.spec.whatwg.org/multipage/#submit-dialog - } + }, // https://html.spec.whatwg.org/multipage/#submit-mutate-action - ("http", FormMethod::FormGet) | ("https", FormMethod::FormGet) | ("data", FormMethod::FormGet) => { + ("http", FormMethod::FormGet) | + ("https", FormMethod::FormGet) | + ("data", FormMethod::FormGet) => { load_data.headers.set(ContentType::form_url_encoded()); self.mutate_action_url(&mut form_data, load_data, encoding, &target_window); - } + }, // https://html.spec.whatwg.org/multipage/#submit-body ("http", FormMethod::FormPost) | ("https", FormMethod::FormPost) => { load_data.method = Method::Post; - self.submit_entity_body(&mut form_data, load_data, enctype, encoding, &target_window); - } + self.submit_entity_body( + &mut form_data, + load_data, + enctype, + encoding, + &target_window, + ); + }, // https://html.spec.whatwg.org/multipage/#submit-get-action - ("file", _) | ("about", _) | ("data", FormMethod::FormPost) | - ("ftp", _) | ("javascript", _) => { + ("file", _) | + ("about", _) | + ("data", FormMethod::FormPost) | + ("ftp", _) | + ("javascript", _) => { self.plan_to_navigate(load_data, &target_window); - } + }, ("mailto", FormMethod::FormPost) => { // TODO: Mail as body // https://html.spec.whatwg.org/multipage/#submit-mailto-body - } + }, ("mailto", FormMethod::FormGet) => { // TODO: Mail with headers // https://html.spec.whatwg.org/multipage/#submit-mailto-headers - } + }, _ => return, } } // https://html.spec.whatwg.org/multipage/#submit-mutate-action - fn mutate_action_url(&self, - form_data: &mut Vec<FormDatum>, - mut load_data: LoadData, - encoding: &'static Encoding, - target: &Window) { + fn mutate_action_url( + &self, + form_data: &mut Vec<FormDatum>, + mut load_data: LoadData, + encoding: &'static Encoding, + target: &Window, + ) { let charset = encoding.name(); self.set_encoding_override(load_data.url.as_mut_url().query_pairs_mut()) .clear() - .extend_pairs(form_data.into_iter() - .map(|field| (field.name.clone(), field.replace_value(charset)))); + .extend_pairs( + form_data + .into_iter() + .map(|field| (field.name.clone(), field.replace_value(charset))), + ); self.plan_to_navigate(load_data, target); } // https://html.spec.whatwg.org/multipage/#submit-body - fn submit_entity_body(&self, - form_data: &mut Vec<FormDatum>, - mut load_data: LoadData, - enctype: FormEncType, - encoding: &'static Encoding, - target: &Window) { + fn submit_entity_body( + &self, + form_data: &mut Vec<FormDatum>, + mut load_data: LoadData, + enctype: FormEncType, + encoding: &'static Encoding, + target: &Window, + ) { let boundary = generate_boundary(); let bytes = match enctype { FormEncType::UrlEncoded => { @@ -421,28 +454,33 @@ impl HTMLFormElement { self.set_encoding_override(load_data.url.as_mut_url().query_pairs_mut()) .clear() - .extend_pairs(form_data.into_iter() - .map(|field| (field.name.clone(), field.replace_value(charset)))); + .extend_pairs( + form_data + .into_iter() + .map(|field| (field.name.clone(), field.replace_value(charset))), + ); load_data.url.query().unwrap_or("").to_string().into_bytes() - } + }, FormEncType::FormDataEncoded => { let mime = mime!(Multipart / FormData; Boundary =(&boundary)); load_data.headers.set(ContentType(mime)); encode_multipart_form_data(form_data, boundary, encoding) - } + }, FormEncType::TextPlainEncoded => { load_data.headers.set(ContentType(mime!(Text / Plain))); self.encode_plaintext(form_data).into_bytes() - } + }, }; load_data.data = Some(bytes); self.plan_to_navigate(load_data, target); } - fn set_encoding_override<'a>(&self, mut serializer: Serializer<UrlQuery<'a>>) - -> Serializer<UrlQuery<'a>> { + fn set_encoding_override<'a>( + &self, + mut serializer: Serializer<UrlQuery<'a>>, + ) -> Serializer<UrlQuery<'a>> { let encoding = self.pick_encoding(); serializer.custom_encoding_override(move |s| encoding.encode(s).0); serializer @@ -473,7 +511,10 @@ impl HTMLFormElement { }); // Step 3. - target.dom_manipulation_task_source().queue(task, target.upcast()).unwrap(); + target + .dom_manipulation_task_source() + .queue(task, target.upcast()) + .unwrap(); } /// Interactively validate the constraints of form elements @@ -482,7 +523,7 @@ impl HTMLFormElement { // Step 1-3 let _unhandled_invalid_controls = match self.static_validation() { Ok(()) => return Ok(()), - Err(err) => err + Err(err) => err, }; // TODO: Report the problems with the constraints of at least one of // the elements given in unhandled invalid controls to the user @@ -497,36 +538,45 @@ impl HTMLFormElement { // FIXME(#3553): This is an incorrect way of getting controls owned by the // form, refactor this when html5ever's form owner PR lands // Step 1-3 - let invalid_controls = node.traverse_preorder().filter_map(|field| { - if let Some(el) = field.downcast::<Element>() { - if el.disabled_state() { - None - } else { - let validatable = match el.as_maybe_validatable() { - Some(v) => v, - None => return None - }; - if !validatable.is_instance_validatable() { - None - } else if validatable.validate(ValidationFlags::empty()) { + let invalid_controls = node + .traverse_preorder() + .filter_map(|field| { + if let Some(el) = field.downcast::<Element>() { + if el.disabled_state() { None } else { - Some(FormSubmittableElement::from_element(&el)) + let validatable = match el.as_maybe_validatable() { + Some(v) => v, + None => return None, + }; + if !validatable.is_instance_validatable() { + None + } else if validatable.validate(ValidationFlags::empty()) { + None + } else { + Some(FormSubmittableElement::from_element(&el)) + } } + } else { + None } - } else { - None - } - }).collect::<Vec<FormSubmittableElement>>(); + }).collect::<Vec<FormSubmittableElement>>(); // Step 4 - if invalid_controls.is_empty() { return Ok(()); } + if invalid_controls.is_empty() { + return Ok(()); + } // Step 5-6 - let unhandled_invalid_controls = invalid_controls.into_iter().filter_map(|field| { - let event = field.as_event_target() - .fire_cancelable_event(atom!("invalid")); - if !event.DefaultPrevented() { return Some(field); } - None - }).collect::<Vec<FormSubmittableElement>>(); + let unhandled_invalid_controls = invalid_controls + .into_iter() + .filter_map(|field| { + let event = field + .as_event_target() + .fire_cancelable_event(atom!("invalid")); + if !event.DefaultPrevented() { + return Some(field); + } + None + }).collect::<Vec<FormSubmittableElement>>(); // Step 7 Err(unhandled_invalid_controls) } @@ -544,8 +594,10 @@ impl HTMLFormElement { let child = child.upcast::<Node>(); // Step 3.1: The field element has a datalist element ancestor. - if child.ancestors() - .any(|a| DomRoot::downcast::<HTMLDataListElement>(a).is_some()) { + if child + .ancestors() + .any(|a| DomRoot::downcast::<HTMLDataListElement>(a).is_some()) + { continue; } if let NodeTypeId::Element(ElementTypeId::HTMLElement(element)) = child.type_id() { @@ -554,21 +606,21 @@ impl HTMLFormElement { let input = child.downcast::<HTMLInputElement>().unwrap(); data_set.append(&mut input.form_datums(submitter)); - } + }, HTMLElementTypeId::HTMLButtonElement => { let button = child.downcast::<HTMLButtonElement>().unwrap(); if let Some(datum) = button.form_datum(submitter) { data_set.push(datum); } - } + }, HTMLElementTypeId::HTMLObjectElement => { // Unimplemented () - } + }, HTMLElementTypeId::HTMLSelectElement => { let select = child.downcast::<HTMLSelectElement>().unwrap(); select.push_form_data(&mut data_set); - } + }, HTMLElementTypeId::HTMLTextAreaElement => { let textarea = child.downcast::<HTMLTextAreaElement>().unwrap(); let name = textarea.Name(); @@ -576,11 +628,11 @@ impl HTMLFormElement { data_set.push(FormDatum { ty: textarea.Type(), name: name, - value: FormDatumValue::String(textarea.Value()) + value: FormDatumValue::String(textarea.Value()), }); } - } - _ => () + }, + _ => (), } } } @@ -611,7 +663,7 @@ impl HTMLFormElement { buf.push('\n'); buf.push(ch); }, - _ => buf.push(ch) + _ => buf.push(ch), }; prev = ch; } @@ -632,11 +684,11 @@ impl HTMLFormElement { datum.name = clean_crlf(&datum.name); datum.value = FormDatumValue::String(clean_crlf(match datum.value { FormDatumValue::String(ref s) => s, - FormDatumValue::File(_) => unreachable!() + FormDatumValue::File(_) => unreachable!(), })); - } + }, } - }; + } // Step 5 ret } @@ -649,7 +701,8 @@ impl HTMLFormElement { self.marked_for_reset.set(true); } - let event = self.upcast::<EventTarget>() + let event = self + .upcast::<EventTarget>() .fire_bubbling_cancelable_event(atom!("reset")); if event.DefaultPrevented() { return; @@ -660,24 +713,32 @@ impl HTMLFormElement { let child = child.upcast::<Node>(); match child.type_id() { - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => { + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLInputElement, + )) => { child.downcast::<HTMLInputElement>().unwrap().reset(); - } + }, // TODO HTMLKeygenElement unimplemented //NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLKeygenElement)) => { // // Unimplemented // {} //} - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) => { + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLSelectElement, + )) => { child.downcast::<HTMLSelectElement>().unwrap().reset(); - } - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => { + }, + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLTextAreaElement, + )) => { child.downcast::<HTMLTextAreaElement>().unwrap().reset(); - } - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOutputElement)) => { + }, + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLOutputElement, + )) => { // Unimplemented - } - _ => {} + }, + _ => {}, } } self.marked_for_reset.set(false); @@ -694,8 +755,10 @@ impl HTMLFormElement { fn remove_control<T: ?Sized + FormControl>(&self, control: &T) { let control = control.to_element(); let mut controls = self.controls.borrow_mut(); - controls.iter().position(|c| c.r() == control) - .map(|idx| controls.remove(idx)); + controls + .iter() + .position(|c| c.r() == control) + .map(|idx| controls.remove(idx)); } } @@ -703,14 +766,14 @@ impl HTMLFormElement { pub enum FormDatumValue { #[allow(dead_code)] File(DomRoot<File>), - String(DOMString) + String(DOMString), } #[derive(Clone, JSTraceable, MallocSizeOf)] pub struct FormDatum { pub ty: DOMString, pub name: DOMString, - pub value: FormDatumValue + pub value: FormDatumValue, } impl FormDatum { @@ -730,14 +793,14 @@ impl FormDatum { pub enum FormEncType { TextPlainEncoded, UrlEncoded, - FormDataEncoded + FormDataEncoded, } #[derive(Clone, Copy, MallocSizeOf)] pub enum FormMethod { FormGet, FormPost, - FormDialog + FormDialog, } #[derive(MallocSizeOf)] @@ -759,24 +822,20 @@ impl FormSubmittableElement { FormSubmittableElement::InputElement(ref input) => input.upcast(), FormSubmittableElement::ObjectElement(ref object) => object.upcast(), FormSubmittableElement::SelectElement(ref select) => select.upcast(), - FormSubmittableElement::TextAreaElement(ref textarea) => textarea.upcast() + FormSubmittableElement::TextAreaElement(ref textarea) => textarea.upcast(), } } fn from_element(element: &Element) -> FormSubmittableElement { if let Some(input) = element.downcast::<HTMLInputElement>() { FormSubmittableElement::InputElement(DomRoot::from_ref(&input)) - } - else if let Some(input) = element.downcast::<HTMLButtonElement>() { + } else if let Some(input) = element.downcast::<HTMLButtonElement>() { FormSubmittableElement::ButtonElement(DomRoot::from_ref(&input)) - } - else if let Some(input) = element.downcast::<HTMLObjectElement>() { + } else if let Some(input) = element.downcast::<HTMLObjectElement>() { FormSubmittableElement::ObjectElement(DomRoot::from_ref(&input)) - } - else if let Some(input) = element.downcast::<HTMLSelectElement>() { + } else if let Some(input) = element.downcast::<HTMLSelectElement>() { FormSubmittableElement::SelectElement(DomRoot::from_ref(&input)) - } - else if let Some(input) = element.downcast::<HTMLTextAreaElement>() { + } else if let Some(input) = element.downcast::<HTMLTextAreaElement>() { FormSubmittableElement::TextAreaElement(DomRoot::from_ref(&input)) } else { unreachable!() @@ -788,100 +847,100 @@ impl FormSubmittableElement { pub enum FormSubmitter<'a> { FormElement(&'a HTMLFormElement), InputElement(&'a HTMLInputElement), - ButtonElement(&'a HTMLButtonElement) - // TODO: image submit, etc etc + ButtonElement(&'a HTMLButtonElement), // TODO: image submit, etc etc } impl<'a> FormSubmitter<'a> { fn action(&self) -> DOMString { match *self { FormSubmitter::FormElement(form) => form.Action(), - FormSubmitter::InputElement(input_element) => { - input_element.get_form_attribute(&local_name!("formaction"), - |i| i.FormAction(), - |f| f.Action()) - }, - FormSubmitter::ButtonElement(button_element) => { - button_element.get_form_attribute(&local_name!("formaction"), - |i| i.FormAction(), - |f| f.Action()) - } + FormSubmitter::InputElement(input_element) => input_element.get_form_attribute( + &local_name!("formaction"), + |i| i.FormAction(), + |f| f.Action(), + ), + FormSubmitter::ButtonElement(button_element) => button_element.get_form_attribute( + &local_name!("formaction"), + |i| i.FormAction(), + |f| f.Action(), + ), } } fn enctype(&self) -> FormEncType { let attr = match *self { FormSubmitter::FormElement(form) => form.Enctype(), - FormSubmitter::InputElement(input_element) => { - input_element.get_form_attribute(&local_name!("formenctype"), - |i| i.FormEnctype(), - |f| f.Enctype()) - }, - FormSubmitter::ButtonElement(button_element) => { - button_element.get_form_attribute(&local_name!("formenctype"), - |i| i.FormEnctype(), - |f| f.Enctype()) - } + FormSubmitter::InputElement(input_element) => input_element.get_form_attribute( + &local_name!("formenctype"), + |i| i.FormEnctype(), + |f| f.Enctype(), + ), + FormSubmitter::ButtonElement(button_element) => button_element.get_form_attribute( + &local_name!("formenctype"), + |i| i.FormEnctype(), + |f| f.Enctype(), + ), }; match &*attr { "multipart/form-data" => FormEncType::FormDataEncoded, "text/plain" => FormEncType::TextPlainEncoded, // https://html.spec.whatwg.org/multipage/#attr-fs-enctype // urlencoded is the default - _ => FormEncType::UrlEncoded + _ => FormEncType::UrlEncoded, } } fn method(&self) -> FormMethod { let attr = match *self { FormSubmitter::FormElement(form) => form.Method(), - FormSubmitter::InputElement(input_element) => { - input_element.get_form_attribute(&local_name!("formmethod"), - |i| i.FormMethod(), - |f| f.Method()) - }, - FormSubmitter::ButtonElement(button_element) => { - button_element.get_form_attribute(&local_name!("formmethod"), - |i| i.FormMethod(), - |f| f.Method()) - } + FormSubmitter::InputElement(input_element) => input_element.get_form_attribute( + &local_name!("formmethod"), + |i| i.FormMethod(), + |f| f.Method(), + ), + FormSubmitter::ButtonElement(button_element) => button_element.get_form_attribute( + &local_name!("formmethod"), + |i| i.FormMethod(), + |f| f.Method(), + ), }; match &*attr { "dialog" => FormMethod::FormDialog, "post" => FormMethod::FormPost, - _ => FormMethod::FormGet + _ => FormMethod::FormGet, } } fn target(&self) -> DOMString { match *self { FormSubmitter::FormElement(form) => form.Target(), - FormSubmitter::InputElement(input_element) => { - input_element.get_form_attribute(&local_name!("formtarget"), - |i| i.FormTarget(), - |f| f.Target()) - }, - FormSubmitter::ButtonElement(button_element) => { - button_element.get_form_attribute(&local_name!("formtarget"), - |i| i.FormTarget(), - |f| f.Target()) - } + FormSubmitter::InputElement(input_element) => input_element.get_form_attribute( + &local_name!("formtarget"), + |i| i.FormTarget(), + |f| f.Target(), + ), + FormSubmitter::ButtonElement(button_element) => button_element.get_form_attribute( + &local_name!("formtarget"), + |i| i.FormTarget(), + |f| f.Target(), + ), } } fn no_validate(&self, _form_owner: &HTMLFormElement) -> bool { match *self { FormSubmitter::FormElement(form) => form.NoValidate(), - FormSubmitter::InputElement(input_element) => { - input_element.get_form_boolean_attribute(&local_name!("formnovalidate"), - |i| i.FormNoValidate(), - |f| f.NoValidate()) - } - FormSubmitter::ButtonElement(button_element) => { - button_element.get_form_boolean_attribute(&local_name!("formnovalidate"), - |i| i.FormNoValidate(), - |f| f.NoValidate()) - } + FormSubmitter::InputElement(input_element) => input_element.get_form_boolean_attribute( + &local_name!("formnovalidate"), + |i| i.FormNoValidate(), + |f| f.NoValidate(), + ), + FormSubmitter::ButtonElement(button_element) => button_element + .get_form_boolean_attribute( + &local_name!("formnovalidate"), + |i| i.FormNoValidate(), + |f| f.NoValidate(), + ), } } } @@ -915,9 +974,10 @@ pub trait FormControl: DomObject { let node = elem.upcast::<Node>(); let old_owner = self.form_owner(); let has_form_id = elem.has_attribute(&local_name!("form")); - let nearest_form_ancestor = node.ancestors() - .filter_map(DomRoot::downcast::<HTMLFormElement>) - .next(); + let nearest_form_ancestor = node + .ancestors() + .filter_map(DomRoot::downcast::<HTMLFormElement>) + .next(); // Step 1 if old_owner.is_some() && !(self.is_listed() && has_form_id) { @@ -930,7 +990,8 @@ pub trait FormControl: DomObject { // Step 3 let doc = document_from_node(node); let form_id = elem.get_string_attribute(&local_name!("form")); - doc.GetElementById(form_id).and_then(DomRoot::downcast::<HTMLFormElement>) + doc.GetElementById(form_id) + .and_then(DomRoot::downcast::<HTMLFormElement>) } else { // Step 4 nearest_form_ancestor @@ -1005,9 +1066,9 @@ pub trait FormControl: DomObject { fn unbind_form_control_from_tree(&self) { let elem = self.to_element(); let has_form_attr = elem.has_attribute(&local_name!("form")); - let same_subtree = self.form_owner().map_or(true, |form| { - elem.is_in_same_home_subtree(&*form) - }); + let same_subtree = self + .form_owner() + .map_or(true, |form| elem.is_in_same_home_subtree(&*form)); self.unregister_if_necessary(); @@ -1021,13 +1082,16 @@ pub trait FormControl: DomObject { } } - fn get_form_attribute<InputFn, OwnerFn>(&self, - attr: &LocalName, - input: InputFn, - owner: OwnerFn) - -> DOMString - where InputFn: Fn(&Self) -> DOMString, - OwnerFn: Fn(&HTMLFormElement) -> DOMString, Self: Sized + fn get_form_attribute<InputFn, OwnerFn>( + &self, + attr: &LocalName, + input: InputFn, + owner: OwnerFn, + ) -> DOMString + where + InputFn: Fn(&Self) -> DOMString, + OwnerFn: Fn(&HTMLFormElement) -> DOMString, + Self: Sized, { if self.to_element().has_attribute(attr) { input(self) @@ -1036,13 +1100,16 @@ pub trait FormControl: DomObject { } } - fn get_form_boolean_attribute<InputFn, OwnerFn>(&self, - attr: &LocalName, - input: InputFn, - owner: OwnerFn) - -> bool - where InputFn: Fn(&Self) -> bool, - OwnerFn: Fn(&HTMLFormElement) -> bool, Self: Sized + fn get_form_boolean_attribute<InputFn, OwnerFn>( + &self, + attr: &LocalName, + input: InputFn, + owner: OwnerFn, + ) -> bool + where + InputFn: Fn(&Self) -> bool, + OwnerFn: Fn(&HTMLFormElement) -> bool, + Self: Sized, { if self.to_element().has_attribute(attr) { input(self) @@ -1064,7 +1131,10 @@ impl VirtualMethods for HTMLFormElement { fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("name") => AttrValue::from_atomic(value.into()), - _ => self.super_type().unwrap().parse_plain_attribute(name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(name, value), } } @@ -1074,14 +1144,19 @@ impl VirtualMethods for HTMLFormElement { // Collect the controls to reset because reset_form_owner // will mutably borrow self.controls rooted_vec!(let mut to_reset); - to_reset.extend(self.controls.borrow().iter() - .filter(|c| !c.is_in_same_home_subtree(self)) - .map(|c| c.clone())); + to_reset.extend( + self.controls + .borrow() + .iter() + .filter(|c| !c.is_in_same_home_subtree(self)) + .map(|c| c.clone()), + ); for control in to_reset.iter() { - control.as_maybe_form_control() - .expect("Element must be a form control") - .reset_form_owner(); + control + .as_maybe_form_control() + .expect("Element must be a form control") + .reset_form_owner(); } } } @@ -1095,46 +1170,47 @@ impl FormControlElementHelpers for Element { let node = self.upcast::<Node>(); match node.type_id() { - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) => { - Some(self.downcast::<HTMLButtonElement>().unwrap() as &FormControl) - }, - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFieldSetElement)) => { - Some(self.downcast::<HTMLFieldSetElement>().unwrap() as &FormControl) - }, - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLImageElement)) => { - Some(self.downcast::<HTMLImageElement>().unwrap() as &FormControl) - }, - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => { - Some(self.downcast::<HTMLInputElement>().unwrap() as &FormControl) - }, - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLabelElement)) => { - Some(self.downcast::<HTMLLabelElement>().unwrap() as &FormControl) - }, - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLegendElement)) => { - Some(self.downcast::<HTMLLegendElement>().unwrap() as &FormControl) - }, - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLObjectElement)) => { - Some(self.downcast::<HTMLObjectElement>().unwrap() as &FormControl) - }, - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOutputElement)) => { - Some(self.downcast::<HTMLOutputElement>().unwrap() as &FormControl) - }, - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) => { - Some(self.downcast::<HTMLSelectElement>().unwrap() as &FormControl) - }, - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => { - Some(self.downcast::<HTMLTextAreaElement>().unwrap() as &FormControl) - }, - _ => { - None - } + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLButtonElement, + )) => Some(self.downcast::<HTMLButtonElement>().unwrap() as &FormControl), + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLFieldSetElement, + )) => Some(self.downcast::<HTMLFieldSetElement>().unwrap() as &FormControl), + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLImageElement, + )) => Some(self.downcast::<HTMLImageElement>().unwrap() as &FormControl), + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLInputElement, + )) => Some(self.downcast::<HTMLInputElement>().unwrap() as &FormControl), + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLLabelElement, + )) => Some(self.downcast::<HTMLLabelElement>().unwrap() as &FormControl), + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLLegendElement, + )) => Some(self.downcast::<HTMLLegendElement>().unwrap() as &FormControl), + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLObjectElement, + )) => Some(self.downcast::<HTMLObjectElement>().unwrap() as &FormControl), + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLOutputElement, + )) => Some(self.downcast::<HTMLOutputElement>().unwrap() as &FormControl), + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLSelectElement, + )) => Some(self.downcast::<HTMLSelectElement>().unwrap() as &FormControl), + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLTextAreaElement, + )) => Some(self.downcast::<HTMLTextAreaElement>().unwrap() as &FormControl), + _ => None, } } } // https://html.spec.whatwg.org/multipage/#multipart/form-data-encoding-algorithm -pub fn encode_multipart_form_data(form_data: &mut Vec<FormDatum>, - boundary: String, encoding: &'static Encoding) -> Vec<u8> { +pub fn encode_multipart_form_data( + form_data: &mut Vec<FormDatum>, + boundary: String, + encoding: &'static Encoding, +) -> Vec<u8> { // Step 1 let mut result = vec![]; @@ -1157,32 +1233,44 @@ pub fn encode_multipart_form_data(form_data: &mut Vec<FormDatum>, result.append(&mut boundary_bytes); let mut content_disposition = ContentDisposition { disposition: DispositionType::Ext("form-data".to_owned()), - parameters: vec![DispositionParam::Ext("name".to_owned(), String::from(entry.name.clone()))] + parameters: vec![DispositionParam::Ext( + "name".to_owned(), + String::from(entry.name.clone()), + )], }; match entry.value { FormDatumValue::String(ref s) => { - let mut bytes = format!("Content-Disposition: {}\r\n\r\n{}", - content_disposition, s).into_bytes(); + let mut bytes = + format!("Content-Disposition: {}\r\n\r\n{}", content_disposition, s) + .into_bytes(); result.append(&mut bytes); - } + }, FormDatumValue::File(ref f) => { - content_disposition.parameters.push( - DispositionParam::Filename(Charset::Ext(String::from(charset.clone())), - None, - f.name().clone().into())); + content_disposition + .parameters + .push(DispositionParam::Filename( + Charset::Ext(String::from(charset.clone())), + None, + f.name().clone().into(), + )); // https://tools.ietf.org/html/rfc7578#section-4.4 - let content_type = ContentType(f.upcast::<Blob>().Type() - .parse().unwrap_or(mime!(Text / Plain))); - let mut type_bytes = format!("Content-Disposition: {}\r\ncontent-type: {}\r\n\r\n", - content_disposition, - content_type).into_bytes(); + let content_type = ContentType( + f.upcast::<Blob>() + .Type() + .parse() + .unwrap_or(mime!(Text / Plain)), + ); + let mut type_bytes = format!( + "Content-Disposition: {}\r\ncontent-type: {}\r\n\r\n", + content_disposition, content_type + ).into_bytes(); result.append(&mut type_bytes); let mut bytes = f.upcast::<Blob>().get_bytes().unwrap_or(vec![]); result.append(&mut bytes); - } + }, } } diff --git a/components/script/dom/htmlframeelement.rs b/components/script/dom/htmlframeelement.rs index c7e282ca4a5..83ad119ada7 100644 --- a/components/script/dom/htmlframeelement.rs +++ b/components/script/dom/htmlframeelement.rs @@ -12,22 +12,32 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLFrameElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLFrameElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLFrameElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLFrameElement { HTMLFrameElement { - htmlelement: HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLFrameElement> { - Node::reflect_node(Box::new(HTMLFrameElement::new_inherited(local_name, prefix, document)), - document, - HTMLFrameElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLFrameElement> { + Node::reflect_node( + Box::new(HTMLFrameElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLFrameElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlframesetelement.rs b/components/script/dom/htmlframesetelement.rs index 909ab214ade..a507b82481a 100644 --- a/components/script/dom/htmlframesetelement.rs +++ b/components/script/dom/htmlframesetelement.rs @@ -14,26 +14,33 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLFrameSetElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLFrameSetElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLFrameSetElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLFrameSetElement { HTMLFrameSetElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLFrameSetElement> { - Node::reflect_node(Box::new(HTMLFrameSetElement::new_inherited(local_name, prefix, document)), - document, - HTMLFrameSetElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLFrameSetElement> { + Node::reflect_node( + Box::new(HTMLFrameSetElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLFrameSetElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlheadelement.rs b/components/script/dom/htmlheadelement.rs index 6d88bcb08b3..de0c06a08e6 100644 --- a/components/script/dom/htmlheadelement.rs +++ b/components/script/dom/htmlheadelement.rs @@ -18,25 +18,31 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLHeadElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLHeadElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLHeadElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLHeadElement { HTMLHeadElement { - htmlelement: HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLHeadElement> { - Node::reflect_node(Box::new(HTMLHeadElement::new_inherited(local_name, prefix, document)), - document, - HTMLHeadElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLHeadElement> { + Node::reflect_node( + Box::new(HTMLHeadElement::new_inherited(local_name, prefix, document)), + document, + HTMLHeadElementBinding::Wrap, + ) } /// <https://html.spec.whatwg.org/multipage/#meta-referrer> @@ -48,11 +54,15 @@ impl HTMLHeadElement { } let node = self.upcast::<Node>(); - let candidates = node.traverse_preorder() - .filter_map(DomRoot::downcast::<Element>) - .filter(|elem| elem.is::<HTMLMetaElement>()) - .filter(|elem| elem.get_string_attribute(&local_name!("name")) == "referrer") - .filter(|elem| elem.get_attribute(&ns!(), &local_name!("content")).is_some()); + let candidates = node + .traverse_preorder() + .filter_map(DomRoot::downcast::<Element>) + .filter(|elem| elem.is::<HTMLMetaElement>()) + .filter(|elem| elem.get_string_attribute(&local_name!("name")) == "referrer") + .filter(|elem| { + elem.get_attribute(&ns!(), &local_name!("content")) + .is_some() + }); for meta in candidates { if let Some(content) = meta.get_attribute(&ns!(), &local_name!("content")).r() { diff --git a/components/script/dom/htmlheadingelement.rs b/components/script/dom/htmlheadingelement.rs index 5dbf23fa157..e74df498645 100644 --- a/components/script/dom/htmlheadingelement.rs +++ b/components/script/dom/htmlheadingelement.rs @@ -27,24 +27,31 @@ pub struct HTMLHeadingElement { } impl HTMLHeadingElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document, - level: HeadingLevel) -> HTMLHeadingElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + level: HeadingLevel, + ) -> HTMLHeadingElement { HTMLHeadingElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document), + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), level: level, } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document, - level: HeadingLevel) -> DomRoot<HTMLHeadingElement> { - Node::reflect_node(Box::new(HTMLHeadingElement::new_inherited(local_name, prefix, document, level)), - document, - HTMLHeadingElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + level: HeadingLevel, + ) -> DomRoot<HTMLHeadingElement> { + Node::reflect_node( + Box::new(HTMLHeadingElement::new_inherited( + local_name, prefix, document, level, + )), + document, + HTMLHeadingElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlhrelement.rs b/components/script/dom/htmlhrelement.rs index 740bbd9aac2..7396c9013e7 100644 --- a/components/script/dom/htmlhrelement.rs +++ b/components/script/dom/htmlhrelement.rs @@ -22,19 +22,27 @@ pub struct HTMLHRElement { } impl HTMLHRElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLHRElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLHRElement { HTMLHRElement { - htmlelement: HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLHRElement> { - Node::reflect_node(Box::new(HTMLHRElement::new_inherited(local_name, prefix, document)), - document, - HTMLHRElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLHRElement> { + Node::reflect_node( + Box::new(HTMLHRElement::new_inherited(local_name, prefix, document)), + document, + HTMLHRElementBinding::Wrap, + ) } } @@ -86,7 +94,6 @@ impl HTMLHRLayoutHelpers for LayoutDom<HTMLHRElement> { } } - impl VirtualMethods for HTMLHRElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) @@ -97,7 +104,10 @@ impl VirtualMethods for HTMLHRElement { &local_name!("align") => AttrValue::from_dimension(value.into()), &local_name!("color") => AttrValue::from_legacy_color(value.into()), &local_name!("width") => AttrValue::from_dimension(value.into()), - _ => self.super_type().unwrap().parse_plain_attribute(name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(name, value), } } } diff --git a/components/script/dom/htmlhtmlelement.rs b/components/script/dom/htmlhtmlelement.rs index c5eb4e1fca5..f9fd18fd693 100644 --- a/components/script/dom/htmlhtmlelement.rs +++ b/components/script/dom/htmlhtmlelement.rs @@ -12,22 +12,30 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLHtmlElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLHtmlElement { - fn new_inherited(localName: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLHtmlElement { + fn new_inherited( + localName: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLHtmlElement { HTMLHtmlElement { - htmlelement: HTMLElement::new_inherited(localName, prefix, document) + htmlelement: HTMLElement::new_inherited(localName, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(localName: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLHtmlElement> { - Node::reflect_node(Box::new(HTMLHtmlElement::new_inherited(localName, prefix, document)), - document, - HTMLHtmlElementBinding::Wrap) + pub fn new( + localName: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLHtmlElement> { + Node::reflect_node( + Box::new(HTMLHtmlElement::new_inherited(localName, prefix, document)), + document, + HTMLHtmlElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmliframeelement.rs b/components/script/dom/htmliframeelement.rs index 658961a1725..3c37c97af4c 100644 --- a/components/script/dom/htmliframeelement.rs +++ b/components/script/dom/htmliframeelement.rs @@ -88,20 +88,24 @@ impl HTMLIFrameElement { /// step 1. fn get_url(&self) -> ServoUrl { let element = self.upcast::<Element>(); - element.get_attribute(&ns!(), &local_name!("src")).and_then(|src| { - let url = src.value(); - if url.is_empty() { - None - } else { - document_from_node(self).base_url().join(&url).ok() - } - }).unwrap_or_else(|| ServoUrl::parse("about:blank").unwrap()) + element + .get_attribute(&ns!(), &local_name!("src")) + .and_then(|src| { + let url = src.value(); + if url.is_empty() { + None + } else { + document_from_node(self).base_url().join(&url).ok() + } + }).unwrap_or_else(|| ServoUrl::parse("about:blank").unwrap()) } - pub fn navigate_or_reload_child_browsing_context(&self, - mut load_data: Option<LoadData>, - nav_type: NavigationType, - replace: bool) { + pub fn navigate_or_reload_child_browsing_context( + &self, + mut load_data: Option<LoadData>, + nav_type: NavigationType, + replace: bool, + ) { let sandboxed = if self.is_sandboxed() { IFrameSandboxed } else { @@ -142,8 +146,11 @@ impl HTMLIFrameElement { match load_data.js_eval_result { Some(JsEvalResult::NoContent) => (), _ => { - *load_blocker = Some(LoadBlocker::new(&*document, LoadType::Subframe(load_data.url.clone()))); - } + *load_blocker = Some(LoadBlocker::new( + &*document, + LoadType::Subframe(load_data.url.clone()), + )); + }, }; } @@ -197,10 +204,10 @@ impl HTMLIFrameElement { sandbox: sandboxed, }; global_scope - .script_to_constellation_chan() - .send(ScriptMsg::ScriptLoadedURLInIFrame(load_info)) - .unwrap(); - } + .script_to_constellation_chan() + .send(ScriptMsg::ScriptLoadedURLInIFrame(load_info)) + .unwrap(); + }, } } @@ -211,7 +218,9 @@ impl HTMLIFrameElement { let window = window_from_node(self); // https://github.com/whatwg/html/issues/490 - if mode == ProcessingMode::FirstTime && !self.upcast::<Element>().has_attribute(&local_name!("src")) { + if mode == ProcessingMode::FirstTime && + !self.upcast::<Element>().has_attribute(&local_name!("src")) + { let this = Trusted::new(self); let pipeline_id = self.pipeline_id().unwrap(); // FIXME(nox): Why are errors silenced here? @@ -245,12 +254,21 @@ impl HTMLIFrameElement { }; let document = document_from_node(self); - let load_data = LoadData::new(url, creator_pipeline_id, document.get_referrer_policy(), Some(document.url())); + let load_data = LoadData::new( + url, + creator_pipeline_id, + document.get_referrer_policy(), + Some(document.url()), + ); let pipeline_id = self.pipeline_id(); // If the initial `about:blank` page is the current page, load with replacement enabled. let replace = pipeline_id.is_some() && pipeline_id == self.about_blank_pipeline_id.get(); - self.navigate_or_reload_child_browsing_context(Some(load_data), NavigationType::Regular, replace); + self.navigate_or_reload_child_browsing_context( + Some(load_data), + NavigationType::Regular, + replace, + ); } fn create_nested_browsing_context(&self) { @@ -259,14 +277,24 @@ impl HTMLIFrameElement { let document = document_from_node(self); let window = window_from_node(self); let pipeline_id = Some(window.upcast::<GlobalScope>().pipeline_id()); - let load_data = LoadData::new(url, pipeline_id, document.get_referrer_policy(), Some(document.url().clone())); + let load_data = LoadData::new( + url, + pipeline_id, + document.get_referrer_policy(), + Some(document.url().clone()), + ); let browsing_context_id = BrowsingContextId::new(); let top_level_browsing_context_id = window.window_proxy().top_level_browsing_context_id(); self.pipeline_id.set(None); self.pending_pipeline_id.set(None); - self.top_level_browsing_context_id.set(Some(top_level_browsing_context_id)); + self.top_level_browsing_context_id + .set(Some(top_level_browsing_context_id)); self.browsing_context_id.set(Some(browsing_context_id)); - self.navigate_or_reload_child_browsing_context(Some(load_data), NavigationType::InitialAboutBlank, false); + self.navigate_or_reload_child_browsing_context( + Some(load_data), + NavigationType::InitialAboutBlank, + false, + ); } fn destroy_nested_browsing_context(&self) { @@ -278,7 +306,9 @@ impl HTMLIFrameElement { } pub fn update_pipeline_id(&self, new_pipeline_id: PipelineId, reason: UpdatePipelineIdReason) { - if self.pending_pipeline_id.get() != Some(new_pipeline_id) && reason == UpdatePipelineIdReason::Navigation { + if self.pending_pipeline_id.get() != Some(new_pipeline_id) && + reason == UpdatePipelineIdReason::Navigation + { return; } @@ -296,9 +326,11 @@ impl HTMLIFrameElement { window.reflow(ReflowGoal::Full, ReflowReason::FramedContentChanged); } - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLIFrameElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLIFrameElement { HTMLIFrameElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), browsing_context_id: Cell::new(None), @@ -310,17 +342,23 @@ impl HTMLIFrameElement { sandbox_allowance: Cell::new(None), load_blocker: DomRefCell::new(None), visibility: Cell::new(true), - name: DomRefCell::new(DOMString::new()) + name: DomRefCell::new(DOMString::new()), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLIFrameElement> { - Node::reflect_node(Box::new(HTMLIFrameElement::new_inherited(local_name, prefix, document)), - document, - HTMLIFrameElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLIFrameElement> { + Node::reflect_node( + Box::new(HTMLIFrameElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLIFrameElementBinding::Wrap, + ) } #[inline] @@ -347,14 +385,20 @@ impl HTMLIFrameElement { pub fn set_visible(&self, visible: bool) { let msg = ScriptMsg::SetVisible(visible); let window = window_from_node(self); - window.upcast::<GlobalScope>().script_to_constellation_chan().send(msg).unwrap(); + window + .upcast::<GlobalScope>() + .script_to_constellation_chan() + .send(msg) + .unwrap(); } /// https://html.spec.whatwg.org/multipage/#iframe-load-event-steps steps 1-4 pub fn iframe_load_event_steps(&self, loaded_pipeline: PipelineId) { // TODO(#9592): assert that the load blocker is present at all times when we // can guarantee that it's created for the case of iframe.reload(). - if Some(loaded_pipeline) != self.pending_pipeline_id.get() { return; } + if Some(loaded_pipeline) != self.pending_pipeline_id.get() { + return; + } // TODO A cross-origin child document would not be easily accessible // from this script thread. It's unclear how to implement @@ -386,20 +430,15 @@ impl HTMLIFrameElementLayoutMethods for LayoutDom<HTMLIFrameElement> { #[inline] #[allow(unsafe_code)] fn pipeline_id(&self) -> Option<PipelineId> { - unsafe { - (*self.unsafe_get()).pipeline_id.get() - } + unsafe { (*self.unsafe_get()).pipeline_id.get() } } #[inline] #[allow(unsafe_code)] fn browsing_context_id(&self) -> Option<BrowsingContextId> { - unsafe { - (*self.unsafe_get()).browsing_context_id.get() - } + unsafe { (*self.unsafe_get()).browsing_context_id.get() } } - #[allow(unsafe_code)] fn get_width(&self) -> LengthOrPercentageOrAuto { unsafe { @@ -432,12 +471,14 @@ impl HTMLIFrameElementMethods for HTMLIFrameElement { // https://html.spec.whatwg.org/multipage/#dom-iframe-sandbox fn Sandbox(&self) -> DomRoot<DOMTokenList> { - self.sandbox.or_init(|| DOMTokenList::new(self.upcast::<Element>(), &local_name!("sandbox"))) + self.sandbox + .or_init(|| DOMTokenList::new(self.upcast::<Element>(), &local_name!("sandbox"))) } // https://html.spec.whatwg.org/multipage/#dom-iframe-contentwindow fn GetContentWindow(&self) -> Option<DomRoot<WindowProxy>> { - self.browsing_context_id.get() + self.browsing_context_id + .get() .and_then(|browsing_context_id| ScriptThread::find_window_proxy(browsing_context_id)) } @@ -453,7 +494,10 @@ impl HTMLIFrameElementMethods for HTMLIFrameElement { let document = ScriptThread::find_document(pipeline_id)?; // Step 4. - let current = GlobalScope::current().expect("No current global object").as_window().Document(); + let current = GlobalScope::current() + .expect("No current global object") + .as_window() + .Document(); if !current.origin().same_origin_domain(document.origin()) { return None; } @@ -508,21 +552,22 @@ impl VirtualMethods for HTMLIFrameElement { self.super_type().unwrap().attribute_mutated(attr, mutation); match attr.local_name() { &local_name!("sandbox") => { - self.sandbox_allowance.set(mutation.new_value(attr).map(|value| { - let mut modes = SandboxAllowance::ALLOW_NOTHING; - for token in value.as_tokens() { - modes |= match &*token.to_ascii_lowercase() { - "allow-same-origin" => SandboxAllowance::ALLOW_SAME_ORIGIN, - "allow-forms" => SandboxAllowance::ALLOW_FORMS, - "allow-pointer-lock" => SandboxAllowance::ALLOW_POINTER_LOCK, - "allow-popups" => SandboxAllowance::ALLOW_POPUPS, - "allow-scripts" => SandboxAllowance::ALLOW_SCRIPTS, - "allow-top-navigation" => SandboxAllowance::ALLOW_TOP_NAVIGATION, - _ => SandboxAllowance::ALLOW_NOTHING - }; - } - modes - })); + self.sandbox_allowance + .set(mutation.new_value(attr).map(|value| { + let mut modes = SandboxAllowance::ALLOW_NOTHING; + for token in value.as_tokens() { + modes |= match &*token.to_ascii_lowercase() { + "allow-same-origin" => SandboxAllowance::ALLOW_SAME_ORIGIN, + "allow-forms" => SandboxAllowance::ALLOW_FORMS, + "allow-pointer-lock" => SandboxAllowance::ALLOW_POINTER_LOCK, + "allow-popups" => SandboxAllowance::ALLOW_POPUPS, + "allow-scripts" => SandboxAllowance::ALLOW_SCRIPTS, + "allow-top-navigation" => SandboxAllowance::ALLOW_TOP_NAVIGATION, + _ => SandboxAllowance::ALLOW_NOTHING, + }; + } + modes + })); }, &local_name!("src") => { // https://html.spec.whatwg.org/multipage/#the-iframe-element @@ -552,7 +597,10 @@ impl VirtualMethods for HTMLIFrameElement { &local_name!("sandbox") => AttrValue::from_serialized_tokenlist(value.into()), &local_name!("width") => AttrValue::from_dimension(value.into()), &local_name!("height") => AttrValue::from_dimension(value.into()), - _ => self.super_type().unwrap().parse_plain_attribute(name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(name, value), } } @@ -583,7 +631,8 @@ impl VirtualMethods for HTMLIFrameElement { // https://html.spec.whatwg.org/multipage/#a-browsing-context-is-discarded let window = window_from_node(self); - let (sender, receiver) = ProfiledIpc::channel(self.global().time_profiler_chan().clone()).unwrap(); + let (sender, receiver) = + ProfiledIpc::channel(self.global().time_profiler_chan().clone()).unwrap(); // Ask the constellation to remove the iframe, and tell us the // pipeline ids of the closed pipelines. @@ -594,7 +643,11 @@ impl VirtualMethods for HTMLIFrameElement { debug!("Unbinding frame {}.", browsing_context_id); let msg = ScriptMsg::RemoveIFrame(browsing_context_id, sender); - window.upcast::<GlobalScope>().script_to_constellation_chan().send(msg).unwrap(); + window + .upcast::<GlobalScope>() + .script_to_constellation_chan() + .send(msg) + .unwrap(); let exited_pipeline_ids = receiver.recv().unwrap(); // The spec for discarding is synchronous, @@ -602,8 +655,14 @@ impl VirtualMethods for HTMLIFrameElement { // when the `PipelineExit` message arrives. for exited_pipeline_id in exited_pipeline_ids { if let Some(exited_document) = ScriptThread::find_document(exited_pipeline_id) { - debug!("Discarding browsing context for pipeline {}", exited_pipeline_id); - exited_document.window().window_proxy().discard_browsing_context(); + debug!( + "Discarding browsing context for pipeline {}", + exited_pipeline_id + ); + exited_document + .window() + .window_proxy() + .discard_browsing_context(); for exited_iframe in exited_document.iter_iframes() { debug!("Discarding nested browsing context"); exited_iframe.destroy_nested_browsing_context(); diff --git a/components/script/dom/htmlimageelement.rs b/components/script/dom/htmlimageelement.rs index b665014cdca..8107d8bcb5d 100644 --- a/components/script/dom/htmlimageelement.rs +++ b/components/script/dom/htmlimageelement.rs @@ -74,7 +74,6 @@ use style::values::specified::length::{Length, NoCalcLength}; use style_traits::ParsingMode; use task_source::{TaskSource, TaskSourceName}; - enum ParseState { InDescriptor, InParens, @@ -119,7 +118,7 @@ enum State { #[derive(Clone, Copy, JSTraceable, MallocSizeOf)] enum ImageRequestPhase { Pending, - Current + Current, } #[derive(JSTraceable, MallocSizeOf)] #[must_root] @@ -170,15 +169,12 @@ impl FetchResponseListener for ImageContext { fn process_request_eof(&mut self) {} fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) { - self.image_cache.notify_pending_response( - self.id, - FetchResponseMsg::ProcessResponse(metadata.clone())); - - let metadata = metadata.ok().map(|meta| { - match meta { - FetchMetadata::Unfiltered(m) => m, - FetchMetadata::Filtered { unsafe_, .. } => unsafe_ - } + self.image_cache + .notify_pending_response(self.id, FetchResponseMsg::ProcessResponse(metadata.clone())); + + let metadata = metadata.ok().map(|meta| match meta { + FetchMetadata::Unfiltered(m) => m, + FetchMetadata::Filtered { unsafe_, .. } => unsafe_, }); // Step 14.5 of https://html.spec.whatwg.org/multipage/#img-environment-changes @@ -190,34 +186,38 @@ impl FetchResponseListener for ImageContext { self.aborted.set(true); } }, - _ => () + _ => (), } } } - let status_code = metadata.as_ref().and_then(|m| { - m.status.as_ref().map(|&(code, _)| code) - }).unwrap_or(0); + let status_code = metadata + .as_ref() + .and_then(|m| m.status.as_ref().map(|&(code, _)| code)) + .unwrap_or(0); self.status = match status_code { - 0 => Err(NetworkError::Internal("No http status code received".to_owned())), + 0 => Err(NetworkError::Internal( + "No http status code received".to_owned(), + )), 200...299 => Ok(()), // HTTP ok status codes - _ => Err(NetworkError::Internal(format!("HTTP error code {}", status_code))) + _ => Err(NetworkError::Internal(format!( + "HTTP error code {}", + status_code + ))), }; } fn process_response_chunk(&mut self, payload: Vec<u8>) { if self.status.is_ok() { - self.image_cache.notify_pending_response( - self.id, - FetchResponseMsg::ProcessResponseChunk(payload)); + self.image_cache + .notify_pending_response(self.id, FetchResponseMsg::ProcessResponseChunk(payload)); } } fn process_response_eof(&mut self, response: Result<(), NetworkError>) { - self.image_cache.notify_pending_response( - self.id, - FetchResponseMsg::ProcessResponseEOF(response)); + self.image_cache + .notify_pending_response(self.id, FetchResponseMsg::ProcessResponseEOF(response)); } } @@ -230,9 +230,11 @@ impl PreInvoke for ImageContext { impl HTMLImageElement { /// Update the current image with a valid URL. fn fetch_image(&self, img_url: &ServoUrl) { - fn add_cache_listener_for_element(image_cache: Arc<ImageCache>, - id: PendingImageId, - elem: &HTMLImageElement) { + fn add_cache_listener_for_element( + image_cache: Arc<ImageCache>, + id: PendingImageId, + elem: &HTMLImageElement, + ) { let trusted_node = Trusted::new(elem); let (responder_sender, responder_receiver) = ipc::channel().unwrap(); @@ -240,55 +242,59 @@ impl HTMLImageElement { let task_source = window.networking_task_source(); let task_canceller = window.task_canceller(TaskSourceName::Networking); let generation = elem.generation.get(); - ROUTER.add_route(responder_receiver.to_opaque(), Box::new(move |message| { - debug!("Got image {:?}", message); - // Return the image via a message to the script thread, which marks - // the element as dirty and triggers a reflow. - let element = trusted_node.clone(); - let image = message.to().unwrap(); - // FIXME(nox): Why are errors silenced here? - let _ = task_source.queue_with_canceller( - task!(process_image_response: move || { + ROUTER.add_route( + responder_receiver.to_opaque(), + Box::new(move |message| { + debug!("Got image {:?}", message); + // Return the image via a message to the script thread, which marks + // the element as dirty and triggers a reflow. + let element = trusted_node.clone(); + let image = message.to().unwrap(); + // FIXME(nox): Why are errors silenced here? + let _ = task_source.queue_with_canceller( + task!(process_image_response: move || { let element = element.root(); // Ignore any image response for a previous request that has been discarded. if generation == element.generation.get() { element.process_image_response(image); } }), - &task_canceller, - ); - })); + &task_canceller, + ); + }), + ); image_cache.add_listener(id, ImageResponder::new(responder_sender, id)); } let window = window_from_node(self); let image_cache = window.image_cache(); - let response = - image_cache.find_image_or_metadata(img_url.clone().into(), - UsePlaceholder::Yes, - CanRequestImages::Yes); + let response = image_cache.find_image_or_metadata( + img_url.clone().into(), + UsePlaceholder::Yes, + CanRequestImages::Yes, + ); match response { Ok(ImageOrMetadataAvailable::ImageAvailable(image, url)) => { self.process_image_response(ImageResponse::Loaded(image, url)); - } + }, Ok(ImageOrMetadataAvailable::MetadataAvailable(m)) => { self.process_image_response(ImageResponse::MetadataLoaded(m)); - } + }, Err(ImageState::Pending(id)) => { add_cache_listener_for_element(image_cache.clone(), id, self); - } + }, Err(ImageState::LoadError) => { self.process_image_response(ImageResponse::None); - } + }, Err(ImageState::NotRequested(id)) => { add_cache_listener_for_element(image_cache, id, self); self.fetch_request(img_url, id); - } + }, } } @@ -309,27 +315,32 @@ impl HTMLImageElement { task_source: window.networking_task_source(), canceller: Some(window.task_canceller(TaskSourceName::Networking)), }; - ROUTER.add_route(action_receiver.to_opaque(), Box::new(move |message| { - listener.notify_fetch(message.to().unwrap()); - })); + ROUTER.add_route( + action_receiver.to_opaque(), + Box::new(move |message| { + listener.notify_fetch(message.to().unwrap()); + }), + ); let request = RequestInit { url: img_url.clone(), origin: document.origin().immutable().clone(), pipeline_id: Some(document.global().pipeline_id()), - .. RequestInit::default() + ..RequestInit::default() }; // This is a background load because the load blocker already fulfills the // purpose of delaying the document's load event. - document.loader_mut().fetch_async_background(request, action_sender); + document + .loader_mut() + .fetch_async_background(request, action_sender); } // Steps common to when an image has been loaded. fn handle_loaded_image(&self, image: Arc<Image>, url: ServoUrl) { self.current_request.borrow_mut().metadata = Some(ImageMetadata { height: image.height, - width: image.width + width: image.width, }); self.current_request.borrow_mut().final_url = Some(url); self.current_request.borrow_mut().image = Some(image); @@ -402,16 +413,18 @@ impl HTMLImageElement { window.add_pending_reflow(); } - fn process_image_response_for_environment_change(&self, - image: ImageResponse, - src: DOMString, - generation: u32, - selected_pixel_density: f64) { + fn process_image_response_for_environment_change( + &self, + image: ImageResponse, + src: DOMString, + generation: u32, + selected_pixel_density: f64, + ) { match image { ImageResponse::Loaded(image, url) | ImageResponse::PlaceholderLoaded(image, url) => { self.pending_request.borrow_mut().metadata = Some(ImageMetadata { height: image.height, - width: image.width + width: image.width, }); self.pending_request.borrow_mut().final_url = Some(url); self.pending_request.borrow_mut().image = Some(image); @@ -451,29 +464,27 @@ impl HTMLImageElement { Some(p) => { if p.is::<HTMLPictureElement>() { nodes = p.upcast::<Node>().children(); - nodes.filter_map(DomRoot::downcast::<Element>) - .map(|n| DomRoot::from_ref(&*n)).collect() + nodes + .filter_map(DomRoot::downcast::<Element>) + .map(|n| DomRoot::from_ref(&*n)) + .collect() } else { vec![DomRoot::from_ref(&*elem)] } - } - None => { - vec![DomRoot::from_ref(&*elem)] - } + }, + None => vec![DomRoot::from_ref(&*elem)], }; // Step 3 let width = match elem.get_attribute(&ns!(), &local_name!("width")) { - Some(x) => { - match parse_length(&x.value()) { - LengthOrPercentageOrAuto::Length(x) =>{ - let abs_length = AbsoluteLength::Px(x.to_f32_px()); - Some(Length::NoCalc(NoCalcLength::Absolute(abs_length))) - }, - _ => None - } + Some(x) => match parse_length(&x.value()) { + LengthOrPercentageOrAuto::Length(x) => { + let abs_length = AbsoluteLength::Px(x.to_f32_px()); + Some(Length::NoCalc(NoCalcLength::Absolute(abs_length))) + }, + _ => None, }, - None => None + None => None, }; // Step 4 @@ -495,14 +506,21 @@ impl HTMLImageElement { // Step 4.1.3 let src_attribute = element.get_string_attribute(&local_name!("src")); let is_src_empty = src_attribute.is_empty(); - let no_density_source_of_1 = source_set.image_sources.iter() - .all(|source| source.descriptor.den != Some(1.)); - let no_width_descriptor = source_set.image_sources.iter() - .all(|source| source.descriptor.wid.is_none()); + let no_density_source_of_1 = source_set + .image_sources + .iter() + .all(|source| source.descriptor.den != Some(1.)); + let no_width_descriptor = source_set + .image_sources + .iter() + .all(|source| source.descriptor.wid.is_none()); if !is_src_empty && no_density_source_of_1 && no_width_descriptor { source_set.image_sources.push(ImageSource { url: src_attribute.to_string(), - descriptor: Descriptor { wid: None, den: None } + descriptor: Descriptor { + wid: None, + den: None, + }, }) } @@ -525,8 +543,8 @@ impl HTMLImageElement { match element.get_attribute(&ns!(), &local_name!("srcset")) { Some(x) => { source_set.image_sources = parse_a_srcset_attribute(&x.value()); - } - _ => continue + }, + _ => continue, } // Step 4.5 @@ -552,12 +570,11 @@ impl HTMLImageElement { // TODO Handle unsupported mime type let mime = x.value().parse::<Mime>(); match mime { - Ok(m) => - match m { - Mime(TopLevel::Image, _, _) => (), - _ => continue - }, - _ => continue + Ok(m) => match m { + Mime(TopLevel::Image, _, _) => (), + _ => continue, + }, + _ => continue, } } @@ -570,7 +587,11 @@ impl HTMLImageElement { } } - fn evaluate_source_size_list(&self, source_size_list: &mut SourceSizeList, _width: Option<Length>) -> Au { + fn evaluate_source_size_list( + &self, + source_size_list: &mut SourceSizeList, + _width: Option<Length>, + ) -> Au { let document = document_from_node(self); let device = document.device(); if !device.is_some() { @@ -632,7 +653,7 @@ impl HTMLImageElement { //Step 2.3 imgsource.descriptor.den = Some(1 as f64); } - }; + } } /// <https://html.spec.whatwg.org/multipage/#select-an-image-source> @@ -689,13 +710,18 @@ impl HTMLImageElement { } } let selected_source = img_sources.remove(best_candidate.1).clone(); - Some((DOMString::from_string(selected_source.url), selected_source.descriptor.den.unwrap() as f64)) + Some(( + DOMString::from_string(selected_source.url), + selected_source.descriptor.den.unwrap() as f64, + )) } - fn init_image_request(&self, - request: &mut RefMut<ImageRequest>, - url: &ServoUrl, - src: &DOMString) { + fn init_image_request( + &self, + request: &mut RefMut<ImageRequest>, + url: &ServoUrl, + src: &DOMString, + ) { request.parsed_url = Some(url.clone()); request.source_url = Some(src.clone()); request.image = None; @@ -712,7 +738,7 @@ impl HTMLImageElement { if let Some(pending_url) = self.pending_request.borrow().parsed_url.clone() { // Step 13 if pending_url == *url { - return + return; } } }, @@ -729,7 +755,7 @@ impl HTMLImageElement { pending_request.parsed_url = None; LoadBlocker::terminate(&mut pending_request.blocker); // TODO: queue a task to restart animation, if restart-animation is set - return + return; } pending_request.current_pixel_density = Some(selected_pixel_density); self.image_request.set(ImageRequestPhase::Pending); @@ -747,7 +773,7 @@ impl HTMLImageElement { self.init_image_request(&mut pending_request, &url, &src); }, } - } + }, } self.fetch_image(&url); } @@ -841,7 +867,7 @@ impl HTMLImageElement { }), window.upcast(), ); - } + }, } } @@ -873,7 +899,9 @@ impl HTMLImageElement { let mut selected_source = None; let mut pixel_density = None; let src_set = elem.get_string_attribute(&local_name!("srcset")); - let is_parent_picture = elem.upcast::<Node>().GetParentElement() + let is_parent_picture = elem + .upcast::<Node>() + .GetParentElement() .map_or(false, |p| p.is::<HTMLPictureElement>()); if src_set.is_empty() && !is_parent_picture && !src.is_empty() { selected_source = Some(src.clone()); @@ -884,15 +912,23 @@ impl HTMLImageElement { *self.last_selected_source.borrow_mut() = selected_source.clone(); // Step 6, check the list of available images - if !selected_source.as_ref().map_or(false, |source| source.is_empty()) { + if !selected_source + .as_ref() + .map_or(false, |source| source.is_empty()) + { if let Ok(img_url) = base_url.join(&src) { let image_cache = window.image_cache(); - let response = image_cache.find_image_or_metadata(img_url.clone().into(), - UsePlaceholder::No, - CanRequestImages::No); + let response = image_cache.find_image_or_metadata( + img_url.clone().into(), + UsePlaceholder::No, + CanRequestImages::No, + ); if let Ok(ImageOrMetadataAvailable::ImageAvailable(image, url)) = response { // Step 6.3 - let metadata = ImageMetadata { height: image.height, width: image.width }; + let metadata = ImageMetadata { + height: image.height, + width: image.width, + }; // Step 6.3.2 abort requests self.abort_request(State::CompletelyAvailable, ImageRequestPhase::Current); self.abort_request(State::CompletelyAvailable, ImageRequestPhase::Pending); @@ -944,11 +980,13 @@ impl HTMLImageElement { /// Step 2-12 of https://html.spec.whatwg.org/multipage/#img-environment-changes fn react_to_environment_changes_sync_steps(&self, generation: u32) { // TODO reduce duplicacy of this code - fn add_cache_listener_for_element(image_cache: Arc<ImageCache>, - id: PendingImageId, - elem: &HTMLImageElement, - selected_source: String, - selected_pixel_density: f64) { + fn add_cache_listener_for_element( + image_cache: Arc<ImageCache>, + id: PendingImageId, + elem: &HTMLImageElement, + selected_source: String, + selected_pixel_density: f64, + ) { let trusted_node = Trusted::new(elem); let (responder_sender, responder_receiver) = ipc::channel().unwrap(); @@ -981,9 +1019,9 @@ impl HTMLImageElement { let elem = self.upcast::<Element>(); let document = document_from_node(elem); - let has_pending_request = match self.image_request.get() { + let has_pending_request = match self.image_request.get() { ImageRequestPhase::Pending => true, - _ => false + _ => false, }; // Step 2 @@ -1003,7 +1041,8 @@ impl HTMLImageElement { _ => false, }; - let same_selected_pixel_density = match self.current_request.borrow().current_pixel_density { + let same_selected_pixel_density = match self.current_request.borrow().current_pixel_density + { Some(den) => selected_pixel_density == den, _ => false, }; @@ -1021,46 +1060,78 @@ impl HTMLImageElement { // Step 12 self.image_request.set(ImageRequestPhase::Pending); - self.init_image_request(&mut self.pending_request.borrow_mut(), &img_url, &selected_source); + self.init_image_request( + &mut self.pending_request.borrow_mut(), + &img_url, + &selected_source, + ); let window = window_from_node(self); let image_cache = window.image_cache(); // Step 14 - let response = - image_cache.find_image_or_metadata(img_url.clone().into(), - UsePlaceholder::No, - CanRequestImages::Yes); + let response = image_cache.find_image_or_metadata( + img_url.clone().into(), + UsePlaceholder::No, + CanRequestImages::Yes, + ); match response { Ok(ImageOrMetadataAvailable::ImageAvailable(_image, _url)) => { // Step 15 - self.finish_reacting_to_environment_change(selected_source, generation, selected_pixel_density); - } + self.finish_reacting_to_environment_change( + selected_source, + generation, + selected_pixel_density, + ); + }, Ok(ImageOrMetadataAvailable::MetadataAvailable(m)) => { - self.process_image_response_for_environment_change(ImageResponse::MetadataLoaded(m), - selected_source, generation, selected_pixel_density); - } + self.process_image_response_for_environment_change( + ImageResponse::MetadataLoaded(m), + selected_source, + generation, + selected_pixel_density, + ); + }, Err(ImageState::Pending(id)) => { - add_cache_listener_for_element(image_cache.clone(), id, self, - selected_source.to_string(), selected_pixel_density); - } + add_cache_listener_for_element( + image_cache.clone(), + id, + self, + selected_source.to_string(), + selected_pixel_density, + ); + }, Err(ImageState::LoadError) => { - self.process_image_response_for_environment_change(ImageResponse::None, - selected_source, generation, selected_pixel_density); - } + self.process_image_response_for_environment_change( + ImageResponse::None, + selected_source, + generation, + selected_pixel_density, + ); + }, Err(ImageState::NotRequested(id)) => { - add_cache_listener_for_element(image_cache, id, self, selected_source.to_string(), - selected_pixel_density); + add_cache_listener_for_element( + image_cache, + id, + self, + selected_source.to_string(), + selected_pixel_density, + ); self.fetch_request(&img_url, id); - } + }, } } /// Step 15 for <https://html.spec.whatwg.org/multipage/#img-environment-changes> - fn finish_reacting_to_environment_change(&self, src: DOMString, generation: u32, selected_pixel_density: f64) { + fn finish_reacting_to_environment_change( + &self, + src: DOMString, + generation: u32, + selected_pixel_density: f64, + ) { let this = Trusted::new(self); let window = window_from_node(self); let src = src.to_string(); @@ -1103,12 +1174,18 @@ impl HTMLImageElement { fn uses_srcset_or_picture(elem: &Element) -> bool { let has_src = elem.has_attribute(&local_name!("srcset")); - let is_parent_picture = elem.upcast::<Node>().GetParentElement() + let is_parent_picture = elem + .upcast::<Node>() + .GetParentElement() .map_or(false, |p| p.is::<HTMLPictureElement>()); has_src || is_parent_picture } - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLImageElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLImageElement { HTMLImageElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), image_request: Cell::new(ImageRequestPhase::Current), @@ -1140,17 +1217,25 @@ impl HTMLImageElement { } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLImageElement> { - Node::reflect_node(Box::new(HTMLImageElement::new_inherited(local_name, prefix, document)), - document, - HTMLImageElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLImageElement> { + Node::reflect_node( + Box::new(HTMLImageElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLImageElementBinding::Wrap, + ) } - pub fn Image(window: &Window, - width: Option<u32>, - height: Option<u32>) -> Fallible<DomRoot<HTMLImageElement>> { + pub fn Image( + window: &Window, + width: Option<u32>, + height: Option<u32>, + ) -> Fallible<DomRoot<HTMLImageElement>> { let document = window.Document(); let image = HTMLImageElement::new(local_name!("img"), None, &document); if let Some(w) = width { @@ -1169,19 +1254,24 @@ impl HTMLImageElement { let value = usemap_attr.value(); if value.len() == 0 || !value.is_char_boundary(1) { - return None + return None; } let (first, last) = value.split_at(1); if first != "#" || last.len() == 0 { - return None + return None; } - let useMapElements = document_from_node(self).upcast::<Node>() - .traverse_preorder() - .filter_map(DomRoot::downcast::<HTMLMapElement>) - .find(|n| n.upcast::<Element>().get_string_attribute(&LocalName::from("name")) == last); + let useMapElements = document_from_node(self) + .upcast::<Node>() + .traverse_preorder() + .filter_map(DomRoot::downcast::<HTMLMapElement>) + .find(|n| { + n.upcast::<Element>() + .get_string_attribute(&LocalName::from("name")) == + last + }); useMapElements.map(|mapElem| mapElem.get_area_elements()) } @@ -1191,7 +1281,6 @@ impl HTMLImageElement { url.scheme() == "data" || url.origin().same_origin(origin) }) } - } #[derive(JSTraceable, MallocSizeOf)] @@ -1203,20 +1292,26 @@ pub enum ImageElementMicrotask { EnvironmentChangesTask { elem: DomRoot<HTMLImageElement>, generation: u32, - } + }, } impl MicrotaskRunnable for ImageElementMicrotask { fn handler(&self) { match self { - &ImageElementMicrotask::StableStateUpdateImageDataTask { ref elem, ref generation } => { + &ImageElementMicrotask::StableStateUpdateImageDataTask { + ref elem, + ref generation, + } => { // Step 7 of https://html.spec.whatwg.org/multipage/#update-the-image-data, // stop here if other instances of this algorithm have been scheduled if elem.generation.get() == *generation { elem.update_the_image_data_sync_steps(); } }, - &ImageElementMicrotask::EnvironmentChangesTask { ref elem, ref generation } => { + &ImageElementMicrotask::EnvironmentChangesTask { + ref elem, + ref generation, + } => { elem.react_to_environment_changes_sync_steps(*generation); }, } @@ -1240,17 +1335,29 @@ pub trait LayoutHTMLImageElementHelpers { impl LayoutHTMLImageElementHelpers for LayoutDom<HTMLImageElement> { #[allow(unsafe_code)] unsafe fn image(&self) -> Option<Arc<Image>> { - (*self.unsafe_get()).current_request.borrow_for_layout().image.clone() + (*self.unsafe_get()) + .current_request + .borrow_for_layout() + .image + .clone() } #[allow(unsafe_code)] unsafe fn image_url(&self) -> Option<ServoUrl> { - (*self.unsafe_get()).current_request.borrow_for_layout().parsed_url.clone() + (*self.unsafe_get()) + .current_request + .borrow_for_layout() + .parsed_url + .clone() } #[allow(unsafe_code)] unsafe fn image_density(&self) -> Option<f64> { - (*self.unsafe_get()).current_request.borrow_for_layout().current_pixel_density.clone() + (*self.unsafe_get()) + .current_request + .borrow_for_layout() + .current_pixel_density + .clone() } #[allow(unsafe_code)] @@ -1382,11 +1489,11 @@ impl HTMLImageElementMethods for HTMLImageElement { let elem = self.upcast::<Element>(); // TODO: take srcset into account if !elem.has_attribute(&local_name!("src")) { - return true + return true; } let src = elem.get_string_attribute(&local_name!("src")); if src.is_empty() { - return true + return true; } let request = self.current_request.borrow(); let request_state = request.state; @@ -1406,7 +1513,7 @@ impl HTMLImageElementMethods for HTMLImageElement { let ref unparsed_url = current_request.source_url; match *unparsed_url { Some(ref url) => url.clone(), - None => DOMString::from("") + None => DOMString::from(""), } }, } @@ -1476,46 +1583,53 @@ impl VirtualMethods for HTMLImageElement { fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("name") => AttrValue::from_atomic(value.into()), - &local_name!("width") | &local_name!("height") => AttrValue::from_dimension(value.into()), + &local_name!("width") | &local_name!("height") => { + AttrValue::from_dimension(value.into()) + }, &local_name!("hspace") | &local_name!("vspace") => AttrValue::from_u32(value.into(), 0), - _ => self.super_type().unwrap().parse_plain_attribute(name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(name, value), } } fn handle_event(&self, event: &Event) { if event.type_() != atom!("click") { - return + return; } - let area_elements = self.areas(); - let elements = match area_elements { - Some(x) => x, - None => return, - }; - - // Fetch click coordinates - let mouse_event = match event.downcast::<MouseEvent>() { - Some(x) => x, - None => return, - }; - - let point = Point2D::new(mouse_event.ClientX().to_f32().unwrap(), - mouse_event.ClientY().to_f32().unwrap()); - let bcr = self.upcast::<Element>().GetBoundingClientRect(); - let bcr_p = Point2D::new(bcr.X() as f32, bcr.Y() as f32); - - // Walk HTMLAreaElements - for element in elements { - let shape = element.get_shape_from_coords(); - let shp = match shape { - Some(x) => x.absolute_coords(bcr_p), - None => return, - }; - if shp.hit_test(&point) { - element.activation_behavior(event, self.upcast()); - return - } - } + let area_elements = self.areas(); + let elements = match area_elements { + Some(x) => x, + None => return, + }; + + // Fetch click coordinates + let mouse_event = match event.downcast::<MouseEvent>() { + Some(x) => x, + None => return, + }; + + let point = Point2D::new( + mouse_event.ClientX().to_f32().unwrap(), + mouse_event.ClientY().to_f32().unwrap(), + ); + let bcr = self.upcast::<Element>().GetBoundingClientRect(); + let bcr_p = Point2D::new(bcr.X() as f32, bcr.Y() as f32); + + // Walk HTMLAreaElements + for element in elements { + let shape = element.get_shape_from_coords(); + let shp = match shape { + Some(x) => x.absolute_coords(bcr_p), + None => return, + }; + if shp.hit_test(&point) { + element.activation_behavior(event, self.upcast()); + return; + } + } } fn bind_to_tree(&self, tree_in_doc: bool) { @@ -1561,11 +1675,7 @@ impl FormControl for HTMLImageElement { fn image_dimension_setter(element: &Element, attr: LocalName, value: u32) { // This setter is a bit weird: the IDL type is unsigned long, but it's parsed as // a dimension for rendering. - let value = if value > UNSIGNED_LONG_MAX { - 0 - } else { - value - }; + let value = if value > UNSIGNED_LONG_MAX { 0 } else { value }; // FIXME: There are probably quite a few more cases of this. This is the // only overflow that was hitting on automation, but we should consider what @@ -1585,11 +1695,12 @@ fn image_dimension_setter(element: &Element, attr: LocalName, value: u32) { /// Collect sequence of code points pub fn collect_sequence_characters<F>(s: &str, predicate: F) -> (&str, &str) - where F: Fn(&char) -> bool +where + F: Fn(&char) -> bool, { for (i, ch) in s.chars().enumerate() { if !predicate(&ch) { - return (&s[0..i], &s[i..]) + return (&s[0..i], &s[i..]); } } @@ -1602,7 +1713,8 @@ pub fn parse_a_srcset_attribute(input: &str) -> Vec<ImageSource> { let mut candidates: Vec<ImageSource> = vec![]; while url_len < input.len() { let position = &input[url_len..]; - let (spaces, position) = collect_sequence_characters(position, |c| *c == ',' || char::is_whitespace(*c)); + let (spaces, position) = + collect_sequence_characters(position, |c| *c == ',' || char::is_whitespace(*c)); // add the length of the url that we parse to advance the start index let space_len = spaces.char_indices().count(); url_len += space_len; @@ -1613,7 +1725,10 @@ pub fn parse_a_srcset_attribute(input: &str) -> Vec<ImageSource> { // add the counts of urls that we parse to advance the start index url_len += url.chars().count(); let comma_count = url.chars().rev().take_while(|c| *c == ',').count(); - let url: String = url.chars().take(url.chars().count() - comma_count).collect(); + let url: String = url + .chars() + .take(url.chars().count() - comma_count) + .collect(); // add 1 to start index, for the comma url_len += comma_count + 1; let (space, position) = collect_sequence_characters(spaces, |c| char::is_whitespace(*c)); @@ -1630,76 +1745,70 @@ pub fn parse_a_srcset_attribute(input: &str) -> Vec<ImageSource> { url_len += 1; } match state { - ParseState::InDescriptor => { - match next_char { - Some((_, ' ')) => { - if !current_descriptor.is_empty() { - descriptors.push(current_descriptor.clone()); - current_descriptor = String::new(); - state = ParseState::AfterDescriptor; - } - continue; - } - Some((_, ',')) => { - if !current_descriptor.is_empty() { - descriptors.push(current_descriptor.clone()); - } - break; - } - Some((_, c @ '(')) => { - current_descriptor.push(c); - state = ParseState::InParens; - continue; - } - Some((_, c)) => { - current_descriptor.push(c); - } - None => { - if !current_descriptor.is_empty() { - descriptors.push(current_descriptor.clone()); - } - break; - } - } - } - ParseState::InParens => { - match next_char { - Some((_, c @ ')')) => { - current_descriptor.push(c); - state = ParseState::InDescriptor; - continue; - } - Some((_, c)) => { - current_descriptor.push(c); - continue; + ParseState::InDescriptor => match next_char { + Some((_, ' ')) => { + if !current_descriptor.is_empty() { + descriptors.push(current_descriptor.clone()); + current_descriptor = String::new(); + state = ParseState::AfterDescriptor; } - None => { - if !current_descriptor.is_empty() { - descriptors.push(current_descriptor.clone()); - } - break; + continue; + }, + Some((_, ',')) => { + if !current_descriptor.is_empty() { + descriptors.push(current_descriptor.clone()); } - } - } - ParseState::AfterDescriptor => { - match next_char { - Some((_, ' ')) => { - state = ParseState::AfterDescriptor; - continue; + break; + }, + Some((_, c @ '(')) => { + current_descriptor.push(c); + state = ParseState::InParens; + continue; + }, + Some((_, c)) => { + current_descriptor.push(c); + }, + None => { + if !current_descriptor.is_empty() { + descriptors.push(current_descriptor.clone()); } - Some((idx, c)) => { - state = ParseState::InDescriptor; - buffered = Some((idx, c)); - continue; + break; + }, + }, + ParseState::InParens => match next_char { + Some((_, c @ ')')) => { + current_descriptor.push(c); + state = ParseState::InDescriptor; + continue; + }, + Some((_, c)) => { + current_descriptor.push(c); + continue; + }, + None => { + if !current_descriptor.is_empty() { + descriptors.push(current_descriptor.clone()); } - None => { - if !current_descriptor.is_empty() { - descriptors.push(current_descriptor.clone()); - } - break; + break; + }, + }, + ParseState::AfterDescriptor => match next_char { + Some((_, ' ')) => { + state = ParseState::AfterDescriptor; + continue; + }, + Some((idx, c)) => { + state = ParseState::InDescriptor; + buffered = Some((idx, c)); + continue; + }, + None => { + if !current_descriptor.is_empty() { + descriptors.push(current_descriptor.clone()); } - } - } + break; + }, + }, } } @@ -1708,7 +1817,8 @@ pub fn parse_a_srcset_attribute(input: &str) -> Vec<ImageSource> { let mut density: Option<f64> = None; let mut future_compat_h: Option<u32> = None; for descriptor in descriptors { - let (digits, remaining) = collect_sequence_characters(&descriptor, |c| is_ascii_digit(c) || *c == '.'); + let (digits, remaining) = + collect_sequence_characters(&descriptor, |c| is_ascii_digit(c) || *c == '.'); let valid_non_negative_integer = parse_unsigned_integer(digits.chars()); let has_w = remaining == "w"; let valid_floating_point = parse_double(digits); @@ -1749,8 +1859,14 @@ pub fn parse_a_srcset_attribute(input: &str) -> Vec<ImageSource> { error = true; } if !error { - let descriptor = Descriptor { wid: width, den: density }; - let image_source = ImageSource { url: url, descriptor: descriptor }; + let descriptor = Descriptor { + wid: width, + den: density, + }; + let image_source = ImageSource { + url: url, + descriptor: descriptor, + }; candidates.push(image_source); } } diff --git a/components/script/dom/htmlinputelement.rs b/components/script/dom/htmlinputelement.rs index f2d83fa4d54..163a85cbdb6 100755 --- a/components/script/dom/htmlinputelement.rs +++ b/components/script/dom/htmlinputelement.rs @@ -97,15 +97,22 @@ impl InputType { // than the underlying value. fn is_textual(&self) -> bool { match *self { - InputType::Color | InputType::Date | InputType::DatetimeLocal - | InputType::Email | InputType::Hidden | InputType::Month - | InputType::Number | InputType::Range | InputType::Search - | InputType::Tel | InputType::Text | InputType::Time - | InputType::Url | InputType::Week => { - true - } - - _ => false + InputType::Color | + InputType::Date | + InputType::DatetimeLocal | + InputType::Email | + InputType::Hidden | + InputType::Month | + InputType::Number | + InputType::Range | + InputType::Search | + InputType::Tel | + InputType::Text | + InputType::Time | + InputType::Url | + InputType::Week => true, + + _ => false, } } @@ -185,7 +192,7 @@ impl<'a> From<&'a Atom> for InputType { atom!("time") => InputType::Time, atom!("url") => InputType::Url, atom!("week") => InputType::Week, - _ => Self::default() + _ => Self::default(), } } } @@ -245,7 +252,7 @@ impl InputActivationState { checked_changed: false, checked_radio: None, was_mutable: false, - old_type: Default::default() + old_type: Default::default(), } } } @@ -255,25 +262,37 @@ static DEFAULT_MAX_LENGTH: i32 = -1; static DEFAULT_MIN_LENGTH: i32 = -1; impl HTMLInputElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLInputElement { - let chan = document.window().upcast::<GlobalScope>().script_to_constellation_chan().clone(); + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLInputElement { + let chan = document + .window() + .upcast::<GlobalScope>() + .script_to_constellation_chan() + .clone(); HTMLInputElement { - htmlelement: - HTMLElement::new_inherited_with_state(ElementState::IN_ENABLED_STATE | - ElementState::IN_READ_WRITE_STATE, - local_name, prefix, document), + htmlelement: HTMLElement::new_inherited_with_state( + ElementState::IN_ENABLED_STATE | ElementState::IN_READ_WRITE_STATE, + local_name, + prefix, + document, + ), input_type: Cell::new(Default::default()), placeholder: DomRefCell::new(DOMString::new()), checked_changed: Cell::new(false), maxlength: Cell::new(DEFAULT_MAX_LENGTH), minlength: Cell::new(DEFAULT_MIN_LENGTH), size: Cell::new(DEFAULT_INPUT_SIZE), - textinput: DomRefCell::new(TextInput::new(Single, - DOMString::new(), - chan, - None, - None, - SelectionDirection::None)), + textinput: DomRefCell::new(TextInput::new( + Single, + DOMString::new(), + chan, + None, + None, + SelectionDirection::None, + )), activation_state: DomRefCell::new(InputActivationState::new()), value_dirty: Cell::new(false), filelist: MutNullableDom::new(None), @@ -282,34 +301,46 @@ impl HTMLInputElement { } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLInputElement> { - Node::reflect_node(Box::new(HTMLInputElement::new_inherited(local_name, prefix, document)), - document, - HTMLInputElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLInputElement> { + Node::reflect_node( + Box::new(HTMLInputElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLInputElementBinding::Wrap, + ) } // https://html.spec.whatwg.org/multipage/#dom-input-value // https://html.spec.whatwg.org/multipage/#concept-input-apply fn value_mode(&self) -> ValueMode { match self.input_type() { - InputType::Submit | InputType::Reset | InputType::Button - | InputType::Image | InputType::Hidden => { - ValueMode::Default - }, - - InputType::Checkbox | InputType::Radio => { - ValueMode::DefaultOn - }, - - InputType::Color | InputType::Date | InputType::DatetimeLocal - | InputType::Email | InputType::Month | InputType::Number - | InputType::Password | InputType::Range | InputType::Search - | InputType::Tel | InputType::Text | InputType::Time - | InputType::Url | InputType::Week => { - ValueMode::Value - } + InputType::Submit | + InputType::Reset | + InputType::Button | + InputType::Image | + InputType::Hidden => ValueMode::Default, + + InputType::Checkbox | InputType::Radio => ValueMode::DefaultOn, + + InputType::Color | + InputType::Date | + InputType::DatetimeLocal | + InputType::Email | + InputType::Month | + InputType::Number | + InputType::Password | + InputType::Range | + InputType::Search | + InputType::Tel | + InputType::Text | + InputType::Time | + InputType::Url | + InputType::Week => ValueMode::Value, InputType::File => ValueMode::Filename, } @@ -336,7 +367,10 @@ pub trait LayoutHTMLInputElementHelpers { #[allow(unsafe_code)] unsafe fn get_raw_textinput_value(input: LayoutDom<HTMLInputElement>) -> DOMString { - (*input.unsafe_get()).textinput.borrow_for_layout().get_content() + (*input.unsafe_get()) + .textinput + .borrow_for_layout() + .get_content() } impl LayoutHTMLInputElementHelpers for LayoutDom<HTMLInputElement> { @@ -397,27 +431,33 @@ impl LayoutHTMLInputElementHelpers for LayoutDom<HTMLInputElement> { let sel = textinput.sorted_selection_offsets_range(); // Translate indices from the raw value to indices in the replacement value. - let char_start = text[.. sel.start].chars().count(); + let char_start = text[..sel.start].chars().count(); let char_end = char_start + text[sel].chars().count(); let bytes_per_char = PASSWORD_REPLACEMENT_CHAR.len_utf8(); - Some(char_start * bytes_per_char .. char_end * bytes_per_char) - } - input_type if input_type.is_textual() => Some(textinput.sorted_selection_offsets_range()), - _ => None + Some(char_start * bytes_per_char..char_end * bytes_per_char) + }, + input_type if input_type.is_textual() => { + Some(textinput.sorted_selection_offsets_range()) + }, + _ => None, } } #[allow(unrooted_must_root)] #[allow(unsafe_code)] unsafe fn checked_state_for_layout(self) -> bool { - self.upcast::<Element>().get_state_for_layout().contains(ElementState::IN_CHECKED_STATE) + self.upcast::<Element>() + .get_state_for_layout() + .contains(ElementState::IN_CHECKED_STATE) } #[allow(unrooted_must_root)] #[allow(unsafe_code)] unsafe fn indeterminate_state_for_layout(self) -> bool { - self.upcast::<Element>().get_state_for_layout().contains(ElementState::IN_INDETERMINATE_STATE) + self.upcast::<Element>() + .get_state_for_layout() + .contains(ElementState::IN_INDETERMINATE_STATE) } } @@ -425,12 +465,13 @@ impl TextControlElement for HTMLInputElement { // https://html.spec.whatwg.org/multipage/#concept-input-apply fn selection_api_applies(&self) -> bool { match self.input_type() { - InputType::Text | InputType::Search | InputType::Url - | InputType::Tel | InputType::Password => { - true - }, + InputType::Text | + InputType::Search | + InputType::Url | + InputType::Tel | + InputType::Password => true, - _ => false + _ => false, } } @@ -443,19 +484,29 @@ impl TextControlElement for HTMLInputElement { // rendered as a text control: file fn has_selectable_text(&self) -> bool { match self.input_type() { - InputType::Text | InputType::Search | InputType::Url - | InputType::Tel | InputType::Password | InputType::Email - | InputType::Date | InputType::Month | InputType::Week - | InputType::Time | InputType::DatetimeLocal | InputType::Number - | InputType::Color => { - true - } - - InputType::Button | InputType::Checkbox | InputType::File - | InputType::Hidden | InputType::Image | InputType::Radio - | InputType::Range | InputType::Reset | InputType::Submit => { - false - } + InputType::Text | + InputType::Search | + InputType::Url | + InputType::Tel | + InputType::Password | + InputType::Email | + InputType::Date | + InputType::Month | + InputType::Week | + InputType::Time | + InputType::DatetimeLocal | + InputType::Number | + InputType::Color => true, + + InputType::Button | + InputType::Checkbox | + InputType::File | + InputType::Hidden | + InputType::Image | + InputType::Radio | + InputType::Range | + InputType::Reset | + InputType::Submit => false, } } @@ -510,7 +561,9 @@ impl HTMLInputElementMethods for HTMLInputElement { // https://html.spec.whatwg.org/multipage/#dom-input-checked fn Checked(&self) -> bool { - self.upcast::<Element>().state().contains(ElementState::IN_CHECKED_STATE) + self.upcast::<Element>() + .state() + .contains(ElementState::IN_CHECKED_STATE) } // https://html.spec.whatwg.org/multipage/#dom-input-checked @@ -542,18 +595,18 @@ impl HTMLInputElementMethods for HTMLInputElement { fn Value(&self) -> DOMString { match self.value_mode() { ValueMode::Value => self.textinput.borrow().get_content(), - ValueMode::Default => { - self.upcast::<Element>() - .get_attribute(&ns!(), &local_name!("value")) - .map_or(DOMString::from(""), - |a| DOMString::from(a.summarize().value)) - } - ValueMode::DefaultOn => { - self.upcast::<Element>() - .get_attribute(&ns!(), &local_name!("value")) - .map_or(DOMString::from("on"), - |a| DOMString::from(a.summarize().value)) - } + ValueMode::Default => self + .upcast::<Element>() + .get_attribute(&ns!(), &local_name!("value")) + .map_or(DOMString::from(""), |a| { + DOMString::from(a.summarize().value) + }), + ValueMode::DefaultOn => self + .upcast::<Element>() + .get_attribute(&ns!(), &local_name!("value")) + .map_or(DOMString::from("on"), |a| { + DOMString::from(a.summarize().value) + }), ValueMode::Filename => { let mut path = DOMString::from(""); match self.filelist.get() { @@ -562,12 +615,12 @@ impl HTMLInputElementMethods for HTMLInputElement { path.push_str("C:\\fakepath\\"); path.push_str(f.name()); path - } + }, None => path, }, None => path, } - } + }, } } @@ -579,7 +632,7 @@ impl HTMLInputElementMethods for HTMLInputElement { self.value_dirty.set(true); // Step 4. - self.sanitize_value(&mut value); + self.sanitize_value(&mut value); let mut textinput = self.textinput.borrow_mut(); @@ -591,11 +644,11 @@ impl HTMLInputElementMethods for HTMLInputElement { // Step 5. textinput.clear_selection_to_limit(Direction::Forward); } - } - ValueMode::Default | - ValueMode::DefaultOn => { - self.upcast::<Element>().set_string_attribute(&local_name!("value"), value); - } + }, + ValueMode::Default | ValueMode::DefaultOn => { + self.upcast::<Element>() + .set_string_attribute(&local_name!("value"), value); + }, ValueMode::Filename => { if value.is_empty() { let window = window_from_node(self); @@ -604,7 +657,7 @@ impl HTMLInputElementMethods for HTMLInputElement { } else { return Err(Error::InvalidState); } - } + }, } self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage); @@ -636,10 +689,12 @@ impl HTMLInputElementMethods for HTMLInputElement { make_setter!(SetFormAction, "formaction"); // https://html.spec.whatwg.org/multipage/#dom-input-formenctype - make_enumerated_getter!(FormEnctype, - "formenctype", - "application/x-www-form-urlencoded", - "text/plain" | "multipart/form-data"); + make_enumerated_getter!( + FormEnctype, + "formenctype", + "application/x-www-form-urlencoded", + "text/plain" | "multipart/form-data" + ); // https://html.spec.whatwg.org/multipage/#dom-input-formenctype make_setter!(SetFormEnctype, "formenctype"); @@ -718,12 +773,15 @@ impl HTMLInputElementMethods for HTMLInputElement { // https://html.spec.whatwg.org/multipage/#dom-input-indeterminate fn Indeterminate(&self) -> bool { - self.upcast::<Element>().state().contains(ElementState::IN_INDETERMINATE_STATE) + self.upcast::<Element>() + .state() + .contains(ElementState::IN_INDETERMINATE_STATE) } // https://html.spec.whatwg.org/multipage/#dom-input-indeterminate fn SetIndeterminate(&self, val: bool) { - self.upcast::<Element>().set_state(ElementState::IN_INDETERMINATE_STATE, val) + self.upcast::<Element>() + .set_state(ElementState::IN_INDETERMINATE_STATE, val) } // https://html.spec.whatwg.org/multipage/#dom-lfe-labels @@ -778,13 +836,20 @@ impl HTMLInputElementMethods for HTMLInputElement { // https://html.spec.whatwg.org/multipage/#dom-textarea/input-setrangetext fn SetRangeText(&self, replacement: DOMString) -> ErrorResult { - self.selection().set_dom_range_text(replacement, None, None, Default::default()) + self.selection() + .set_dom_range_text(replacement, None, None, Default::default()) } // https://html.spec.whatwg.org/multipage/#dom-textarea/input-setrangetext - fn SetRangeText_(&self, replacement: DOMString, start: u32, end: u32, - selection_mode: SelectionMode) -> ErrorResult { - self.selection().set_dom_range_text(replacement, Some(start), Some(end), selection_mode) + fn SetRangeText_( + &self, + replacement: DOMString, + start: u32, + end: u32, + selection_mode: SelectionMode, + ) -> ErrorResult { + self.selection() + .set_dom_range_text(replacement, Some(start), Some(end), selection_mode) } // Select the files based on filepaths passed in, @@ -798,7 +863,6 @@ impl HTMLInputElementMethods for HTMLInputElement { } } - #[allow(unsafe_code)] fn broadcast_radio_checked(broadcaster: &HTMLInputElement, group: Option<&Atom>) { match group { @@ -815,11 +879,17 @@ fn broadcast_radio_checked(broadcaster: &HTMLInputElement, group: Option<&Atom>) let doc = document_from_node(broadcaster); // This function is a workaround for lifetime constraint difficulties. - fn do_broadcast(doc_node: &Node, broadcaster: &HTMLInputElement, - owner: Option<&HTMLFormElement>, group: Option<&Atom>) { - let iter = doc_node.query_selector_iter(DOMString::from("input[type=radio]")).unwrap() - .filter_map(DomRoot::downcast::<HTMLInputElement>) - .filter(|r| in_same_group(&r, owner, group) && broadcaster != &**r); + fn do_broadcast( + doc_node: &Node, + broadcaster: &HTMLInputElement, + owner: Option<&HTMLFormElement>, + group: Option<&Atom>, + ) { + let iter = doc_node + .query_selector_iter(DOMString::from("input[type=radio]")) + .unwrap() + .filter_map(DomRoot::downcast::<HTMLInputElement>) + .filter(|r| in_same_group(&r, owner, group) && broadcaster != &**r); for ref r in iter { if r.Checked() { r.SetChecked(false); @@ -831,8 +901,11 @@ fn broadcast_radio_checked(broadcaster: &HTMLInputElement, group: Option<&Atom>) } // https://html.spec.whatwg.org/multipage/#radio-button-group -fn in_same_group(other: &HTMLInputElement, owner: Option<&HTMLFormElement>, - group: Option<&Atom>) -> bool { +fn in_same_group( + other: &HTMLInputElement, + owner: Option<&HTMLFormElement>, + group: Option<&Atom>, +) -> bool { other.input_type() == InputType::Radio && // TODO Both a and b are in the same home subtree. other.form_owner().r() == owner && @@ -860,15 +933,15 @@ impl HTMLInputElement { // Step 3.4 let name = self.Name(); let is_submitter = match submitter { - Some(FormSubmitter::InputElement(s)) => { - self == s - }, - _ => false + Some(FormSubmitter::InputElement(s)) => self == s, + _ => false, }; match self.input_type() { // Step 3.1: it's a button but it is not submitter. - InputType::Submit | InputType::Button | InputType::Reset if !is_submitter => return vec![], + InputType::Submit | InputType::Button | InputType::Reset if !is_submitter => { + return vec![] + }, // Step 3.1: it's the "Checkbox" or "Radio Button" and whose checkedness is false. InputType::Radio | InputType::Checkbox => if !self.Checked() || name.is_empty() { @@ -890,7 +963,7 @@ impl HTMLInputElement { value: FormDatumValue::File(DomRoot::from_ref(&f)), }); } - } + }, None => { datums.push(FormDatum { // XXX(izgzhen): Spec says 'application/octet-stream' as the type, @@ -899,26 +972,25 @@ impl HTMLInputElement { name: name.clone(), value: FormDatumValue::String(DOMString::from("")), }) - } + }, } return datums; - } + }, InputType::Image => return vec![], // Unimplemented // Step 3.1: it's not the "Image Button" and doesn't have a name attribute. _ => if name.is_empty() { return vec![]; - } - + }, } // Step 3.9 vec![FormDatum { ty: ty.clone(), name: name, - value: FormDatumValue::String(self.Value()) + value: FormDatumValue::String(self.Value()), }] } @@ -931,15 +1003,15 @@ impl HTMLInputElement { } fn update_checked_state(&self, checked: bool, dirty: bool) { - self.upcast::<Element>().set_state(ElementState::IN_CHECKED_STATE, checked); + self.upcast::<Element>() + .set_state(ElementState::IN_CHECKED_STATE, checked); if dirty { self.checked_changed.set(true); } if self.input_type() == InputType::Radio && checked { - broadcast_radio_checked(self, - self.radio_group_name().as_ref()); + broadcast_radio_checked(self, self.radio_group_name().as_ref()); } self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage); @@ -961,7 +1033,7 @@ impl HTMLInputElement { self.checked_changed.set(false); }, InputType::Image => (), - _ => () + _ => (), } self.textinput.borrow_mut().set_content(self.DefaultValue()); self.value_dirty.set(false); @@ -970,7 +1042,7 @@ impl HTMLInputElement { fn update_placeholder_shown_state(&self) { if !self.input_type().is_textual_or_password() { - return + return; } let has_placeholder = !self.placeholder.borrow().is_empty(); @@ -994,12 +1066,15 @@ impl HTMLInputElement { let target = self.upcast::<EventTarget>(); if self.Multiple() { - let opt_test_paths = opt_test_paths.map(|paths| paths.iter().map(|p| p.to_string()).collect()); + let opt_test_paths = + opt_test_paths.map(|paths| paths.iter().map(|p| p.to_string()).collect()); - let (chan, recv) = - ipc::channel(self.global().time_profiler_chan().clone()).expect("Error initializing channel"); + let (chan, recv) = ipc::channel(self.global().time_profiler_chan().clone()) + .expect("Error initializing channel"); let msg = FileManagerThreadMsg::SelectFiles(filter, chan, origin, opt_test_paths); - let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg)).unwrap(); + let _ = resource_threads + .send(CoreResourceMsg::ToFileManager(msg)) + .unwrap(); match recv.recv().expect("IpcSender side error") { Ok(selected_files) => { @@ -1017,14 +1092,16 @@ impl HTMLInputElement { } else { Some(paths[0].to_string()) // neglect other paths } - } + }, None => None, }; - let (chan, recv) = - ipc::channel(self.global().time_profiler_chan().clone()).expect("Error initializing channel"); + let (chan, recv) = ipc::channel(self.global().time_profiler_chan().clone()) + .expect("Error initializing channel"); let msg = FileManagerThreadMsg::SelectFile(filter, chan, origin, opt_test_path); - let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg)).unwrap(); + let _ = resource_threads + .send(CoreResourceMsg::ToFileManager(msg)) + .unwrap(); match recv.recv().expect("IpcSender side error") { Ok(selected) => { @@ -1050,26 +1127,26 @@ impl HTMLInputElement { match self.input_type() { InputType::Text | InputType::Search | InputType::Tel | InputType::Password => { value.strip_newlines(); - } + }, InputType::Url => { value.strip_newlines(); value.strip_leading_and_trailing_ascii_whitespace(); - } + }, InputType::Date => { if !value.is_valid_date_string() { value.clear(); } - } + }, InputType::Month => { if !value.is_valid_month_string() { value.clear(); } - } + }, InputType::Week => { if !value.is_valid_week_string() { value.clear(); } - } + }, InputType::Color => { let is_valid = { let mut chars = value.chars(); @@ -1085,27 +1162,30 @@ impl HTMLInputElement { } else { *value = "#000000".into(); } - } + }, InputType::Time => { if !value.is_valid_time_string() { value.clear(); } - } + }, InputType::DatetimeLocal => { - if value.convert_valid_normalized_local_date_and_time_string().is_err() { + if value + .convert_valid_normalized_local_date_and_time_string() + .is_err() + { value.clear(); } - } + }, InputType::Number => { if !value.is_valid_floating_point_number_string() { value.clear(); } - } + }, // https://html.spec.whatwg.org/multipage/#range-state-(type=range):value-sanitization-algorithm InputType::Range => { value.set_best_representation_of_the_floating_point_number(); - } - _ => () + }, + _ => (), } } @@ -1127,8 +1207,8 @@ impl VirtualMethods for HTMLInputElement { let disabled_state = match mutation { AttributeMutation::Set(None) => true, AttributeMutation::Set(Some(_)) => { - // Input was already disabled before. - return; + // Input was already disabled before. + return; }, AttributeMutation::Removed => false, }; @@ -1146,19 +1226,17 @@ impl VirtualMethods for HTMLInputElement { let checked_state = match mutation { AttributeMutation::Set(None) => true, AttributeMutation::Set(Some(_)) => { - // Input was already checked before. - return; + // Input was already checked before. + return; }, AttributeMutation::Removed => false, }; self.update_checked_state(checked_state, false); }, &local_name!("size") => { - let size = mutation.new_value(attr).map(|value| { - value.as_uint() - }); + let size = mutation.new_value(attr).map(|value| value.as_uint()); self.size.set(size.unwrap_or(DEFAULT_INPUT_SIZE)); - } + }, &local_name!("type") => { let el = self.upcast::<Element>(); match mutation { @@ -1192,30 +1270,35 @@ impl VirtualMethods for HTMLInputElement { (&ValueMode::Value, false, ValueMode::DefaultOn) => { self.SetValue(old_idl_value) .expect("Failed to set input value on type change to a default ValueMode."); - } + }, // Step 2 (_, _, ValueMode::Value) if old_value_mode != ValueMode::Value => { - self.SetValue(self.upcast::<Element>() - .get_attribute(&ns!(), &local_name!("value")) - .map_or(DOMString::from(""), - |a| DOMString::from(a.summarize().value))) - .expect("Failed to set input value on type change to ValueMode::Value."); + self.SetValue( + self.upcast::<Element>() + .get_attribute(&ns!(), &local_name!("value")) + .map_or(DOMString::from(""), |a| { + DOMString::from(a.summarize().value) + }), + ).expect( + "Failed to set input value on type change to ValueMode::Value.", + ); self.value_dirty.set(false); - } + }, // Step 3 - (_, _, ValueMode::Filename) if old_value_mode != ValueMode::Filename => { + (_, _, ValueMode::Filename) + if old_value_mode != ValueMode::Filename => + { self.SetValue(DOMString::from("")) .expect("Failed to set input value on type change to ValueMode::Filename."); } - _ => {} + _ => {}, } // Step 5 if new_type == InputType::Radio { - self.radio_group_updated( - self.radio_group_name().as_ref()); + self.radio_group_updated(self.radio_group_name().as_ref()); } // Step 6 @@ -1231,16 +1314,14 @@ impl VirtualMethods for HTMLInputElement { }, AttributeMutation::Removed => { if self.input_type() == InputType::Radio { - broadcast_radio_checked( - self, - self.radio_group_name().as_ref()); + broadcast_radio_checked(self, self.radio_group_name().as_ref()); } self.input_type.set(InputType::default()); let el = self.upcast::<Element>(); let read_write = !(self.ReadOnly() || el.disabled_state()); el.set_read_write_state(read_write); - } + }, } self.update_placeholder_shown_state(); @@ -1255,43 +1336,40 @@ impl VirtualMethods for HTMLInputElement { }, &local_name!("name") if self.input_type() == InputType::Radio => { self.radio_group_updated( - mutation.new_value(attr).as_ref().map(|name| name.as_atom())); + mutation.new_value(attr).as_ref().map(|name| name.as_atom()), + ); }, - &local_name!("maxlength") => { - match *attr.value() { - AttrValue::Int(_, value) => { - let mut textinput = self.textinput.borrow_mut(); + &local_name!("maxlength") => match *attr.value() { + AttrValue::Int(_, value) => { + let mut textinput = self.textinput.borrow_mut(); - if value < 0 { - textinput.set_max_length(None); - } else { - textinput.set_max_length(Some(value as usize)) - } - }, - _ => panic!("Expected an AttrValue::Int"), - } + if value < 0 { + textinput.set_max_length(None); + } else { + textinput.set_max_length(Some(value as usize)) + } + }, + _ => panic!("Expected an AttrValue::Int"), }, - &local_name!("minlength") => { - match *attr.value() { - AttrValue::Int(_, value) => { - let mut textinput = self.textinput.borrow_mut(); + &local_name!("minlength") => match *attr.value() { + AttrValue::Int(_, value) => { + let mut textinput = self.textinput.borrow_mut(); - if value < 0 { - textinput.set_min_length(None); - } else { - textinput.set_min_length(Some(value as usize)) - } - }, - _ => panic!("Expected an AttrValue::Int"), - } + if value < 0 { + textinput.set_min_length(None); + } else { + textinput.set_min_length(Some(value as usize)) + } + }, + _ => panic!("Expected an AttrValue::Int"), }, &local_name!("placeholder") => { { let mut placeholder = self.placeholder.borrow_mut(); placeholder.clear(); if let AttributeMutation::Set(_) = mutation { - placeholder.extend( - attr.value().chars().filter(|&c| c != '\n' && c != '\r')); + placeholder + .extend(attr.value().chars().filter(|&c| c != '\n' && c != '\r')); } } self.update_placeholder_shown_state(); @@ -1304,7 +1382,7 @@ impl VirtualMethods for HTMLInputElement { }, AttributeMutation::Removed => { el.set_read_write_state(!el.disabled_state()); - } + }, } }, &local_name!("form") => { @@ -1320,9 +1398,16 @@ impl VirtualMethods for HTMLInputElement { &local_name!("name") => AttrValue::from_atomic(value.into()), &local_name!("size") => AttrValue::from_limited_u32(value.into(), DEFAULT_INPUT_SIZE), &local_name!("type") => AttrValue::from_atomic(value.into()), - &local_name!("maxlength") => AttrValue::from_limited_i32(value.into(), DEFAULT_MAX_LENGTH), - &local_name!("minlength") => AttrValue::from_limited_i32(value.into(), DEFAULT_MIN_LENGTH), - _ => self.super_type().unwrap().parse_plain_attribute(name, value), + &local_name!("maxlength") => { + AttrValue::from_limited_i32(value.into(), DEFAULT_MAX_LENGTH) + }, + &local_name!("minlength") => { + AttrValue::from_limited_i32(value.into(), DEFAULT_MIN_LENGTH) + }, + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(name, value), } } @@ -1330,7 +1415,8 @@ impl VirtualMethods for HTMLInputElement { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } - self.upcast::<Element>().check_ancestors_disabled_state_for_form_control(); + self.upcast::<Element>() + .check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { @@ -1338,7 +1424,10 @@ impl VirtualMethods for HTMLInputElement { let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); - if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { + if node + .ancestors() + .any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) + { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); @@ -1359,64 +1448,72 @@ impl VirtualMethods for HTMLInputElement { document_from_node(self).request_focus(self.upcast()); if self.input_type().is_textual_or_password() && // Check if we display a placeholder. Layout doesn't know about this. - !self.textinput.borrow().is_empty() { - if let Some(mouse_event) = event.downcast::<MouseEvent>() { - // dispatch_key_event (document.rs) triggers a click event when releasing - // the space key. There's no nice way to catch this so let's use this for - // now. - if let Some(point_in_target) = mouse_event.point_in_target() { - let window = window_from_node(self); - let TextIndexResponse(index) = window.text_index_query( - self.upcast::<Node>().to_trusted_node_address(), - point_in_target - ); - if let Some(i) = index { - self.textinput.borrow_mut().set_edit_point_index(i as usize); - // trigger redraw - self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage); - event.PreventDefault(); - } - } - } - } - } else if event.type_() == atom!("keydown") && !event.DefaultPrevented() && - self.input_type().is_textual_or_password() { - if let Some(keyevent) = event.downcast::<KeyboardEvent>() { - // This can't be inlined, as holding on to textinput.borrow_mut() - // during self.implicit_submission will cause a panic. - let action = self.textinput.borrow_mut().handle_keydown(keyevent); - match action { - TriggerDefaultAction => { - self.implicit_submission(keyevent.CtrlKey(), - keyevent.ShiftKey(), - keyevent.AltKey(), - keyevent.MetaKey()); - }, - DispatchInput => { - self.value_dirty.set(true); - self.update_placeholder_shown_state(); + !self.textinput.borrow().is_empty() + { + if let Some(mouse_event) = event.downcast::<MouseEvent>() { + // dispatch_key_event (document.rs) triggers a click event when releasing + // the space key. There's no nice way to catch this so let's use this for + // now. + if let Some(point_in_target) = mouse_event.point_in_target() { + let window = window_from_node(self); + let TextIndexResponse(index) = window.text_index_query( + self.upcast::<Node>().to_trusted_node_address(), + point_in_target, + ); + if let Some(i) = index { + self.textinput.borrow_mut().set_edit_point_index(i as usize); + // trigger redraw self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage); - event.mark_as_handled(); + event.PreventDefault(); } - RedrawSelection => { - self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage); - event.mark_as_handled(); - } - Nothing => (), } } - } else if event.type_() == atom!("keypress") && !event.DefaultPrevented() && - self.input_type().is_textual_or_password() { - if event.IsTrusted() { - let window = window_from_node(self); - let _ = window.user_interaction_task_source() - .queue_event(&self.upcast(), - atom!("input"), - EventBubbles::Bubbles, - EventCancelable::NotCancelable, - &window); + } + } else if event.type_() == atom!("keydown") && + !event.DefaultPrevented() && + self.input_type().is_textual_or_password() + { + if let Some(keyevent) = event.downcast::<KeyboardEvent>() { + // This can't be inlined, as holding on to textinput.borrow_mut() + // during self.implicit_submission will cause a panic. + let action = self.textinput.borrow_mut().handle_keydown(keyevent); + match action { + TriggerDefaultAction => { + self.implicit_submission( + keyevent.CtrlKey(), + keyevent.ShiftKey(), + keyevent.AltKey(), + keyevent.MetaKey(), + ); + }, + DispatchInput => { + self.value_dirty.set(true); + self.update_placeholder_shown_state(); + self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage); + event.mark_as_handled(); + }, + RedrawSelection => { + self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage); + event.mark_as_handled(); + }, + Nothing => (), } } + } else if event.type_() == atom!("keypress") && + !event.DefaultPrevented() && + self.input_type().is_textual_or_password() + { + if event.IsTrusted() { + let window = window_from_node(self); + let _ = window.user_interaction_task_source().queue_event( + &self.upcast(), + atom!("input"), + EventBubbles::Bubbles, + EventCancelable::NotCancelable, + &window, + ); + } + } } } @@ -1456,9 +1553,12 @@ impl Activatable for HTMLInputElement { // https://html.spec.whatwg.org/multipage/#reset-button-state-%28type=reset%29:activation-behaviour-2 // https://html.spec.whatwg.org/multipage/#checkbox-state-%28type=checkbox%29:activation-behaviour-2 // https://html.spec.whatwg.org/multipage/#radio-button-state-%28type=radio%29:activation-behaviour-2 - InputType::Submit | InputType::Reset | InputType::File - | InputType::Checkbox | InputType::Radio => self.is_mutable(), - _ => false + InputType::Submit | + InputType::Reset | + InputType::File | + InputType::Checkbox | + InputType::Radio => self.is_mutable(), + _ => false, } } @@ -1496,18 +1596,16 @@ impl Activatable for HTMLInputElement { let group = self.radio_group_name();; // Safe since we only manipulate the DOM tree after finding an element - let checked_member = doc_node.query_selector_iter(DOMString::from("input[type=radio]")) - .unwrap() - .filter_map(DomRoot::downcast::<HTMLInputElement>) - .find(|r| { - in_same_group(&*r, owner.r(), group.as_ref()) && - r.Checked() - }); + let checked_member = doc_node + .query_selector_iter(DOMString::from("input[type=radio]")) + .unwrap() + .filter_map(DomRoot::downcast::<HTMLInputElement>) + .find(|r| in_same_group(&*r, owner.r(), group.as_ref()) && r.Checked()); cache.checked_radio = checked_member.r().map(Dom::from_ref); cache.checked_changed = self.checked_changed.get(); self.SetChecked(true); - } - _ => () + }, + _ => (), } } } @@ -1516,7 +1614,7 @@ impl Activatable for HTMLInputElement { fn canceled_activation(&self) { let cache = self.activation_state.borrow(); let ty = self.input_type(); - if cache.old_type != ty { + if cache.old_type != ty { // Type changed, abandon ship // https://www.w3.org/Bugs/Public/show_bug.cgi?id=27414 return; @@ -1543,18 +1641,22 @@ impl Activatable for HTMLInputElement { Some(o) => { // Avoiding iterating through the whole tree here, instead // we can check if the conditions for radio group siblings apply - if in_same_group(&o, self.form_owner().r(), self.radio_group_name().as_ref()) { + if in_same_group( + &o, + self.form_owner().r(), + self.radio_group_name().as_ref(), + ) { o.SetChecked(true); } else { self.SetChecked(false); } }, - None => self.SetChecked(false) + None => self.SetChecked(false), }; self.checked_changed.set(cache.checked_changed); } - } - _ => () + }, + _ => (), } } @@ -1572,17 +1674,17 @@ impl Activatable for HTMLInputElement { // FIXME (Manishearth): support document owners (needs ability to get parent browsing context) // Check if document owner is fully active self.form_owner().map(|o| { - o.submit(SubmittedFrom::NotFromForm, - FormSubmitter::InputElement(self.clone())) + o.submit( + SubmittedFrom::NotFromForm, + FormSubmitter::InputElement(self.clone()), + ) }); }, InputType::Reset => { // https://html.spec.whatwg.org/multipage/#reset-button-state-(type=reset):activation-behavior // FIXME (Manishearth): support document owners (needs ability to get parent browsing context) // Check if document owner is fully active - self.form_owner().map(|o| { - o.reset(ResetFrom::NotFromForm) - }); + self.form_owner().map(|o| o.reset(ResetFrom::NotFromForm)); }, InputType::Checkbox | InputType::Radio => { // https://html.spec.whatwg.org/multipage/#checkbox-state-(type=checkbox):activation-behavior @@ -1593,7 +1695,7 @@ impl Activatable for HTMLInputElement { target.fire_bubbling_event(atom!("change")); }, InputType::File => self.select_files(None), - _ => () + _ => (), } } @@ -1605,38 +1707,51 @@ impl Activatable for HTMLInputElement { let owner = self.form_owner(); let form = match owner { None => return, - Some(ref f) => f + Some(ref f) => f, }; if self.upcast::<Element>().click_in_progress() { return; } let submit_button; - submit_button = node.query_selector_iter(DOMString::from("input[type=submit]")).unwrap() + submit_button = node + .query_selector_iter(DOMString::from("input[type=submit]")) + .unwrap() .filter_map(DomRoot::downcast::<HTMLInputElement>) .find(|r| r.form_owner() == owner); match submit_button { Some(ref button) => { if button.is_instance_activatable() { - synthetic_click_activation(button.as_element(), - ctrl_key, - shift_key, - alt_key, - meta_key, - ActivationSource::NotFromClick) + synthetic_click_activation( + button.as_element(), + ctrl_key, + shift_key, + alt_key, + meta_key, + ActivationSource::NotFromClick, + ) } - } + }, None => { - let inputs = node.query_selector_iter(DOMString::from("input")).unwrap() + let inputs = node + .query_selector_iter(DOMString::from("input")) + .unwrap() .filter_map(DomRoot::downcast::<HTMLInputElement>) .filter(|input| { input.form_owner() == owner && match input.input_type() { - InputType::Text | InputType::Search | InputType::Url | InputType::Tel - | InputType::Email | InputType::Password | InputType::Date - | InputType::Month | InputType::Week | InputType::Time - | InputType::DatetimeLocal | InputType::Number - => true, - _ => false + InputType::Text | + InputType::Search | + InputType::Url | + InputType::Tel | + InputType::Email | + InputType::Password | + InputType::Date | + InputType::Month | + InputType::Week | + InputType::Time | + InputType::DatetimeLocal | + InputType::Number => true, + _ => false, } }); @@ -1644,9 +1759,11 @@ impl Activatable for HTMLInputElement { // lazily test for > 1 submission-blocking inputs return; } - form.submit(SubmittedFrom::NotFromForm, - FormSubmitter::FormElement(&form)); - } + form.submit( + SubmittedFrom::NotFromForm, + FormSubmitter::FormElement(&form), + ); + }, } } } diff --git a/components/script/dom/htmllabelelement.rs b/components/script/dom/htmllabelelement.rs index 4e565816989..0233294e970 100644 --- a/components/script/dom/htmllabelelement.rs +++ b/components/script/dom/htmllabelelement.rs @@ -23,26 +23,33 @@ use style::attr::AttrValue; #[dom_struct] pub struct HTMLLabelElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLLabelElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLLabelElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLLabelElement { HTMLLabelElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document), + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLLabelElement> { - Node::reflect_node(Box::new(HTMLLabelElement::new_inherited(local_name, prefix, document)), - document, - HTMLLabelElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLLabelElement> { + Node::reflect_node( + Box::new(HTMLLabelElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLLabelElementBinding::Wrap, + ) } } @@ -57,33 +64,37 @@ impl Activatable for HTMLLabelElement { // https://html.spec.whatwg.org/multipage/#run-pre-click-activation-steps // https://html.spec.whatwg.org/multipage/#the-button-element:activation-behavior - fn pre_click_activation(&self) { - } + fn pre_click_activation(&self) {} // https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps - fn canceled_activation(&self) { - } + fn canceled_activation(&self) {} // https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps fn activation_behavior(&self, _event: &Event, _target: &EventTarget) { if let Some(e) = self.GetControl() { let elem = e.upcast::<Element>(); - synthetic_click_activation(elem, - false, - false, - false, - false, - ActivationSource::NotFromClick); + synthetic_click_activation( + elem, + false, + false, + false, + false, + ActivationSource::NotFromClick, + ); } } // https://html.spec.whatwg.org/multipage/#implicit-submission - fn implicit_submission(&self, _ctrl_key: bool, _shift_key: bool, _alt_key: bool, _meta_key: bool) { + fn implicit_submission( + &self, + _ctrl_key: bool, + _shift_key: bool, + _alt_key: bool, + _meta_key: bool, + ) { //FIXME: Investigate and implement implicit submission for label elements // Issue filed at https://github.com/servo/servo/issues/8263 } - - } impl HTMLLabelElementMethods for HTMLLabelElement { @@ -104,17 +115,21 @@ impl HTMLLabelElementMethods for HTMLLabelElement { return None; } - let for_attr = match self.upcast::<Element>().get_attribute(&ns!(), &local_name!("for")) { + let for_attr = match self + .upcast::<Element>() + .get_attribute(&ns!(), &local_name!("for")) + { Some(for_attr) => for_attr, None => return self.first_labelable_descendant(), }; let for_value = for_attr.value(); - document_from_node(self).get_element_by_id(for_value.as_atom()) - .and_then(DomRoot::downcast::<HTMLElement>) - .into_iter() - .filter(|e| e.is_labelable_element()) - .next() + document_from_node(self) + .get_element_by_id(for_value.as_atom()) + .and_then(DomRoot::downcast::<HTMLElement>) + .into_iter() + .filter(|e| e.is_labelable_element()) + .next() } } @@ -126,7 +141,10 @@ impl VirtualMethods for HTMLLabelElement { fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("for") => AttrValue::from_atomic(value.into()), - _ => self.super_type().unwrap().parse_plain_attribute(name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(name, value), } } @@ -153,9 +171,12 @@ impl HTMLLabelElement { impl FormControl for HTMLLabelElement { fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> { - self.GetControl().map(DomRoot::upcast::<Element>).and_then(|elem| { - elem.as_maybe_form_control().and_then(|control| control.form_owner()) - }) + self.GetControl() + .map(DomRoot::upcast::<Element>) + .and_then(|elem| { + elem.as_maybe_form_control() + .and_then(|control| control.form_owner()) + }) } fn set_form_owner(&self, _: Option<&HTMLFormElement>) { diff --git a/components/script/dom/htmllegendelement.rs b/components/script/dom/htmllegendelement.rs index 04e8636bb03..57d81f67857 100644 --- a/components/script/dom/htmllegendelement.rs +++ b/components/script/dom/htmllegendelement.rs @@ -24,10 +24,11 @@ pub struct HTMLLegendElement { } impl HTMLLegendElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) - -> HTMLLegendElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLLegendElement { HTMLLegendElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), form_owner: Default::default(), @@ -35,13 +36,18 @@ impl HTMLLegendElement { } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) - -> DomRoot<HTMLLegendElement> { - Node::reflect_node(Box::new(HTMLLegendElement::new_inherited(local_name, prefix, document)), - document, - HTMLLegendElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLLegendElement> { + Node::reflect_node( + Box::new(HTMLLegendElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLLegendElementBinding::Wrap, + ) } } @@ -55,7 +61,8 @@ impl VirtualMethods for HTMLLegendElement { s.bind_to_tree(tree_in_doc); } - self.upcast::<Element>().check_ancestors_disabled_state_for_form_control(); + self.upcast::<Element>() + .check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { @@ -63,7 +70,10 @@ impl VirtualMethods for HTMLLegendElement { let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); - if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { + if node + .ancestors() + .any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) + { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); @@ -71,7 +81,6 @@ impl VirtualMethods for HTMLLegendElement { } } - impl HTMLLegendElementMethods for HTMLLegendElement { // https://html.spec.whatwg.org/multipage/#dom-legend-form fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> { diff --git a/components/script/dom/htmllielement.rs b/components/script/dom/htmllielement.rs index 81b6c4ff6a1..c36ea5716b3 100644 --- a/components/script/dom/htmllielement.rs +++ b/components/script/dom/htmllielement.rs @@ -21,19 +21,27 @@ pub struct HTMLLIElement { } impl HTMLLIElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLLIElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLLIElement { HTMLLIElement { - htmlelement: HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLLIElement> { - Node::reflect_node(Box::new(HTMLLIElement::new_inherited(local_name, prefix, document)), - document, - HTMLLIElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLLIElement> { + Node::reflect_node( + Box::new(HTMLLIElement::new_inherited(local_name, prefix, document)), + document, + HTMLLIElementBinding::Wrap, + ) } } @@ -53,7 +61,10 @@ impl VirtualMethods for HTMLLIElement { fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("value") => AttrValue::from_i32(value.into(), 0), - _ => self.super_type().unwrap().parse_plain_attribute(name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(name, value), } } } diff --git a/components/script/dom/htmllinkelement.rs b/components/script/dom/htmllinkelement.rs index be7b2785ee9..7cb04d6f124 100644 --- a/components/script/dom/htmllinkelement.rs +++ b/components/script/dom/htmllinkelement.rs @@ -65,8 +65,12 @@ pub struct HTMLLinkElement { } impl HTMLLinkElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document, - creator: ElementCreator) -> HTMLLinkElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + creator: ElementCreator, + ) -> HTMLLinkElement { HTMLLinkElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), rel_list: Default::default(), @@ -80,13 +84,19 @@ impl HTMLLinkElement { } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document, - creator: ElementCreator) -> DomRoot<HTMLLinkElement> { - Node::reflect_node(Box::new(HTMLLinkElement::new_inherited(local_name, prefix, document, creator)), - document, - HTMLLinkElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + creator: ElementCreator, + ) -> DomRoot<HTMLLinkElement> { + Node::reflect_node( + Box::new(HTMLLinkElement::new_inherited( + local_name, prefix, document, creator, + )), + document, + HTMLLinkElementBinding::Wrap, + ) } pub fn get_request_generation_id(&self) -> RequestGenerationId { @@ -112,12 +122,14 @@ impl HTMLLinkElement { pub fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { - CSSStyleSheet::new(&window_from_node(self), - self.upcast::<Element>(), - "text/css".into(), - None, // todo handle location - None, // todo handle title - sheet) + CSSStyleSheet::new( + &window_from_node(self), + self.upcast::<Element>(), + "text/css".into(), + None, // todo handle location + None, // todo handle title + sheet, + ) }) }) } @@ -125,10 +137,9 @@ impl HTMLLinkElement { pub fn is_alternate(&self) -> bool { let rel = get_attr(self.upcast(), &local_name!("rel")); match rel { - Some(ref value) => { - value.split(HTML_SPACE_CHARACTERS) - .any(|s| s.eq_ignore_ascii_case("alternate")) - }, + Some(ref value) => value + .split(HTML_SPACE_CHARACTERS) + .any(|s| s.eq_ignore_ascii_case("alternate")), None => false, } } @@ -144,10 +155,9 @@ fn get_attr(element: &Element, local_name: &LocalName) -> Option<String> { fn string_is_stylesheet(value: &Option<String>) -> bool { match *value { - Some(ref value) => { - value.split(HTML_SPACE_CHARACTERS) - .any(|s| s.eq_ignore_ascii_case("stylesheet")) - }, + Some(ref value) => value + .split(HTML_SPACE_CHARACTERS) + .any(|s| s.eq_ignore_ascii_case("stylesheet")), None => false, } } @@ -157,10 +167,9 @@ fn string_is_stylesheet(value: &Option<String>) -> bool { /// <https://html.spec.whatwg.org/multipage/#rel-icon> fn is_favicon(value: &Option<String>) -> bool { match *value { - Some(ref value) => { - value.split(HTML_SPACE_CHARACTERS) - .any(|s| s.eq_ignore_ascii_case("icon") || s.eq_ignore_ascii_case("apple-touch-icon")) - }, + Some(ref value) => value + .split(HTML_SPACE_CHARACTERS) + .any(|s| s.eq_ignore_ascii_case("icon") || s.eq_ignore_ascii_case("apple-touch-icon")), None => false, } } @@ -189,7 +198,11 @@ impl VirtualMethods for HTMLLinkElement { &local_name!("sizes") => { if is_favicon(&rel) { if let Some(ref href) = get_attr(self.upcast(), &local_name!("href")) { - self.handle_favicon_url(rel.as_ref().unwrap(), href, &Some(attr.value().to_string())); + self.handle_favicon_url( + rel.as_ref().unwrap(), + href, + &Some(attr.value().to_string()), + ); } } }, @@ -200,7 +213,10 @@ impl VirtualMethods for HTMLLinkElement { fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()), - _ => self.super_type().unwrap().parse_plain_attribute(name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(name, value), } } @@ -219,11 +235,11 @@ impl VirtualMethods for HTMLLinkElement { match href { Some(ref href) if string_is_stylesheet(&rel) => { self.handle_stylesheet_url(href); - } + }, Some(ref href) if is_favicon(&rel) => { self.handle_favicon_url(rel.as_ref().unwrap(), href, &sizes); - } - _ => {} + }, + _ => {}, } } } @@ -239,7 +255,6 @@ impl VirtualMethods for HTMLLinkElement { } } - impl HTMLLinkElement { /// <https://html.spec.whatwg.org/multipage/#concept-link-obtain> fn handle_stylesheet_url(&self, href: &str) { @@ -259,7 +274,7 @@ impl HTMLLinkElement { Err(e) => { debug!("Parsing url {} failed: {}", href, e); return; - } + }, }; let element = self.upcast::<Element>(); @@ -298,14 +313,18 @@ impl HTMLLinkElement { None => "", }; - self.request_generation_id.set(self.request_generation_id.get().increment()); + self.request_generation_id + .set(self.request_generation_id.get().increment()); // TODO: #8085 - Don't load external stylesheets if the node's mq // doesn't match. let loader = StylesheetLoader::for_element(self.upcast()); - loader.load(StylesheetContextSource::LinkElement { - media: Some(media), - }, link_url, cors_setting, integrity_metadata.to_owned()); + loader.load( + StylesheetContextSource::LinkElement { media: Some(media) }, + link_url, + cors_setting, + integrity_metadata.to_owned(), + ); } fn handle_favicon_url(&self, _rel: &str, href: &str, _sizes: &Option<String>) { @@ -317,9 +336,8 @@ impl HTMLLinkElement { let msg = EmbedderMsg::NewFavicon(url.clone()); window.send_to_embedder(msg); } - - } - Err(e) => debug!("Parsing url {} failed: {}", href, e) + }, + Err(e) => debug!("Parsing url {} failed: {}", href, e), } } } @@ -351,7 +369,7 @@ impl StylesheetOwner for HTMLLinkElement { fn referrer_policy(&self) -> Option<ReferrerPolicy> { if self.RelList().Contains("noreferrer".into()) { - return Some(ReferrerPolicy::NoReferrer) + return Some(ReferrerPolicy::NoReferrer); } None @@ -376,7 +394,8 @@ impl HTMLLinkElementMethods for HTMLLinkElement { // https://html.spec.whatwg.org/multipage/#dom-link-rel fn SetRel(&self, rel: DOMString) { - self.upcast::<Element>().set_tokenlist_attribute(&local_name!("rel"), rel); + self.upcast::<Element>() + .set_tokenlist_attribute(&local_name!("rel"), rel); } // https://html.spec.whatwg.org/multipage/#dom-link-media @@ -405,7 +424,8 @@ impl HTMLLinkElementMethods for HTMLLinkElement { // https://html.spec.whatwg.org/multipage/#dom-link-rellist fn RelList(&self) -> DomRoot<DOMTokenList> { - self.rel_list.or_init(|| DOMTokenList::new(self.upcast(), &local_name!("rel"))) + self.rel_list + .or_init(|| DOMTokenList::new(self.upcast(), &local_name!("rel"))) } // https://html.spec.whatwg.org/multipage/#dom-link-charset diff --git a/components/script/dom/htmlmapelement.rs b/components/script/dom/htmlmapelement.rs index 0648c2b3c7b..2ccc78df0a9 100644 --- a/components/script/dom/htmlmapelement.rs +++ b/components/script/dom/htmlmapelement.rs @@ -14,30 +14,37 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLMapElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLMapElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLMapElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLMapElement { HTMLMapElement { - htmlelement: HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLMapElement> { - Node::reflect_node(Box::new(HTMLMapElement::new_inherited(local_name, prefix, document)), - document, - HTMLMapElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLMapElement> { + Node::reflect_node( + Box::new(HTMLMapElement::new_inherited(local_name, prefix, document)), + document, + HTMLMapElementBinding::Wrap, + ) } pub fn get_area_elements(&self) -> Vec<DomRoot<HTMLAreaElement>> { self.upcast::<Node>() .traverse_preorder() - .filter_map(DomRoot::downcast::<HTMLAreaElement>).collect() + .filter_map(DomRoot::downcast::<HTMLAreaElement>) + .collect() } } diff --git a/components/script/dom/htmlmediaelement.rs b/components/script/dom/htmlmediaelement.rs index 83ad930337c..ad2a487a16f 100644 --- a/components/script/dom/htmlmediaelement.rs +++ b/components/script/dom/htmlmediaelement.rs @@ -106,11 +106,7 @@ enum ReadyState { } impl HTMLMediaElement { - pub fn new_inherited( - tag_name: LocalName, - prefix: Option<Prefix>, - document: &Document, - ) -> Self { + pub fn new_inherited(tag_name: LocalName, prefix: Option<Prefix>, document: &Document) -> Self { Self { htmlelement: HTMLElement::new_inherited(tag_name, prefix, document), network_state: Cell::new(NetworkState::Empty), @@ -133,9 +129,7 @@ impl HTMLMediaElement { match self.upcast::<Node>().type_id() { NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLMediaElement(media_type_id), - )) => { - media_type_id - }, + )) => media_type_id, _ => unreachable!(), } } @@ -163,7 +157,11 @@ impl HTMLMediaElement { // FIXME(nox): Reject promise if not allowed to play. // Step 2. - if self.error.get().map_or(false, |e| e.Code() == MEDIA_ERR_SRC_NOT_SUPPORTED) { + if self + .error + .get() + .map_or(false, |e| e.Code() == MEDIA_ERR_SRC_NOT_SUPPORTED) + { promise.reject_error(Error::NotSupported); return; } @@ -200,24 +198,20 @@ impl HTMLMediaElement { ReadyState::HaveNothing | ReadyState::HaveMetadata | ReadyState::HaveCurrentData => { - task_source.queue_simple_event( - self.upcast(), - atom!("waiting"), - &window, - ); + task_source.queue_simple_event(self.upcast(), atom!("waiting"), &window); }, - ReadyState::HaveFutureData | - ReadyState::HaveEnoughData => { + ReadyState::HaveFutureData | ReadyState::HaveEnoughData => { self.notify_about_playing(); - } + }, } } else if state == ReadyState::HaveFutureData || state == ReadyState::HaveEnoughData { // Step 7. self.take_pending_play_promises(Ok(())); let this = Trusted::new(self); let generation_id = self.generation_id.get(); - task_source.queue( - task!(resolve_pending_play_promises: move || { + task_source + .queue( + task!(resolve_pending_play_promises: move || { let this = this.root(); if generation_id != this.generation_id.get() { return; @@ -225,8 +219,8 @@ impl HTMLMediaElement { this.fulfill_in_flight_play_promises(|| ()); }), - window.upcast(), - ).unwrap(); + window.upcast(), + ).unwrap(); } // Step 8. @@ -330,11 +324,7 @@ impl HTMLMediaElement { // Step 1. match (old_ready_state, ready_state) { (ReadyState::HaveNothing, ReadyState::HaveMetadata) => { - task_source.queue_simple_event( - self.upcast(), - atom!("loadedmetadata"), - &window, - ); + task_source.queue_simple_event(self.upcast(), atom!("loadedmetadata"), &window); // No other steps are applicable in this case. return; @@ -369,12 +359,10 @@ impl HTMLMediaElement { _ => (), } - if old_ready_state <= ReadyState::HaveCurrentData && ready_state >= ReadyState::HaveFutureData { - task_source.queue_simple_event( - self.upcast(), - atom!("canplay"), - &window, - ); + if old_ready_state <= ReadyState::HaveCurrentData && + ready_state >= ReadyState::HaveFutureData + { + task_source.queue_simple_event(self.upcast(), atom!("canplay"), &window); if !self.Paused() { self.notify_about_playing(); @@ -386,18 +374,12 @@ impl HTMLMediaElement { // FIXME(nox): I have no idea what this TODO is about. // FIXME(nox): Review this block. - if self.autoplaying.get() && - self.Paused() && - self.Autoplay() { + if self.autoplaying.get() && self.Paused() && self.Autoplay() { // Step 1 self.paused.set(false); // TODO step 2: show poster // Step 3 - task_source.queue_simple_event( - self.upcast(), - atom!("play"), - &window, - ); + task_source.queue_simple_event(self.upcast(), atom!("play"), &window); // Step 4 self.notify_about_playing(); // Step 5 @@ -406,11 +388,7 @@ impl HTMLMediaElement { // FIXME(nox): According to the spec, this should come *before* the // "play" event. - task_source.queue_simple_event( - self.upcast(), - atom!("canplaythrough"), - &window, - ); + task_source.queue_simple_event(self.upcast(), atom!("canplaythrough"), &window); } } @@ -435,7 +413,7 @@ impl HTMLMediaElement { let task = MediaElementMicrotask::ResourceSelectionTask { elem: DomRoot::from_ref(self), generation_id: self.generation_id.get(), - base_url: doc.base_url() + base_url: doc.base_url(), }; // FIXME(nox): This will later call the resource_selection_algorith_sync @@ -460,10 +438,14 @@ impl HTMLMediaElement { if media.src_object.get().is_some() { return Some(Mode::Object); } - if let Some(attr) = media.upcast::<Element>().get_attribute(&ns!(), &local_name!("src")) { + if let Some(attr) = media + .upcast::<Element>() + .get_attribute(&ns!(), &local_name!("src")) + { return Some(Mode::Attribute(attr.Value().into())); } - let source_child_element = media.upcast::<Node>() + let source_child_element = media + .upcast::<Node>() .children() .filter_map(DomRoot::downcast::<HTMLSourceElement>) .next(); @@ -520,7 +502,7 @@ impl HTMLMediaElement { Err(_) => { self.queue_dedicated_media_source_failure_steps(); return; - } + }, }; // Step 9.attr.3. @@ -565,12 +547,14 @@ impl HTMLMediaElement { // Step 4.remote.1.3. let this = Trusted::new(self); - window.dom_manipulation_task_source().queue( - task!(set_media_delay_load_event_flag_to_false: move || { + window + .dom_manipulation_task_source() + .queue( + task!(set_media_delay_load_event_flag_to_false: move || { this.root().delay_load_event(false); }), - window.upcast(), - ).unwrap(); + window.upcast(), + ).unwrap(); // Steps 4.remote.1.4. // FIXME(nox): Somehow we should wait for the task from previous @@ -599,7 +583,7 @@ impl HTMLMediaElement { pipeline_id: Some(self.global().pipeline_id()), referrer_url: Some(document.url()), referrer_policy: document.get_referrer_policy(), - .. RequestInit::default() + ..RequestInit::default() }; let context = Arc::new(Mutex::new(HTMLMediaElementContext::new(self))); @@ -608,12 +592,17 @@ impl HTMLMediaElement { let listener = NetworkListener { context: context, task_source: window.networking_task_source(), - canceller: Some(window.task_canceller(TaskSourceName::Networking)) + canceller: Some(window.task_canceller(TaskSourceName::Networking)), }; - ROUTER.add_route(action_receiver.to_opaque(), Box::new(move |message| { - listener.notify_fetch(message.to().unwrap()); - })); - document.loader_mut().fetch_async_background(request, action_sender); + ROUTER.add_route( + action_receiver.to_opaque(), + Box::new(move |message| { + listener.notify_fetch(message.to().unwrap()); + }), + ); + document + .loader_mut() + .fetch_async_background(request, action_sender); }, Resource::Object => { // FIXME(nox): Actually do something with the object. @@ -753,7 +742,9 @@ impl HTMLMediaElement { /// Appends a promise to the list of pending play promises. #[allow(unrooted_must_root)] fn push_pending_play_promise(&self, promise: &Rc<Promise>) { - self.pending_play_promises.borrow_mut().push(promise.clone()); + self.pending_play_promises + .borrow_mut() + .push(promise.clone()); } /// Takes the pending play promises. @@ -768,14 +759,11 @@ impl HTMLMediaElement { /// which were taken and moved to the in-flight queue. #[allow(unrooted_must_root)] fn take_pending_play_promises(&self, result: ErrorResult) { - let pending_play_promises = mem::replace( - &mut *self.pending_play_promises.borrow_mut(), - vec![], - ); - self.in_flight_play_promises_queue.borrow_mut().push_back(( - pending_play_promises.into(), - result, - )); + let pending_play_promises = + mem::replace(&mut *self.pending_play_promises.borrow_mut(), vec![]); + self.in_flight_play_promises_queue + .borrow_mut() + .push_back((pending_play_promises.into(), result)); } /// Fulfills the next in-flight play promises queue after running a closure. @@ -791,7 +779,8 @@ impl HTMLMediaElement { where F: FnOnce(), { - let (promises, result) = self.in_flight_play_promises_queue + let (promises, result) = self + .in_flight_play_promises_queue .borrow_mut() .pop_front() .expect("there should be at least one list of in flight play promises"); @@ -870,11 +859,10 @@ impl HTMLMediaElementMethods for HTMLMediaElement { // https://html.spec.whatwg.org/multipage/#dom-navigator-canplaytype fn CanPlayType(&self, type_: DOMString) -> CanPlayTypeResult { match type_.parse::<Mime>() { - Ok(Mime(TopLevel::Application, SubLevel::OctetStream, _)) | - Err(_) => { + Ok(Mime(TopLevel::Application, SubLevel::OctetStream, _)) | Err(_) => { CanPlayTypeResult::_empty }, - _ => CanPlayTypeResult::Maybe + _ => CanPlayTypeResult::Maybe, } } @@ -921,7 +909,7 @@ impl VirtualMethods for HTMLMediaElement { if mutation.new_value(attr).is_some() { self.media_element_load_algorithm(); } - } + }, _ => (), }; } @@ -932,7 +920,7 @@ impl VirtualMethods for HTMLMediaElement { if context.tree_in_doc { let task = MediaElementMicrotask::PauseIfNotInDocumentTask { - elem: DomRoot::from_ref(self) + elem: DomRoot::from_ref(self), }; ScriptThread::await_stable_state(Microtask::MediaElement(task)); } @@ -948,13 +936,17 @@ pub enum MediaElementMicrotask { }, PauseIfNotInDocumentTask { elem: DomRoot<HTMLMediaElement>, - } + }, } impl MicrotaskRunnable for MediaElementMicrotask { fn handler(&self) { match self { - &MediaElementMicrotask::ResourceSelectionTask { ref elem, generation_id, ref base_url } => { + &MediaElementMicrotask::ResourceSelectionTask { + ref elem, + generation_id, + ref base_url, + } => { if generation_id == elem.generation_id.get() { elem.resource_selection_algorithm_sync(base_url.clone()); } @@ -997,14 +989,14 @@ impl FetchResponseListener for HTMLMediaElementContext { fn process_request_eof(&mut self) {} fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) { - self.metadata = metadata.ok().map(|m| { - match m { - FetchMetadata::Unfiltered(m) => m, - FetchMetadata::Filtered { unsafe_, .. } => unsafe_ - } + self.metadata = metadata.ok().map(|m| match m { + FetchMetadata::Unfiltered(m) => m, + FetchMetadata::Filtered { unsafe_, .. } => unsafe_, }); - let status_is_ok = self.metadata.as_ref() + let status_is_ok = self + .metadata + .as_ref() .and_then(|m| m.status.as_ref()) .map_or(true, |s| s.0 >= 200 && s.0 < 300); @@ -1013,7 +1005,9 @@ impl FetchResponseListener for HTMLMediaElementContext { // Ensure that the element doesn't receive any further notifications // of the aborted fetch. self.ignore_response = true; - self.elem.root().queue_dedicated_media_source_failure_steps(); + self.elem + .root() + .queue_dedicated_media_source_failure_steps(); } } @@ -1074,8 +1068,10 @@ impl FetchResponseListener for HTMLMediaElementContext { // => "If the connection is interrupted after some media data has been received..." else if elem.ready_state.get() != ReadyState::HaveNothing { // Step 2 - elem.error.set(Some(&*MediaError::new(&*window_from_node(&*elem), - MEDIA_ERR_NETWORK))); + elem.error.set(Some(&*MediaError::new( + &*window_from_node(&*elem), + MEDIA_ERR_NETWORK, + ))); // Step 3 elem.network_state.set(NetworkState::Idle); diff --git a/components/script/dom/htmlmetaelement.rs b/components/script/dom/htmlmetaelement.rs index bbfdb228b33..94408954d5c 100644 --- a/components/script/dom/htmlmetaelement.rs +++ b/components/script/dom/htmlmetaelement.rs @@ -37,9 +37,11 @@ pub struct HTMLMetaElement { } impl HTMLMetaElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLMetaElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLMetaElement { HTMLMetaElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), stylesheet: DomRefCell::new(None), @@ -48,12 +50,16 @@ impl HTMLMetaElement { } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLMetaElement> { - Node::reflect_node(Box::new(HTMLMetaElement::new_inherited(local_name, prefix, document)), - document, - HTMLMetaElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLMetaElement> { + Node::reflect_node( + Box::new(HTMLMetaElement::new_inherited(local_name, prefix, document)), + document, + HTMLMetaElementBinding::Wrap, + ) } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { @@ -63,12 +69,14 @@ impl HTMLMetaElement { pub fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { - CSSStyleSheet::new(&window_from_node(self), - self.upcast::<Element>(), - "text/css".into(), - None, // todo handle location - None, // todo handle title - sheet) + CSSStyleSheet::new( + &window_from_node(self), + self.upcast::<Element>(), + "text/css".into(), + None, // todo handle location + None, // todo handle title + sheet, + ) }) }) } @@ -90,7 +98,11 @@ impl HTMLMetaElement { } fn apply_viewport(&self) { - if !PREFS.get("layout.viewport.enabled").as_boolean().unwrap_or(false) { + if !PREFS + .get("layout.viewport.enabled") + .as_boolean() + .unwrap_or(false) + { return; } let element = self.upcast::<Element>(); @@ -176,7 +188,10 @@ impl VirtualMethods for HTMLMetaElement { fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("name") => AttrValue::from_atomic(value.into()), - _ => self.super_type().unwrap().parse_plain_attribute(name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(name, value), } } diff --git a/components/script/dom/htmlmeterelement.rs b/components/script/dom/htmlmeterelement.rs index eee3c92b657..31d50500fe0 100644 --- a/components/script/dom/htmlmeterelement.rs +++ b/components/script/dom/htmlmeterelement.rs @@ -14,25 +14,33 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLMeterElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLMeterElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLMeterElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLMeterElement { HTMLMeterElement { - htmlelement: HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLMeterElement> { - Node::reflect_node(Box::new(HTMLMeterElement::new_inherited(local_name, prefix, document)), - document, - HTMLMeterElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLMeterElement> { + Node::reflect_node( + Box::new(HTMLMeterElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLMeterElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlmodelement.rs b/components/script/dom/htmlmodelement.rs index e749bea706f..ac459681b10 100644 --- a/components/script/dom/htmlmodelement.rs +++ b/components/script/dom/htmlmodelement.rs @@ -12,25 +12,30 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLModElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLModElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLModElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLModElement { HTMLModElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLModElement> { - Node::reflect_node(Box::new(HTMLModElement::new_inherited(local_name, prefix, document)), - document, - HTMLModElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLModElement> { + Node::reflect_node( + Box::new(HTMLModElement::new_inherited(local_name, prefix, document)), + document, + HTMLModElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlobjectelement.rs b/components/script/dom/htmlobjectelement.rs index d78e102d1da..439a5c69f2d 100755 --- a/components/script/dom/htmlobjectelement.rs +++ b/components/script/dom/htmlobjectelement.rs @@ -32,24 +32,31 @@ pub struct HTMLObjectElement { } impl HTMLObjectElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLObjectElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLObjectElement { HTMLObjectElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document), + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), image: DomRefCell::new(None), form_owner: Default::default(), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLObjectElement> { - Node::reflect_node(Box::new(HTMLObjectElement::new_inherited(local_name, prefix, document)), - document, - HTMLObjectElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLObjectElement> { + Node::reflect_node( + Box::new(HTMLObjectElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLObjectElementBinding::Wrap, + ) } } @@ -64,12 +71,14 @@ impl<'a> ProcessDataURL for &'a HTMLObjectElement { let elem = self.upcast::<Element>(); // TODO: support other values - match (elem.get_attribute(&ns!(), &local_name!("type")), - elem.get_attribute(&ns!(), &local_name!("data"))) { + match ( + elem.get_attribute(&ns!(), &local_name!("type")), + elem.get_attribute(&ns!(), &local_name!("data")), + ) { (None, Some(_uri)) => { // TODO(gw): Prefetch the image here. - } - _ => { } + }, + _ => {}, } } } diff --git a/components/script/dom/htmlolistelement.rs b/components/script/dom/htmlolistelement.rs index 8de9a8595e1..c79e824dd8f 100644 --- a/components/script/dom/htmlolistelement.rs +++ b/components/script/dom/htmlolistelement.rs @@ -16,20 +16,28 @@ pub struct HTMLOListElement { } impl HTMLOListElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLOListElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLOListElement { HTMLOListElement { - htmlelement: HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLOListElement> { - Node::reflect_node(Box::new(HTMLOListElement::new_inherited(local_name, prefix, document)), - document, - HTMLOListElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLOListElement> { + Node::reflect_node( + Box::new(HTMLOListElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLOListElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmloptgroupelement.rs b/components/script/dom/htmloptgroupelement.rs index 8413b464407..f1bf1b10ca0 100644 --- a/components/script/dom/htmloptgroupelement.rs +++ b/components/script/dom/htmloptgroupelement.rs @@ -19,27 +19,38 @@ use style::element_state::ElementState; #[dom_struct] pub struct HTMLOptGroupElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLOptGroupElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLOptGroupElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLOptGroupElement { HTMLOptGroupElement { - htmlelement: - HTMLElement::new_inherited_with_state(ElementState::IN_ENABLED_STATE, - local_name, prefix, document) + htmlelement: HTMLElement::new_inherited_with_state( + ElementState::IN_ENABLED_STATE, + local_name, + prefix, + document, + ), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLOptGroupElement> { - Node::reflect_node(Box::new(HTMLOptGroupElement::new_inherited(local_name, prefix, document)), - document, - HTMLOptGroupElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLOptGroupElement> { + Node::reflect_node( + Box::new(HTMLOptGroupElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLOptGroupElementBinding::Wrap, + ) } } @@ -71,9 +82,11 @@ impl VirtualMethods for HTMLOptGroupElement { let el = self.upcast::<Element>(); el.set_disabled_state(disabled_state); el.set_enabled_state(!disabled_state); - let options = el.upcast::<Node>().children().filter(|child| { - child.is::<HTMLOptionElement>() - }).map(|child| DomRoot::from_ref(child.downcast::<HTMLOptionElement>().unwrap())); + let options = el + .upcast::<Node>() + .children() + .filter(|child| child.is::<HTMLOptionElement>()) + .map(|child| DomRoot::from_ref(child.downcast::<HTMLOptionElement>().unwrap())); if disabled_state { for option in options { let el = option.upcast::<Element>(); diff --git a/components/script/dom/htmloptionelement.rs b/components/script/dom/htmloptionelement.rs index ff59c4b0e24..2521ec1d94c 100644 --- a/components/script/dom/htmloptionelement.rs +++ b/components/script/dom/htmloptionelement.rs @@ -40,25 +40,36 @@ pub struct HTMLOptionElement { } impl HTMLOptionElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLOptionElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLOptionElement { HTMLOptionElement { - htmlelement: - HTMLElement::new_inherited_with_state(ElementState::IN_ENABLED_STATE, - local_name, prefix, document), + htmlelement: HTMLElement::new_inherited_with_state( + ElementState::IN_ENABLED_STATE, + local_name, + prefix, + document, + ), selectedness: Cell::new(false), dirtiness: Cell::new(false), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLOptionElement> { - Node::reflect_node(Box::new(HTMLOptionElement::new_inherited(local_name, prefix, document)), - document, - HTMLOptionElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLOptionElement> { + Node::reflect_node( + Box::new(HTMLOptionElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLOptionElementBinding::Wrap, + ) } pub fn set_selectedness(&self, selected: bool) { @@ -70,9 +81,12 @@ impl HTMLOptionElement { } fn pick_if_selected_and_reset(&self) { - if let Some(select) = self.upcast::<Node>().ancestors() - .filter_map(DomRoot::downcast::<HTMLSelectElement>) - .next() { + if let Some(select) = self + .upcast::<Node>() + .ancestors() + .filter_map(DomRoot::downcast::<HTMLSelectElement>) + .next() + { if self.Selected() { select.pick_option(self); } @@ -83,7 +97,8 @@ impl HTMLOptionElement { // FIXME(ajeffrey): Provide a way of buffering DOMStrings other than using Strings fn collect_text(element: &Element, value: &mut String) { - let svg_script = *element.namespace() == ns!(svg) && element.local_name() == &local_name!("script"); + let svg_script = + *element.namespace() == ns!(svg) && element.local_name() == &local_name!("script"); let html_script = element.is::<HTMLScriptElement>(); if svg_script || html_script { return; @@ -120,13 +135,13 @@ impl HTMLOptionElementMethods for HTMLOptionElement { // https://html.spec.whatwg.org/multipage/#dom-option-form fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> { - let parent = self.upcast::<Node>().GetParentNode().and_then(|p| + let parent = self.upcast::<Node>().GetParentNode().and_then(|p| { if p.is::<HTMLOptGroupElement>() { p.upcast::<Node>().GetParentNode() } else { Some(p) } - ); + }); parent.and_then(|p| p.downcast::<HTMLSelectElement>().and_then(|s| s.GetForm())) } @@ -197,7 +212,7 @@ impl VirtualMethods for HTMLOptionElement { el.set_disabled_state(false); el.set_enabled_state(true); el.check_parent_disabled_state_for_option(); - } + }, } }, &local_name!("selected") => { @@ -225,7 +240,8 @@ impl VirtualMethods for HTMLOptionElement { s.bind_to_tree(tree_in_doc); } - self.upcast::<Element>().check_parent_disabled_state_for_option(); + self.upcast::<Element>() + .check_parent_disabled_state_for_option(); self.pick_if_selected_and_reset(); } @@ -233,9 +249,12 @@ impl VirtualMethods for HTMLOptionElement { fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); - if let Some(select) = context.parent.inclusive_ancestors() - .filter_map(DomRoot::downcast::<HTMLSelectElement>) - .next() { + if let Some(select) = context + .parent + .inclusive_ancestors() + .filter_map(DomRoot::downcast::<HTMLSelectElement>) + .next() + { select.ask_for_reset(); } diff --git a/components/script/dom/htmloptionscollection.rs b/components/script/dom/htmloptionscollection.rs index 98c0440d43a..1d296cccda8 100644 --- a/components/script/dom/htmloptionscollection.rs +++ b/components/script/dom/htmloptionscollection.rs @@ -28,18 +28,25 @@ pub struct HTMLOptionsCollection { } impl HTMLOptionsCollection { - fn new_inherited(select: &HTMLSelectElement, filter: Box<CollectionFilter + 'static>) -> HTMLOptionsCollection { + fn new_inherited( + select: &HTMLSelectElement, + filter: Box<CollectionFilter + 'static>, + ) -> HTMLOptionsCollection { HTMLOptionsCollection { collection: HTMLCollection::new_inherited(select.upcast(), filter), } } - pub fn new(window: &Window, select: &HTMLSelectElement, filter: Box<CollectionFilter + 'static>) - -> DomRoot<HTMLOptionsCollection> - { - reflect_dom_object(Box::new(HTMLOptionsCollection::new_inherited(select, filter)), - window, - HTMLOptionsCollectionBinding::Wrap) + pub fn new( + window: &Window, + select: &HTMLSelectElement, + filter: Box<CollectionFilter + 'static>, + ) -> DomRoot<HTMLOptionsCollection> { + reflect_dom_object( + Box::new(HTMLOptionsCollection::new_inherited(select, filter)), + window, + HTMLOptionsCollectionBinding::Wrap, + ) } fn add_new_elements(&self, count: u32) -> ErrorResult { @@ -50,7 +57,7 @@ impl HTMLOptionsCollection { let element = HTMLOptionElement::new(local_name!("option"), None, &document); let node = element.upcast::<Node>(); root.AppendChild(node)?; - }; + } Ok(()) } } @@ -132,12 +139,20 @@ impl HTMLOptionsCollectionMethods for HTMLOptionsCollection { } // https://html.spec.whatwg.org/multipage/#dom-htmloptionscollection-add - fn Add(&self, element: HTMLOptionElementOrHTMLOptGroupElement, before: Option<HTMLElementOrLong>) -> ErrorResult { + fn Add( + &self, + element: HTMLOptionElementOrHTMLOptGroupElement, + before: Option<HTMLElementOrLong>, + ) -> ErrorResult { let root = self.upcast().root_node(); let node: &Node = match element { - HTMLOptionElementOrHTMLOptGroupElement::HTMLOptionElement(ref element) => element.upcast(), - HTMLOptionElementOrHTMLOptGroupElement::HTMLOptGroupElement(ref element) => element.upcast(), + HTMLOptionElementOrHTMLOptGroupElement::HTMLOptionElement(ref element) => { + element.upcast() + }, + HTMLOptionElementOrHTMLOptGroupElement::HTMLOptGroupElement(ref element) => { + element.upcast() + }, }; // Step 1 @@ -159,13 +174,12 @@ impl HTMLOptionsCollectionMethods for HTMLOptionsCollection { } // Step 4 - let reference_node = before.and_then(|before| { - match before { - HTMLElementOrLong::HTMLElement(element) => Some(DomRoot::upcast::<Node>(element)), - HTMLElementOrLong::Long(index) => { - self.upcast().IndexedGetter(index as u32).map(DomRoot::upcast::<Node>) - } - } + let reference_node = before.and_then(|before| match before { + HTMLElementOrLong::HTMLElement(element) => Some(DomRoot::upcast::<Node>(element)), + HTMLElementOrLong::Long(index) => self + .upcast() + .IndexedGetter(index as u32) + .map(DomRoot::upcast::<Node>), }); // Step 5 diff --git a/components/script/dom/htmloutputelement.rs b/components/script/dom/htmloutputelement.rs index e9706684e68..f91d09ae42d 100644 --- a/components/script/dom/htmloutputelement.rs +++ b/components/script/dom/htmloutputelement.rs @@ -25,23 +25,30 @@ pub struct HTMLOutputElement { } impl HTMLOutputElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLOutputElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLOutputElement { HTMLOutputElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document), + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), form_owner: Default::default(), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLOutputElement> { - Node::reflect_node(Box::new(HTMLOutputElement::new_inherited(local_name, prefix, document)), - document, - HTMLOutputElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLOutputElement> { + Node::reflect_node( + Box::new(HTMLOutputElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLOutputElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlparagraphelement.rs b/components/script/dom/htmlparagraphelement.rs index bcebc146daf..d2372d72ad3 100644 --- a/components/script/dom/htmlparagraphelement.rs +++ b/components/script/dom/htmlparagraphelement.rs @@ -12,25 +12,32 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLParagraphElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLParagraphElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLParagraphElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLParagraphElement { HTMLParagraphElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLParagraphElement> { - Node::reflect_node(Box::new(HTMLParagraphElement::new_inherited(local_name, prefix, document)), - document, - HTMLParagraphElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLParagraphElement> { + Node::reflect_node( + Box::new(HTMLParagraphElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLParagraphElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlparamelement.rs b/components/script/dom/htmlparamelement.rs index 3cad6ef80e5..704a9822be3 100644 --- a/components/script/dom/htmlparamelement.rs +++ b/components/script/dom/htmlparamelement.rs @@ -12,25 +12,32 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLParamElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLParamElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLParamElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLParamElement { HTMLParamElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLParamElement> { - Node::reflect_node(Box::new(HTMLParamElement::new_inherited(local_name, prefix, document)), - document, - HTMLParamElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLParamElement> { + Node::reflect_node( + Box::new(HTMLParamElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLParamElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlpictureelement.rs b/components/script/dom/htmlpictureelement.rs index cf5154a47a1..4a28220eaba 100644 --- a/components/script/dom/htmlpictureelement.rs +++ b/components/script/dom/htmlpictureelement.rs @@ -16,21 +16,28 @@ pub struct HTMLPictureElement { } impl HTMLPictureElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLPictureElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLPictureElement { HTMLPictureElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLPictureElement> { - Node::reflect_node(Box::new(HTMLPictureElement::new_inherited(local_name, prefix, document)), - document, - HTMLPictureElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLPictureElement> { + Node::reflect_node( + Box::new(HTMLPictureElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLPictureElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlpreelement.rs b/components/script/dom/htmlpreelement.rs index 5519196020d..cfbfe11564b 100644 --- a/components/script/dom/htmlpreelement.rs +++ b/components/script/dom/htmlpreelement.rs @@ -16,21 +16,26 @@ pub struct HTMLPreElement { } impl HTMLPreElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLPreElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLPreElement { HTMLPreElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLPreElement> { - Node::reflect_node(Box::new(HTMLPreElement::new_inherited(local_name, prefix, document)), - document, - HTMLPreElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLPreElement> { + Node::reflect_node( + Box::new(HTMLPreElement::new_inherited(local_name, prefix, document)), + document, + HTMLPreElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlprogresselement.rs b/components/script/dom/htmlprogresselement.rs index b8f4dbd6970..30b5ccaf519 100644 --- a/components/script/dom/htmlprogresselement.rs +++ b/components/script/dom/htmlprogresselement.rs @@ -18,22 +18,29 @@ pub struct HTMLProgressElement { } impl HTMLProgressElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLProgressElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLProgressElement { HTMLProgressElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLProgressElement> { - Node::reflect_node(Box::new(HTMLProgressElement::new_inherited(local_name, prefix, document)), - document, - HTMLProgressElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLProgressElement> { + Node::reflect_node( + Box::new(HTMLProgressElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLProgressElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlquoteelement.rs b/components/script/dom/htmlquoteelement.rs index 0d03a69848a..e1a428e60e1 100644 --- a/components/script/dom/htmlquoteelement.rs +++ b/components/script/dom/htmlquoteelement.rs @@ -16,21 +16,28 @@ pub struct HTMLQuoteElement { } impl HTMLQuoteElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLQuoteElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLQuoteElement { HTMLQuoteElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLQuoteElement> { - Node::reflect_node(Box::new(HTMLQuoteElement::new_inherited(local_name, prefix, document)), - document, - HTMLQuoteElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLQuoteElement> { + Node::reflect_node( + Box::new(HTMLQuoteElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLQuoteElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlscriptelement.rs b/components/script/dom/htmlscriptelement.rs index 8f07f1e80c8..d78a04e93e0 100644 --- a/components/script/dom/htmlscriptelement.rs +++ b/components/script/dom/htmlscriptelement.rs @@ -67,11 +67,14 @@ pub struct HTMLScriptElement { } impl HTMLScriptElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document, - creator: ElementCreator) -> HTMLScriptElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + creator: ElementCreator, + ) -> HTMLScriptElement { HTMLScriptElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document), + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), already_started: Cell::new(false), parser_inserted: Cell::new(creator.is_parser_created()), non_blocking: Cell::new(!creator.is_parser_created()), @@ -81,15 +84,22 @@ impl HTMLScriptElement { } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document, - creator: ElementCreator) -> DomRoot<HTMLScriptElement> { - Node::reflect_node(Box::new(HTMLScriptElement::new_inherited(local_name, prefix, document, creator)), - document, - HTMLScriptElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + creator: ElementCreator, + ) -> DomRoot<HTMLScriptElement> { + Node::reflect_node( + Box::new(HTMLScriptElement::new_inherited( + local_name, prefix, document, creator, + )), + document, + HTMLScriptElementBinding::Wrap, + ) } } - /// Supported script types as defined by /// <https://html.spec.whatwg.org/multipage/#javascript-mime-type>. static SCRIPT_JS_MIMES: StaticStringVec = &[ @@ -154,7 +164,7 @@ struct ScriptContext { /// The initial URL requested. url: ServoUrl, /// Indicates whether the request failed, and why - status: Result<(), NetworkError> + status: Result<(), NetworkError>, } impl FetchResponseListener for ScriptContext { @@ -162,24 +172,29 @@ impl FetchResponseListener for ScriptContext { fn process_request_eof(&mut self) {} // TODO(KiChjang): Perhaps add custom steps to perform fetch here? - fn process_response(&mut self, - metadata: Result<FetchMetadata, NetworkError>) { + fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) { self.metadata = metadata.ok().map(|meta| match meta { FetchMetadata::Unfiltered(m) => m, - FetchMetadata::Filtered { unsafe_, .. } => unsafe_ + FetchMetadata::Filtered { unsafe_, .. } => unsafe_, }); - let status_code = self.metadata.as_ref().and_then(|m| { - match m.status { + let status_code = self + .metadata + .as_ref() + .and_then(|m| match m.status { Some((c, _)) => Some(c), _ => None, - } - }).unwrap_or(0); + }).unwrap_or(0); self.status = match status_code { - 0 => Err(NetworkError::Internal("No http status code received".to_owned())), + 0 => Err(NetworkError::Internal( + "No http status code received".to_owned(), + )), 200...299 => Ok(()), // HTTP ok status codes - _ => Err(NetworkError::Internal(format!("HTTP error code {}", status_code))) + _ => Err(NetworkError::Internal(format!( + "HTTP error code {}", + status_code + ))), }; } @@ -197,7 +212,8 @@ impl FetchResponseListener for ScriptContext { let metadata = self.metadata.take().unwrap(); // Step 6. - let encoding = metadata.charset + let encoding = metadata + .charset .and_then(|encoding| Encoding::for_label(encoding.as_bytes())) .unwrap_or(self.character_encoding); @@ -216,7 +232,9 @@ impl FetchResponseListener for ScriptContext { ExternalScriptKind::Asap => document.asap_script_loaded(&elem, load), ExternalScriptKind::AsapInOrder => document.asap_in_order_script_loaded(&elem, load), ExternalScriptKind::Deferred => document.deferred_script_loaded(&elem, load), - ExternalScriptKind::ParsingBlocking => document.pending_parsing_blocking_script_loaded(&elem, load), + ExternalScriptKind::ParsingBlocking => { + document.pending_parsing_blocking_script_loaded(&elem, load) + }, } document.finish_load(LoadType::Script(self.url.clone())); @@ -226,12 +244,14 @@ impl FetchResponseListener for ScriptContext { impl PreInvoke for ScriptContext {} /// <https://html.spec.whatwg.org/multipage/#fetch-a-classic-script> -fn fetch_a_classic_script(script: &HTMLScriptElement, - kind: ExternalScriptKind, - url: ServoUrl, - cors_setting: Option<CorsSettings>, - integrity_metadata: String, - character_encoding: &'static Encoding) { +fn fetch_a_classic_script( + script: &HTMLScriptElement, + kind: ExternalScriptKind, + url: ServoUrl, + cors_setting: Option<CorsSettings>, + integrity_metadata: String, + character_encoding: &'static Encoding, +) { let doc = document_from_node(script); // Step 1, 2. @@ -255,7 +275,7 @@ fn fetch_a_classic_script(script: &HTMLScriptElement, referrer_url: Some(doc.url()), referrer_policy: doc.get_referrer_policy(), integrity_metadata: integrity_metadata, - .. RequestInit::default() + ..RequestInit::default() }; // TODO: Step 3, Add custom steps to perform fetch @@ -264,22 +284,25 @@ fn fetch_a_classic_script(script: &HTMLScriptElement, elem: Trusted::new(script), kind: kind, character_encoding: character_encoding, - data: vec!(), + data: vec![], metadata: None, url: url.clone(), - status: Ok(()) + status: Ok(()), })); let (action_sender, action_receiver) = ipc::channel().unwrap(); let listener = NetworkListener { context: context, task_source: doc.window().networking_task_source(), - canceller: Some(doc.window().task_canceller(TaskSourceName::Networking)) + canceller: Some(doc.window().task_canceller(TaskSourceName::Networking)), }; - ROUTER.add_route(action_receiver.to_opaque(), Box::new(move |message| { - listener.notify_fetch(message.to().unwrap()); - })); + ROUTER.add_route( + action_receiver.to_opaque(), + Box::new(move |message| { + listener.notify_fetch(message.to().unwrap()); + }), + ); doc.fetch_async(LoadType::Script(url), request, action_sender); } @@ -364,9 +387,10 @@ impl HTMLScriptElement { } // Step 14. - let encoding = element.get_attribute(&ns!(), &local_name!("charset")) - .and_then(|charset| Encoding::for_label(charset.value().as_bytes())) - .unwrap_or_else(|| doc.encoding()); + let encoding = element + .get_attribute(&ns!(), &local_name!("charset")) + .and_then(|charset| Encoding::for_label(charset.value().as_bytes())) + .unwrap_or_else(|| doc.encoding()); // Step 15. let cors_setting = cors_setting_for_element(element); @@ -413,27 +437,37 @@ impl HTMLScriptElement { }; // Preparation for step 23. - let kind = if element.has_attribute(&local_name!("defer")) && was_parser_inserted && !async { - // Step 23.a: classic, has src, has defer, was parser-inserted, is not async. - ExternalScriptKind::Deferred - } else if was_parser_inserted && !async { - // Step 23.c: classic, has src, was parser-inserted, is not async. - ExternalScriptKind::ParsingBlocking - } else if !async && !self.non_blocking.get() { - // Step 23.d: classic, has src, is not async, is not non-blocking. - ExternalScriptKind::AsapInOrder - } else { - // Step 23.f: classic, has src. - ExternalScriptKind::Asap - }; + let kind = + if element.has_attribute(&local_name!("defer")) && was_parser_inserted && !async { + // Step 23.a: classic, has src, has defer, was parser-inserted, is not async. + ExternalScriptKind::Deferred + } else if was_parser_inserted && !async { + // Step 23.c: classic, has src, was parser-inserted, is not async. + ExternalScriptKind::ParsingBlocking + } else if !async && !self.non_blocking.get() { + // Step 23.d: classic, has src, is not async, is not non-blocking. + ExternalScriptKind::AsapInOrder + } else { + // Step 23.f: classic, has src. + ExternalScriptKind::Asap + }; // Step 21.6. - fetch_a_classic_script(self, kind, url, cors_setting, integrity_metadata.to_owned(), encoding); + fetch_a_classic_script( + self, + kind, + url, + cors_setting, + integrity_metadata.to_owned(), + encoding, + ); // Step 23. match kind { ExternalScriptKind::Deferred => doc.add_deferred_script(self), - ExternalScriptKind::ParsingBlocking => doc.set_pending_parsing_blocking_script(self, None), + ExternalScriptKind::ParsingBlocking => { + doc.set_pending_parsing_blocking_script(self, None) + }, ExternalScriptKind::AsapInOrder => doc.push_asap_in_order_script(self), ExternalScriptKind::Asap => doc.add_asap_script(self), } @@ -444,8 +478,10 @@ impl HTMLScriptElement { // Step 23. if was_parser_inserted && - doc.get_current_parser().map_or(false, |parser| parser.script_nesting_level() <= 1) && - doc.get_script_blocking_stylesheets_count() > 0 { + doc.get_current_parser() + .map_or(false, |parser| parser.script_nesting_level() <= 1) && + doc.get_script_blocking_stylesheets_count() > 0 + { // Step 23.h: classic, has no src, was parser-inserted, is blocked on stylesheet. doc.set_pending_parsing_blocking_script(self, Some(result)); } else { @@ -461,9 +497,10 @@ impl HTMLScriptElement { } match Command::new("js-beautify") - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn() { + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + { Err(_) => { warn!("Failed to execute js-beautify. Will store unmodified script"); }, @@ -512,7 +549,7 @@ impl HTMLScriptElement { warn!("error loading script {:?}", e); self.dispatch_error_event(); return; - } + }, Ok(script) => script, }; @@ -564,28 +601,44 @@ impl HTMLScriptElement { // Steps 4-10 let window = window_from_node(self); - let line_number = if script.external { 1 } else { self.line_number as u32 }; + let line_number = if script.external { + 1 + } else { + self.line_number as u32 + }; rooted!(in(window.get_cx()) let mut rval = UndefinedValue()); let global = window.upcast::<GlobalScope>(); global.evaluate_script_on_global_with_result( - &script.text, script.url.as_str(), rval.handle_mut(), line_number); + &script.text, + script.url.as_str(), + rval.handle_mut(), + line_number, + ); } pub fn queue_error_event(&self) { let window = window_from_node(self); - window.dom_manipulation_task_source().queue_simple_event(self.upcast(), atom!("error"), &window); + window.dom_manipulation_task_source().queue_simple_event( + self.upcast(), + atom!("error"), + &window, + ); } pub fn dispatch_load_event(&self) { - self.dispatch_event(atom!("load"), - EventBubbles::DoesNotBubble, - EventCancelable::NotCancelable); + self.dispatch_event( + atom!("load"), + EventBubbles::DoesNotBubble, + EventCancelable::NotCancelable, + ); } pub fn dispatch_error_event(&self) { - self.dispatch_event(atom!("error"), - EventBubbles::DoesNotBubble, - EventCancelable::NotCancelable); + self.dispatch_event( + atom!("error"), + EventBubbles::DoesNotBubble, + EventCancelable::NotCancelable, + ); } pub fn is_javascript(&self) -> bool { @@ -599,7 +652,8 @@ impl HTMLScriptElement { }, Some(s) => { debug!("script type={}", &**s); - SCRIPT_JS_MIMES.contains(&s.to_ascii_lowercase().trim_matches(HTML_SPACE_CHARACTERS)) + SCRIPT_JS_MIMES + .contains(&s.to_ascii_lowercase().trim_matches(HTML_SPACE_CHARACTERS)) }, None => { debug!("no script type"); @@ -618,11 +672,11 @@ impl HTMLScriptElement { None => { debug!("no script type or language, inferring js"); true - } + }, }; // https://github.com/rust-lang/rust/issues/21114 is_js - } + }, }; // https://github.com/rust-lang/rust/issues/21114 is_js @@ -636,10 +690,12 @@ impl HTMLScriptElement { self.already_started.set(already_started); } - fn dispatch_event(&self, - type_: Atom, - bubbles: EventBubbles, - cancelable: EventCancelable) -> EventStatus { + fn dispatch_event( + &self, + type_: Atom, + bubbles: EventBubbles, + cancelable: EventCancelable, + ) -> EventStatus { let window = window_from_node(self); let event = Event::new(window.upcast(), type_, bubbles, cancelable); event.fire(self.upcast()) @@ -684,15 +740,21 @@ impl VirtualMethods for HTMLScriptElement { } } - fn cloning_steps(&self, copy: &Node, maybe_doc: Option<&Document>, - clone_children: CloneChildrenFlag) { + fn cloning_steps( + &self, + copy: &Node, + maybe_doc: Option<&Document>, + clone_children: CloneChildrenFlag, + ) { if let Some(ref s) = self.super_type() { s.cloning_steps(copy, maybe_doc, clone_children); } // https://html.spec.whatwg.org/multipage/#already-started if self.already_started.get() { - copy.downcast::<HTMLScriptElement>().unwrap().set_already_started(true); + copy.downcast::<HTMLScriptElement>() + .unwrap() + .set_already_started(true); } } } @@ -716,13 +778,16 @@ impl HTMLScriptElementMethods for HTMLScriptElement { // https://html.spec.whatwg.org/multipage/#dom-script-async fn Async(&self) -> bool { - self.non_blocking.get() || self.upcast::<Element>().has_attribute(&local_name!("async")) + self.non_blocking.get() || self + .upcast::<Element>() + .has_attribute(&local_name!("async")) } // https://html.spec.whatwg.org/multipage/#dom-script-async fn SetAsync(&self, value: bool) { self.non_blocking.set(false); - self.upcast::<Element>().set_bool_attribute(&local_name!("async"), value); + self.upcast::<Element>() + .set_bool_attribute(&local_name!("async"), value); } // https://html.spec.whatwg.org/multipage/#dom-script-defer diff --git a/components/script/dom/htmlselectelement.rs b/components/script/dom/htmlselectelement.rs index 401d29c6cb8..4fec663a356 100755 --- a/components/script/dom/htmlselectelement.rs +++ b/components/script/dom/htmlselectelement.rs @@ -51,8 +51,7 @@ impl CollectionFilter for OptionsFilter { } match node.GetParentNode() { - Some(optgroup) => - optgroup.is::<HTMLOptGroupElement>() && root.is_parent_of(&optgroup), + Some(optgroup) => optgroup.is::<HTMLOptGroupElement>() && root.is_parent_of(&optgroup), None => false, } } @@ -68,41 +67,50 @@ pub struct HTMLSelectElement { static DEFAULT_SELECT_SIZE: u32 = 0; impl HTMLSelectElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLSelectElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLSelectElement { HTMLSelectElement { - htmlelement: - HTMLElement::new_inherited_with_state(ElementState::IN_ENABLED_STATE, - local_name, prefix, document), - options: Default::default(), - form_owner: Default::default(), + htmlelement: HTMLElement::new_inherited_with_state( + ElementState::IN_ENABLED_STATE, + local_name, + prefix, + document, + ), + options: Default::default(), + form_owner: Default::default(), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLSelectElement> { - Node::reflect_node(Box::new(HTMLSelectElement::new_inherited(local_name, prefix, document)), - document, - HTMLSelectElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLSelectElement> { + Node::reflect_node( + Box::new(HTMLSelectElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLSelectElementBinding::Wrap, + ) } // https://html.spec.whatwg.org/multipage/#concept-select-option-list - fn list_of_options(&self) -> impl Iterator<Item=DomRoot<HTMLOptionElement>> { - self.upcast::<Node>() - .children() - .flat_map(|node| { - if node.is::<HTMLOptionElement>() { - let node = DomRoot::downcast::<HTMLOptionElement>(node).unwrap(); - Choice3::First(iter::once(node)) - } else if node.is::<HTMLOptGroupElement>() { - Choice3::Second(node.children().filter_map(DomRoot::downcast)) - } else { - Choice3::Third(iter::empty()) - } - }) + fn list_of_options(&self) -> impl Iterator<Item = DomRoot<HTMLOptionElement>> { + self.upcast::<Node>().children().flat_map(|node| { + if node.is::<HTMLOptionElement>() { + let node = DomRoot::downcast::<HTMLOptionElement>(node).unwrap(); + Choice3::First(iter::once(node)) + } else if node.is::<HTMLOptGroupElement>() { + Choice3::Second(node.children().filter_map(DomRoot::downcast)) + } else { + Choice3::Third(iter::empty()) + } + }) } // https://html.spec.whatwg.org/multipage/#the-select-element:concept-form-reset-control @@ -155,7 +163,7 @@ impl HTMLSelectElement { data_set.push(FormDatum { ty: self.Type(), name: self.Name(), - value: FormDatumValue::String(opt.Value()) + value: FormDatumValue::String(opt.Value()), }); } } @@ -175,16 +183,16 @@ impl HTMLSelectElement { // https://html.spec.whatwg.org/multipage/#concept-select-size fn display_size(&self) -> u32 { - if self.Size() == 0 { - if self.Multiple() { - 4 - } else { - 1 - } - } else { - self.Size() - } - } + if self.Size() == 0 { + if self.Multiple() { + 4 + } else { + 1 + } + } else { + self.Size() + } + } } impl HTMLSelectElementMethods for HTMLSelectElement { @@ -196,7 +204,11 @@ impl HTMLSelectElementMethods for HTMLSelectElement { // Note: this function currently only exists for union.html. // https://html.spec.whatwg.org/multipage/#dom-select-add - fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { + fn Add( + &self, + _element: HTMLOptionElementOrHTMLOptGroupElement, + _before: Option<HTMLElementOrLong>, + ) { } // https://html.spec.whatwg.org/multipage/#dom-fe-disabled @@ -246,8 +258,7 @@ impl HTMLSelectElementMethods for HTMLSelectElement { fn Options(&self) -> DomRoot<HTMLOptionsCollection> { self.options.or_init(|| { let window = window_from_node(self); - HTMLOptionsCollection::new( - &window, self, Box::new(OptionsFilter)) + HTMLOptionsCollection::new(&window, self, Box::new(OptionsFilter)) }) } @@ -273,7 +284,9 @@ impl HTMLSelectElementMethods for HTMLSelectElement { // https://html.spec.whatwg.org/multipage/#dom-select-nameditem fn NamedItem(&self, name: DOMString) -> Option<DomRoot<HTMLOptionElement>> { - self.Options().NamedGetter(name).map_or(None, |e| DomRoot::downcast::<HTMLOptionElement>(e)) + self.Options() + .NamedGetter(name) + .map_or(None, |e| DomRoot::downcast::<HTMLOptionElement>(e)) } // https://html.spec.whatwg.org/multipage/#dom-select-remove @@ -359,7 +372,7 @@ impl VirtualMethods for HTMLSelectElement { el.set_disabled_state(false); el.set_enabled_state(true); el.check_ancestors_disabled_state_for_form_control(); - } + }, } }, &local_name!("form") => { @@ -374,7 +387,8 @@ impl VirtualMethods for HTMLSelectElement { s.bind_to_tree(tree_in_doc); } - self.upcast::<Element>().check_ancestors_disabled_state_for_form_control(); + self.upcast::<Element>() + .check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { @@ -382,7 +396,10 @@ impl VirtualMethods for HTMLSelectElement { let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); - if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { + if node + .ancestors() + .any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) + { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); @@ -392,7 +409,10 @@ impl VirtualMethods for HTMLSelectElement { fn parse_plain_attribute(&self, local_name: &LocalName, value: DOMString) -> AttrValue { match *local_name { local_name!("size") => AttrValue::from_u32(value.into(), DEFAULT_SELECT_SIZE), - _ => self.super_type().unwrap().parse_plain_attribute(local_name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(local_name, value), } } } @@ -429,7 +449,10 @@ enum Choice3<I, J, K> { } impl<I, J, K, T> Iterator for Choice3<I, J, K> - where I: Iterator<Item=T>, J: Iterator<Item=T>, K: Iterator<Item=T> +where + I: Iterator<Item = T>, + J: Iterator<Item = T>, + K: Iterator<Item = T>, { type Item = T; diff --git a/components/script/dom/htmlsourceelement.rs b/components/script/dom/htmlsourceelement.rs index 770270d3379..c33a6ba8571 100644 --- a/components/script/dom/htmlsourceelement.rs +++ b/components/script/dom/htmlsourceelement.rs @@ -18,26 +18,33 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLSourceElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLSourceElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLSourceElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLSourceElement { HTMLSourceElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLSourceElement> { - Node::reflect_node(Box::new(HTMLSourceElement::new_inherited(local_name, prefix, document)), - document, - HTMLSourceElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLSourceElement> { + Node::reflect_node( + Box::new(HTMLSourceElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLSourceElementBinding::Wrap, + ) } } @@ -86,5 +93,4 @@ impl HTMLSourceElementMethods for HTMLSourceElement { // https://html.spec.whatwg.org/multipage/#dom-source-media make_setter!(SetMedia, "media"); - } diff --git a/components/script/dom/htmlspanelement.rs b/components/script/dom/htmlspanelement.rs index 9e3448662d0..a626455c823 100644 --- a/components/script/dom/htmlspanelement.rs +++ b/components/script/dom/htmlspanelement.rs @@ -12,22 +12,30 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLSpanElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLSpanElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLSpanElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLSpanElement { HTMLSpanElement { - htmlelement: HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLSpanElement> { - Node::reflect_node(Box::new(HTMLSpanElement::new_inherited(local_name, prefix, document)), - document, - HTMLSpanElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLSpanElement> { + Node::reflect_node( + Box::new(HTMLSpanElement::new_inherited(local_name, prefix, document)), + document, + HTMLSpanElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlstyleelement.rs b/components/script/dom/htmlstyleelement.rs index bcecab9088b..cd0448fb602 100644 --- a/components/script/dom/htmlstyleelement.rs +++ b/components/script/dom/htmlstyleelement.rs @@ -42,10 +42,12 @@ pub struct HTMLStyleElement { } impl HTMLStyleElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document, - creator: ElementCreator) -> HTMLStyleElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + creator: ElementCreator, + ) -> HTMLStyleElement { HTMLStyleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), stylesheet: DomRefCell::new(None), @@ -59,13 +61,19 @@ impl HTMLStyleElement { } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document, - creator: ElementCreator) -> DomRoot<HTMLStyleElement> { - Node::reflect_node(Box::new(HTMLStyleElement::new_inherited(local_name, prefix, document, creator)), - document, - HTMLStyleElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + creator: ElementCreator, + ) -> DomRoot<HTMLStyleElement> { + Node::reflect_node( + Box::new(HTMLStyleElement::new_inherited( + local_name, prefix, document, creator, + )), + document, + HTMLStyleElementBinding::Wrap, + ) } pub fn parse_own_css(&self) { @@ -82,7 +90,9 @@ impl HTMLStyleElement { None => String::new(), }; - let data = node.GetTextContent().expect("Element.textContent must be a string"); + let data = node + .GetTextContent() + .expect("Element.textContent must be a string"); let url = window.get_url(); let css_error_reporter = window.css_error_reporter(); let context = CssParserContext::new_for_cssom( @@ -95,10 +105,8 @@ impl HTMLStyleElement { ); let shared_lock = node.owner_doc().style_shared_lock().clone(); let mut input = ParserInput::new(&mq_str); - let mq = Arc::new(shared_lock.wrap(MediaList::parse( - &context, - &mut CssParser::new(&mut input), - ))); + let mq = + Arc::new(shared_lock.wrap(MediaList::parse(&context, &mut CssParser::new(&mut input)))); let loader = StylesheetLoader::for_element(self.upcast()); let sheet = Stylesheet::from_str( &data, @@ -117,7 +125,11 @@ impl HTMLStyleElement { // No subresource loads were triggered, queue load event if self.pending_loads.get() == 0 { let window = window_from_node(self); - window.dom_manipulation_task_source().queue_simple_event(self.upcast(), atom!("load"), &window); + window.dom_manipulation_task_source().queue_simple_event( + self.upcast(), + atom!("load"), + &window, + ); } self.set_stylesheet(sheet); @@ -141,12 +153,14 @@ impl HTMLStyleElement { pub fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { - CSSStyleSheet::new(&window_from_node(self), - self.upcast::<Element>(), - "text/css".into(), - None, // todo handle location - None, // todo handle title - sheet) + CSSStyleSheet::new( + &window_from_node(self), + self.upcast::<Element>(), + "text/css".into(), + None, // todo handle location + None, // todo handle title + sheet, + ) }) }) } @@ -243,7 +257,6 @@ impl StylesheetOwner for HTMLStyleElement { } } - impl HTMLStyleElementMethods for HTMLStyleElement { // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet fn GetSheet(&self) -> Option<DomRoot<DOMStyleSheet>> { diff --git a/components/script/dom/htmltablecaptionelement.rs b/components/script/dom/htmltablecaptionelement.rs index a993d03a990..9f20ef716c5 100644 --- a/components/script/dom/htmltablecaptionelement.rs +++ b/components/script/dom/htmltablecaptionelement.rs @@ -12,25 +12,32 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLTableCaptionElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLTableCaptionElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLTableCaptionElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLTableCaptionElement { HTMLTableCaptionElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLTableCaptionElement> { - Node::reflect_node(Box::new(HTMLTableCaptionElement::new_inherited(local_name, prefix, document)), - document, - HTMLTableCaptionElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLTableCaptionElement> { + Node::reflect_node( + Box::new(HTMLTableCaptionElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLTableCaptionElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmltablecellelement.rs b/components/script/dom/htmltablecellelement.rs index b3197d7f67e..5b9d8aa7748 100644 --- a/components/script/dom/htmltablecellelement.rs +++ b/components/script/dom/htmltablecellelement.rs @@ -28,10 +28,11 @@ pub struct HTMLTableCellElement { } impl HTMLTableCellElement { - pub fn new_inherited(tag_name: LocalName, - prefix: Option<Prefix>, - document: &Document) - -> HTMLTableCellElement { + pub fn new_inherited( + tag_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLTableCellElement { HTMLTableCellElement { htmlelement: HTMLElement::new_inherited(tag_name, prefix, document), } @@ -74,13 +75,13 @@ impl HTMLTableCellElementMethods for HTMLTableCellElement { _ => return -1, }; - parent_children.filter(|c| c.is::<HTMLTableCellElement>()) - .position(|c| &*c == self_node) - .map_or(-1, |p| p as i32) + parent_children + .filter(|c| c.is::<HTMLTableCellElement>()) + .position(|c| &*c == self_node) + .map_or(-1, |p| p as i32) } } - pub trait HTMLTableCellElementLayoutHelpers { fn get_background_color(&self) -> Option<RGBA>; fn get_colspan(&self) -> Option<u32>; @@ -142,7 +143,7 @@ impl VirtualMethods for HTMLTableCellElement { } } attr - } + }, local_name!("rowspan") => { let mut attr = AttrValue::from_u32(value.into(), DEFAULT_ROWSPAN); if let AttrValue::UInt(ref mut s, ref mut val) = attr { @@ -157,10 +158,13 @@ impl VirtualMethods for HTMLTableCellElement { } } attr - } + }, local_name!("bgcolor") => AttrValue::from_legacy_color(value.into()), local_name!("width") => AttrValue::from_nonzero_dimension(value.into()), - _ => self.super_type().unwrap().parse_plain_attribute(local_name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(local_name, value), } } } diff --git a/components/script/dom/htmltablecolelement.rs b/components/script/dom/htmltablecolelement.rs index 71e3177554f..040a412121a 100644 --- a/components/script/dom/htmltablecolelement.rs +++ b/components/script/dom/htmltablecolelement.rs @@ -16,21 +16,28 @@ pub struct HTMLTableColElement { } impl HTMLTableColElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLTableColElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLTableColElement { HTMLTableColElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLTableColElement> { - Node::reflect_node(Box::new(HTMLTableColElement::new_inherited(local_name, prefix, document)), - document, - HTMLTableColElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLTableColElement> { + Node::reflect_node( + Box::new(HTMLTableColElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLTableColElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmltabledatacellelement.rs b/components/script/dom/htmltabledatacellelement.rs index ba885952fe7..9d5e4c1c035 100644 --- a/components/script/dom/htmltabledatacellelement.rs +++ b/components/script/dom/htmltabledatacellelement.rs @@ -16,24 +16,28 @@ pub struct HTMLTableDataCellElement { } impl HTMLTableDataCellElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLTableDataCellElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLTableDataCellElement { HTMLTableDataCellElement { - htmltablecellelement: - HTMLTableCellElement::new_inherited(local_name, prefix, document) + htmltablecellelement: HTMLTableCellElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) - -> DomRoot<HTMLTableDataCellElement> { + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLTableDataCellElement> { Node::reflect_node( Box::new(HTMLTableDataCellElement::new_inherited( - local_name, prefix, document + local_name, prefix, document, )), document, - HTMLTableDataCellElementBinding::Wrap + HTMLTableDataCellElementBinding::Wrap, ) } } diff --git a/components/script/dom/htmltableelement.rs b/components/script/dom/htmltableelement.rs index c475c3eee1d..a9826aea9d0 100644 --- a/components/script/dom/htmltableelement.rs +++ b/components/script/dom/htmltableelement.rs @@ -44,14 +44,19 @@ struct TableRowFilter { impl CollectionFilter for TableRowFilter { fn filter(&self, elem: &Element, root: &Node) -> bool { elem.is::<HTMLTableRowElement>() && - (root.is_parent_of(elem.upcast()) - || self.sections.iter().any(|ref section| section.is_parent_of(elem.upcast()))) + (root.is_parent_of(elem.upcast()) || self + .sections + .iter() + .any(|ref section| section.is_parent_of(elem.upcast()))) } } impl HTMLTableElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) - -> HTMLTableElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLTableElement { HTMLTableElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), border: Cell::new(None), @@ -61,11 +66,18 @@ impl HTMLTableElement { } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) - -> DomRoot<HTMLTableElement> { - Node::reflect_node(Box::new(HTMLTableElement::new_inherited(local_name, prefix, document)), - document, - HTMLTableElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLTableElement> { + Node::reflect_node( + Box::new(HTMLTableElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLTableElementBinding::Wrap, + ) } pub fn get_border(&self) -> Option<u32> { @@ -74,7 +86,10 @@ impl HTMLTableElement { // https://html.spec.whatwg.org/multipage/#dom-table-thead // https://html.spec.whatwg.org/multipage/#dom-table-tfoot - fn get_first_section_of_type(&self, atom: &LocalName) -> Option<DomRoot<HTMLTableSectionElement>> { + fn get_first_section_of_type( + &self, + atom: &LocalName, + ) -> Option<DomRoot<HTMLTableSectionElement>> { self.upcast::<Node>() .child_elements() .find(|n| n.is::<HTMLTableSectionElement>() && n.local_name() == atom) @@ -83,15 +98,18 @@ impl HTMLTableElement { // https://html.spec.whatwg.org/multipage/#dom-table-thead // https://html.spec.whatwg.org/multipage/#dom-table-tfoot - fn set_first_section_of_type<P>(&self, - atom: &LocalName, - section: Option<&HTMLTableSectionElement>, - reference_predicate: P) - -> ErrorResult - where P: FnMut(&DomRoot<Element>) -> bool { + fn set_first_section_of_type<P>( + &self, + atom: &LocalName, + section: Option<&HTMLTableSectionElement>, + reference_predicate: P, + ) -> ErrorResult + where + P: FnMut(&DomRoot<Element>) -> bool, + { if let Some(e) = section { if e.upcast::<Element>().local_name() != atom { - return Err(Error::HierarchyRequest) + return Err(Error::HierarchyRequest); } } @@ -113,16 +131,14 @@ impl HTMLTableElement { // https://html.spec.whatwg.org/multipage/#dom-table-createtfoot fn create_section_of_type(&self, atom: &LocalName) -> DomRoot<HTMLTableSectionElement> { if let Some(section) = self.get_first_section_of_type(atom) { - return section + return section; } - let section = HTMLTableSectionElement::new(atom.clone(), - None, - &document_from_node(self)); + let section = HTMLTableSectionElement::new(atom.clone(), None, &document_from_node(self)); match atom { &local_name!("thead") => self.SetTHead(Some(§ion)), &local_name!("tfoot") => self.SetTFoot(Some(§ion)), - _ => unreachable!("unexpected section type") + _ => unreachable!("unexpected section type"), }.expect("unexpected section type"); section @@ -138,11 +154,13 @@ impl HTMLTableElement { fn get_rows(&self) -> TableRowFilter { TableRowFilter { - sections: self.upcast::<Node>() - .children() - .filter_map(|ref node| - node.downcast::<HTMLTableSectionElement>().map(|_| Dom::from_ref(&**node))) - .collect() + sections: self + .upcast::<Node>() + .children() + .filter_map(|ref node| { + node.downcast::<HTMLTableSectionElement>() + .map(|_| Dom::from_ref(&**node)) + }).collect(), } } } @@ -156,7 +174,10 @@ impl HTMLTableElementMethods for HTMLTableElement { // https://html.spec.whatwg.org/multipage/#dom-table-caption fn GetCaption(&self) -> Option<DomRoot<HTMLTableCaptionElement>> { - self.upcast::<Node>().children().filter_map(DomRoot::downcast).next() + self.upcast::<Node>() + .children() + .filter_map(DomRoot::downcast) + .next() } // https://html.spec.whatwg.org/multipage/#dom-table-caption @@ -177,12 +198,14 @@ impl HTMLTableElementMethods for HTMLTableElement { match self.GetCaption() { Some(caption) => caption, None => { - let caption = HTMLTableCaptionElement::new(local_name!("caption"), - None, - &document_from_node(self)); + let caption = HTMLTableCaptionElement::new( + local_name!("caption"), + None, + &document_from_node(self), + ); self.SetCaption(Some(&caption)); caption - } + }, } } @@ -193,7 +216,6 @@ impl HTMLTableElementMethods for HTMLTableElement { } } - // https://html.spec.whatwg.org/multipage/#dom-table-thead fn GetTHead(&self) -> Option<DomRoot<HTMLTableSectionElement>> { self.get_first_section_of_type(&local_name!("thead")) @@ -233,7 +255,6 @@ impl HTMLTableElementMethods for HTMLTableElement { if name == &local_name!("thead") || name == &local_name!("tbody") { return false; } - } true @@ -269,19 +290,16 @@ impl HTMLTableElementMethods for HTMLTableElement { }) } - // https://html.spec.whatwg.org/multipage/#dom-table-createtbody fn CreateTBody(&self) -> DomRoot<HTMLTableSectionElement> { - let tbody = HTMLTableSectionElement::new(local_name!("tbody"), - None, - &document_from_node(self)); + let tbody = + HTMLTableSectionElement::new(local_name!("tbody"), None, &document_from_node(self)); let node = self.upcast::<Node>(); - let last_tbody = - node.rev_children() - .filter_map(DomRoot::downcast::<Element>) - .find(|n| n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody")); - let reference_element = - last_tbody.and_then(|t| t.upcast::<Node>().GetNextSibling()); + let last_tbody = node + .rev_children() + .filter_map(DomRoot::downcast::<Element>) + .find(|n| n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody")); + let reference_element = last_tbody.and_then(|t| t.upcast::<Node>().GetNextSibling()); node.InsertBefore(tbody.upcast(), reference_element.r()) .expect("Insertion failed"); @@ -297,47 +315,61 @@ impl HTMLTableElementMethods for HTMLTableElement { return Err(Error::IndexSize); } - let new_row = HTMLTableRowElement::new(local_name!("tr"), - None, - &document_from_node(self)); + let new_row = HTMLTableRowElement::new(local_name!("tr"), None, &document_from_node(self)); let node = self.upcast::<Node>(); if number_of_row_elements == 0 { // append new row to last or new tbody in table - if let Some(last_tbody) = node.rev_children() + if let Some(last_tbody) = node + .rev_children() .filter_map(DomRoot::downcast::<Element>) - .find(|n| n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody")) { - last_tbody.upcast::<Node>().AppendChild(new_row.upcast::<Node>()) - .expect("InsertRow failed to append first row."); - } else { - let tbody = self.CreateTBody(); - node.AppendChild(tbody.upcast()) - .expect("InsertRow failed to append new tbody."); - - tbody.upcast::<Node>().AppendChild(new_row.upcast::<Node>()) - .expect("InsertRow failed to append first row."); - } + .find(|n| { + n.is::<HTMLTableSectionElement>() && n.local_name() == &local_name!("tbody") + }) { + last_tbody + .upcast::<Node>() + .AppendChild(new_row.upcast::<Node>()) + .expect("InsertRow failed to append first row."); + } else { + let tbody = self.CreateTBody(); + node.AppendChild(tbody.upcast()) + .expect("InsertRow failed to append new tbody."); + + tbody + .upcast::<Node>() + .AppendChild(new_row.upcast::<Node>()) + .expect("InsertRow failed to append first row."); + } } else if index == number_of_row_elements as i32 || index == -1 { // append new row to parent of last row in table - let last_row = rows.Item(number_of_row_elements - 1) - .expect("InsertRow failed to find last row in table."); - - let last_row_parent = - last_row.upcast::<Node>().GetParentNode() - .expect("InsertRow failed to find parent of last row in table."); - - last_row_parent.upcast::<Node>().AppendChild(new_row.upcast::<Node>()) - .expect("InsertRow failed to append last row."); + let last_row = rows + .Item(number_of_row_elements - 1) + .expect("InsertRow failed to find last row in table."); + + let last_row_parent = last_row + .upcast::<Node>() + .GetParentNode() + .expect("InsertRow failed to find parent of last row in table."); + + last_row_parent + .upcast::<Node>() + .AppendChild(new_row.upcast::<Node>()) + .expect("InsertRow failed to append last row."); } else { // insert new row before the index-th row in rows using the same parent - let ith_row = rows.Item(index as u32) - .expect("InsertRow failed to find a row in table."); - - let ith_row_parent = ith_row.upcast::<Node>().GetParentNode() - .expect("InsertRow failed to find parent of a row in table."); - - ith_row_parent.upcast::<Node>().InsertBefore(new_row.upcast::<Node>(), Some(ith_row.upcast::<Node>())) - .expect("InsertRow failed to append row"); + let ith_row = rows + .Item(index as u32) + .expect("InsertRow failed to find a row in table."); + + let ith_row_parent = ith_row + .upcast::<Node>() + .GetParentNode() + .expect("InsertRow failed to find parent of a row in table."); + + ith_row_parent + .upcast::<Node>() + .InsertBefore(new_row.upcast::<Node>(), Some(ith_row.upcast::<Node>())) + .expect("InsertRow failed to append row"); } Ok(new_row) @@ -392,16 +424,12 @@ impl HTMLTableElementLayoutHelpers for LayoutDom<HTMLTableElement> { #[allow(unsafe_code)] fn get_border(&self) -> Option<u32> { - unsafe { - (*self.unsafe_get()).border.get() - } + unsafe { (*self.unsafe_get()).border.get() } } #[allow(unsafe_code)] fn get_cellspacing(&self) -> Option<u32> { - unsafe { - (*self.unsafe_get()).cellspacing.get() - } + unsafe { (*self.unsafe_get()).cellspacing.get() } } #[allow(unsafe_code)] @@ -426,14 +454,18 @@ impl VirtualMethods for HTMLTableElement { match *attr.local_name() { local_name!("border") => { // According to HTML5 § 14.3.9, invalid values map to 1px. - self.border.set(mutation.new_value(attr).map(|value| { - parse_unsigned_integer(value.chars()).unwrap_or(1) - })); - } + self.border.set( + mutation + .new_value(attr) + .map(|value| parse_unsigned_integer(value.chars()).unwrap_or(1)), + ); + }, local_name!("cellspacing") => { - self.cellspacing.set(mutation.new_value(attr).and_then(|value| { - parse_unsigned_integer(value.chars()).ok() - })); + self.cellspacing.set( + mutation + .new_value(attr) + .and_then(|value| parse_unsigned_integer(value.chars()).ok()), + ); }, _ => {}, } @@ -444,7 +476,10 @@ impl VirtualMethods for HTMLTableElement { local_name!("border") => AttrValue::from_u32(value.into(), 1), local_name!("width") => AttrValue::from_nonzero_dimension(value.into()), local_name!("bgcolor") => AttrValue::from_legacy_color(value.into()), - _ => self.super_type().unwrap().parse_plain_attribute(local_name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(local_name, value), } } } diff --git a/components/script/dom/htmltableheadercellelement.rs b/components/script/dom/htmltableheadercellelement.rs index db7e6ee368c..f0757b20403 100644 --- a/components/script/dom/htmltableheadercellelement.rs +++ b/components/script/dom/htmltableheadercellelement.rs @@ -16,21 +16,28 @@ pub struct HTMLTableHeaderCellElement { } impl HTMLTableHeaderCellElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLTableHeaderCellElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLTableHeaderCellElement { HTMLTableHeaderCellElement { - htmltablecellelement: - HTMLTableCellElement::new_inherited(local_name, prefix, document) + htmltablecellelement: HTMLTableCellElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLTableHeaderCellElement> { - Node::reflect_node(Box::new(HTMLTableHeaderCellElement::new_inherited(local_name, prefix, document)), - document, - HTMLTableHeaderCellElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLTableHeaderCellElement> { + Node::reflect_node( + Box::new(HTMLTableHeaderCellElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLTableHeaderCellElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmltablerowelement.rs b/components/script/dom/htmltablerowelement.rs index 6e8802c2937..8cceb2212a0 100644 --- a/components/script/dom/htmltablerowelement.rs +++ b/components/script/dom/htmltablerowelement.rs @@ -41,8 +41,11 @@ pub struct HTMLTableRowElement { } impl HTMLTableRowElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) - -> HTMLTableRowElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLTableRowElement { HTMLTableRowElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), cells: Default::default(), @@ -50,19 +53,27 @@ impl HTMLTableRowElement { } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) - -> DomRoot<HTMLTableRowElement> { - Node::reflect_node(Box::new(HTMLTableRowElement::new_inherited(local_name, prefix, document)), - document, - HTMLTableRowElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLTableRowElement> { + Node::reflect_node( + Box::new(HTMLTableRowElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLTableRowElementBinding::Wrap, + ) } /// Determine the index for this `HTMLTableRowElement` within the given /// `HTMLCollection`. Returns `-1` if not found within collection. fn row_index(&self, collection: DomRoot<HTMLCollection>) -> i32 { - collection.elements_iter() - .position(|elem| (&elem as &Element) == self.upcast()) - .map_or(-1, |i| i as i32) + collection + .elements_iter() + .position(|elem| (&elem as &Element) == self.upcast()) + .map_or(-1, |i| i as i32) } } @@ -88,7 +99,8 @@ impl HTMLTableRowElementMethods for HTMLTableRowElement { node.insert_cell_or_row( index, || self.Cells(), - || HTMLTableDataCellElement::new(local_name!("td"), None, &node.owner_doc())) + || HTMLTableDataCellElement::new(local_name!("td"), None, &node.owner_doc()), + ) } // https://html.spec.whatwg.org/multipage/#dom-tr-deletecell @@ -97,7 +109,8 @@ impl HTMLTableRowElementMethods for HTMLTableRowElement { node.delete_cell_or_row( index, || self.Cells(), - |n| n.is::<HTMLTableDataCellElement>()) + |n| n.is::<HTMLTableDataCellElement>(), + ) } // https://html.spec.whatwg.org/multipage/#dom-tr-rowindex @@ -116,8 +129,9 @@ impl HTMLTableRowElementMethods for HTMLTableRowElement { Some(parent) => parent, None => return -1, }; - grandparent.downcast::<HTMLTableElement>() - .map_or(-1, |table| self.row_index(table.Rows())) + grandparent + .downcast::<HTMLTableElement>() + .map_or(-1, |table| self.row_index(table.Rows())) } // https://html.spec.whatwg.org/multipage/#dom-tr-sectionrowindex @@ -161,7 +175,10 @@ impl VirtualMethods for HTMLTableRowElement { fn parse_plain_attribute(&self, local_name: &LocalName, value: DOMString) -> AttrValue { match *local_name { local_name!("bgcolor") => AttrValue::from_legacy_color(value.into()), - _ => self.super_type().unwrap().parse_plain_attribute(local_name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(local_name, value), } } } diff --git a/components/script/dom/htmltablesectionelement.rs b/components/script/dom/htmltablesectionelement.rs index 58c72ddeed5..885b03e018d 100644 --- a/components/script/dom/htmltablesectionelement.rs +++ b/components/script/dom/htmltablesectionelement.rs @@ -26,19 +26,29 @@ pub struct HTMLTableSectionElement { } impl HTMLTableSectionElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) - -> HTMLTableSectionElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLTableSectionElement { HTMLTableSectionElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) - -> DomRoot<HTMLTableSectionElement> { - Node::reflect_node(Box::new(HTMLTableSectionElement::new_inherited(local_name, prefix, document)), - document, - HTMLTableSectionElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLTableSectionElement> { + Node::reflect_node( + Box::new(HTMLTableSectionElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLTableSectionElementBinding::Wrap, + ) } } @@ -46,8 +56,7 @@ impl HTMLTableSectionElement { struct RowsFilter; impl CollectionFilter for RowsFilter { fn filter(&self, elem: &Element, root: &Node) -> bool { - elem.is::<HTMLTableRowElement>() && - elem.upcast::<Node>().GetParentNode().r() == Some(root) + elem.is::<HTMLTableRowElement>() && elem.upcast::<Node>().GetParentNode().r() == Some(root) } } @@ -63,16 +72,14 @@ impl HTMLTableSectionElementMethods for HTMLTableSectionElement { node.insert_cell_or_row( index, || self.Rows(), - || HTMLTableRowElement::new(local_name!("tr"), None, &node.owner_doc())) + || HTMLTableRowElement::new(local_name!("tr"), None, &node.owner_doc()), + ) } // https://html.spec.whatwg.org/multipage/#dom-tbody-deleterow fn DeleteRow(&self, index: i32) -> ErrorResult { let node = self.upcast::<Node>(); - node.delete_cell_or_row( - index, - || self.Rows(), - |n| n.is::<HTMLTableRowElement>()) + node.delete_cell_or_row(index, || self.Rows(), |n| n.is::<HTMLTableRowElement>()) } } @@ -100,7 +107,10 @@ impl VirtualMethods for HTMLTableSectionElement { fn parse_plain_attribute(&self, local_name: &LocalName, value: DOMString) -> AttrValue { match *local_name { local_name!("bgcolor") => AttrValue::from_legacy_color(value.into()), - _ => self.super_type().unwrap().parse_plain_attribute(local_name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(local_name, value), } } } diff --git a/components/script/dom/htmltemplateelement.rs b/components/script/dom/htmltemplateelement.rs index 0d61ceb09a6..8cfa662332d 100644 --- a/components/script/dom/htmltemplateelement.rs +++ b/components/script/dom/htmltemplateelement.rs @@ -25,23 +25,30 @@ pub struct HTMLTemplateElement { } impl HTMLTemplateElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLTemplateElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLTemplateElement { HTMLTemplateElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document), + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), contents: MutNullableDom::new(None), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLTemplateElement> { - Node::reflect_node(Box::new(HTMLTemplateElement::new_inherited(local_name, prefix, document)), - document, - HTMLTemplateElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLTemplateElement> { + Node::reflect_node( + Box::new(HTMLTemplateElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLTemplateElementBinding::Wrap, + ) } } @@ -50,7 +57,8 @@ impl HTMLTemplateElementMethods for HTMLTemplateElement { fn Content(&self) -> DomRoot<DocumentFragment> { self.contents.or_init(|| { let doc = document_from_node(self); - doc.appropriate_template_contents_owner_document().CreateDocumentFragment() + doc.appropriate_template_contents_owner_document() + .CreateDocumentFragment() }) } } @@ -70,9 +78,15 @@ impl VirtualMethods for HTMLTemplateElement { } /// <https://html.spec.whatwg.org/multipage/#the-template-element:concept-node-clone-ext> - fn cloning_steps(&self, copy: &Node, maybe_doc: Option<&Document>, - clone_children: CloneChildrenFlag) { - self.super_type().unwrap().cloning_steps(copy, maybe_doc, clone_children); + fn cloning_steps( + &self, + copy: &Node, + maybe_doc: Option<&Document>, + clone_children: CloneChildrenFlag, + ) { + self.super_type() + .unwrap() + .cloning_steps(copy, maybe_doc, clone_children); if clone_children == CloneChildrenFlag::DoNotCloneChildren { // Step 1. return; @@ -83,7 +97,10 @@ impl VirtualMethods for HTMLTemplateElement { let copy_contents_doc = copy_contents.owner_doc(); for child in self.Content().upcast::<Node>().children() { let copy_child = Node::clone( - &child, Some(©_contents_doc), CloneChildrenFlag::CloneChildren); + &child, + Some(©_contents_doc), + CloneChildrenFlag::CloneChildren, + ); copy_contents.AppendChild(©_child).unwrap(); } } diff --git a/components/script/dom/htmltextareaelement.rs b/components/script/dom/htmltextareaelement.rs index 459500da9a1..f3b8a301f74 100755 --- a/components/script/dom/htmltextareaelement.rs +++ b/components/script/dom/htmltextareaelement.rs @@ -64,9 +64,13 @@ impl LayoutHTMLTextAreaElementHelpers for LayoutDom<HTMLTextAreaElement> { #[allow(unrooted_must_root)] #[allow(unsafe_code)] unsafe fn value_for_layout(self) -> String { - let text = (*self.unsafe_get()).textinput.borrow_for_layout().get_content(); + let text = (*self.unsafe_get()) + .textinput + .borrow_for_layout() + .get_content(); if text.is_empty() { - (*self.unsafe_get()).placeholder + (*self.unsafe_get()) + .placeholder .borrow_for_layout() .replace("\r\n", "\n") .replace("\r", "\n") @@ -114,30 +118,50 @@ const DEFAULT_MAX_LENGTH: i32 = -1; const DEFAULT_MIN_LENGTH: i32 = -1; impl HTMLTextAreaElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLTextAreaElement { - let chan = document.window().upcast::<GlobalScope>().script_to_constellation_chan().clone(); + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLTextAreaElement { + let chan = document + .window() + .upcast::<GlobalScope>() + .script_to_constellation_chan() + .clone(); HTMLTextAreaElement { - htmlelement: - HTMLElement::new_inherited_with_state(ElementState::IN_ENABLED_STATE | - ElementState::IN_READ_WRITE_STATE, - local_name, prefix, document), + htmlelement: HTMLElement::new_inherited_with_state( + ElementState::IN_ENABLED_STATE | ElementState::IN_READ_WRITE_STATE, + local_name, + prefix, + document, + ), placeholder: DomRefCell::new(DOMString::new()), textinput: DomRefCell::new(TextInput::new( - Lines::Multiple, DOMString::new(), chan, None, None, SelectionDirection::None)), + Lines::Multiple, + DOMString::new(), + chan, + None, + None, + SelectionDirection::None, + )), value_dirty: Cell::new(false), form_owner: Default::default(), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLTextAreaElement> { - Node::reflect_node(Box::new(HTMLTextAreaElement::new_inherited(local_name, prefix, document)), - document, - HTMLTextAreaElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLTextAreaElement> { + Node::reflect_node( + Box::new(HTMLTextAreaElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLTextAreaElementBinding::Wrap, + ) } fn update_placeholder_shown_state(&self) { @@ -280,7 +304,7 @@ impl HTMLTextAreaElementMethods for HTMLTextAreaElement { // https://html.spec.whatwg.org/multipage/#dom-textarea-textlength fn TextLength(&self) -> u32 { - self.textinput.borrow().utf16_len() as u32 + self.textinput.borrow().utf16_len() as u32 } // https://html.spec.whatwg.org/multipage/#dom-lfe-labels @@ -330,17 +354,23 @@ impl HTMLTextAreaElementMethods for HTMLTextAreaElement { // https://html.spec.whatwg.org/multipage/#dom-textarea/input-setrangetext fn SetRangeText(&self, replacement: DOMString) -> ErrorResult { - self.selection().set_dom_range_text(replacement, None, None, Default::default()) + self.selection() + .set_dom_range_text(replacement, None, None, Default::default()) } // https://html.spec.whatwg.org/multipage/#dom-textarea/input-setrangetext - fn SetRangeText_(&self, replacement: DOMString, start: u32, end: u32, - selection_mode: SelectionMode) -> ErrorResult { - self.selection().set_dom_range_text(replacement, Some(start), Some(end), selection_mode) + fn SetRangeText_( + &self, + replacement: DOMString, + start: u32, + end: u32, + selection_mode: SelectionMode, + ) -> ErrorResult { + self.selection() + .set_dom_range_text(replacement, Some(start), Some(end), selection_mode) } } - impl HTMLTextAreaElement { pub fn reset(&self) { // https://html.spec.whatwg.org/multipage/#the-textarea-element:concept-form-reset-control @@ -355,7 +385,6 @@ impl HTMLTextAreaElement { } } - impl VirtualMethods for HTMLTextAreaElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) @@ -381,36 +410,32 @@ impl VirtualMethods for HTMLTextAreaElement { if !el.disabled_state() && !el.read_write_state() { el.set_read_write_state(true); } - } - } - }, - local_name!("maxlength") => { - match *attr.value() { - AttrValue::Int(_, value) => { - let mut textinput = self.textinput.borrow_mut(); - - if value < 0 { - textinput.set_max_length(None); - } else { - textinput.set_max_length(Some(value as usize)) - } }, - _ => panic!("Expected an AttrValue::Int"), } }, - local_name!("minlength") => { - match *attr.value() { - AttrValue::Int(_, value) => { - let mut textinput = self.textinput.borrow_mut(); - - if value < 0 { - textinput.set_min_length(None); - } else { - textinput.set_min_length(Some(value as usize)) - } - }, - _ => panic!("Expected an AttrValue::Int"), - } + local_name!("maxlength") => match *attr.value() { + AttrValue::Int(_, value) => { + let mut textinput = self.textinput.borrow_mut(); + + if value < 0 { + textinput.set_max_length(None); + } else { + textinput.set_max_length(Some(value as usize)) + } + }, + _ => panic!("Expected an AttrValue::Int"), + }, + local_name!("minlength") => match *attr.value() { + AttrValue::Int(_, value) => { + let mut textinput = self.textinput.borrow_mut(); + + if value < 0 { + textinput.set_min_length(None); + } else { + textinput.set_min_length(Some(value as usize)) + } + }, + _ => panic!("Expected an AttrValue::Int"), }, local_name!("placeholder") => { { @@ -430,7 +455,7 @@ impl VirtualMethods for HTMLTextAreaElement { }, AttributeMutation::Removed => { el.set_read_write_state(!el.disabled_state()); - } + }, } }, local_name!("form") => { @@ -445,16 +470,24 @@ impl VirtualMethods for HTMLTextAreaElement { s.bind_to_tree(tree_in_doc); } - self.upcast::<Element>().check_ancestors_disabled_state_for_form_control(); + self.upcast::<Element>() + .check_ancestors_disabled_state_for_form_control(); } fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match *name { local_name!("cols") => AttrValue::from_limited_u32(value.into(), DEFAULT_COLS), local_name!("rows") => AttrValue::from_limited_u32(value.into(), DEFAULT_ROWS), - local_name!("maxlength") => AttrValue::from_limited_i32(value.into(), DEFAULT_MAX_LENGTH), - local_name!("minlength") => AttrValue::from_limited_i32(value.into(), DEFAULT_MIN_LENGTH), - _ => self.super_type().unwrap().parse_plain_attribute(name, value), + local_name!("maxlength") => { + AttrValue::from_limited_i32(value.into(), DEFAULT_MAX_LENGTH) + }, + local_name!("minlength") => { + AttrValue::from_limited_i32(value.into(), DEFAULT_MIN_LENGTH) + }, + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(name, value), } } @@ -463,7 +496,10 @@ impl VirtualMethods for HTMLTextAreaElement { let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); - if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { + if node + .ancestors() + .any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) + { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); @@ -472,8 +508,12 @@ impl VirtualMethods for HTMLTextAreaElement { // The cloning steps for textarea elements must propagate the raw value // and dirty value flag from the node being cloned to the copy. - fn cloning_steps(&self, copy: &Node, maybe_doc: Option<&Document>, - clone_children: CloneChildrenFlag) { + fn cloning_steps( + &self, + copy: &Node, + maybe_doc: Option<&Document>, + clone_children: CloneChildrenFlag, + ) { if let Some(ref s) = self.super_type() { s.cloning_steps(copy, maybe_doc, clone_children); } @@ -514,23 +554,24 @@ impl VirtualMethods for HTMLTextAreaElement { self.update_placeholder_shown_state(); self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage); event.mark_as_handled(); - } + }, KeyReaction::RedrawSelection => { self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage); event.mark_as_handled(); - } + }, KeyReaction::Nothing => (), } } } else if event.type_() == atom!("keypress") && !event.DefaultPrevented() { if event.IsTrusted() { let window = window_from_node(self); - let _ = window.user_interaction_task_source() - .queue_event(&self.upcast(), - atom!("input"), - EventBubbles::Bubbles, - EventCancelable::NotCancelable, - &window); + let _ = window.user_interaction_task_source().queue_event( + &self.upcast(), + atom!("input"), + EventBubbles::Bubbles, + EventCancelable::NotCancelable, + &window, + ); } } } @@ -557,5 +598,4 @@ impl FormControl for HTMLTextAreaElement { } } - impl Validatable for HTMLTextAreaElement {} diff --git a/components/script/dom/htmltimeelement.rs b/components/script/dom/htmltimeelement.rs index bc477d99ed6..80f04df41f7 100644 --- a/components/script/dom/htmltimeelement.rs +++ b/components/script/dom/htmltimeelement.rs @@ -18,19 +18,27 @@ pub struct HTMLTimeElement { } impl HTMLTimeElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLTimeElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLTimeElement { HTMLTimeElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLTimeElement> { - Node::reflect_node(Box::new(HTMLTimeElement::new_inherited(local_name, prefix, document)), - document, - HTMLTimeElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLTimeElement> { + Node::reflect_node( + Box::new(HTMLTimeElement::new_inherited(local_name, prefix, document)), + document, + HTMLTimeElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmltitleelement.rs b/components/script/dom/htmltitleelement.rs index 986feac95a8..bbb8e569394 100644 --- a/components/script/dom/htmltitleelement.rs +++ b/components/script/dom/htmltitleelement.rs @@ -21,19 +21,29 @@ pub struct HTMLTitleElement { } impl HTMLTitleElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLTitleElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLTitleElement { HTMLTitleElement { - htmlelement: HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLTitleElement> { - Node::reflect_node(Box::new(HTMLTitleElement::new_inherited(local_name, prefix, document)), - document, - HTMLTitleElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLTitleElement> { + Node::reflect_node( + Box::new(HTMLTitleElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLTitleElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmltrackelement.rs b/components/script/dom/htmltrackelement.rs index 7b6eb23cf1e..6f8112825cb 100644 --- a/components/script/dom/htmltrackelement.rs +++ b/components/script/dom/htmltrackelement.rs @@ -16,18 +16,28 @@ pub struct HTMLTrackElement { } impl HTMLTrackElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLTrackElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLTrackElement { HTMLTrackElement { - htmlelement: HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLTrackElement> { - Node::reflect_node(Box::new(HTMLTrackElement::new_inherited(local_name, prefix, document)), - document, - HTMLTrackElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLTrackElement> { + Node::reflect_node( + Box::new(HTMLTrackElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLTrackElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlulistelement.rs b/components/script/dom/htmlulistelement.rs index b2338cae886..cfab0f3b6fb 100644 --- a/components/script/dom/htmlulistelement.rs +++ b/components/script/dom/htmlulistelement.rs @@ -12,22 +12,32 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLUListElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLUListElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLUListElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLUListElement { HTMLUListElement { - htmlelement: HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLUListElement> { - Node::reflect_node(Box::new(HTMLUListElement::new_inherited(local_name, prefix, document)), - document, - HTMLUListElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLUListElement> { + Node::reflect_node( + Box::new(HTMLUListElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLUListElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlunknownelement.rs b/components/script/dom/htmlunknownelement.rs index 0897171442a..fa1a14326e3 100644 --- a/components/script/dom/htmlunknownelement.rs +++ b/components/script/dom/htmlunknownelement.rs @@ -12,25 +12,32 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLUnknownElement { - htmlelement: HTMLElement + htmlelement: HTMLElement, } impl HTMLUnknownElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> HTMLUnknownElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLUnknownElement { HTMLUnknownElement { - htmlelement: - HTMLElement::new_inherited(local_name, prefix, document) + htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLUnknownElement> { - Node::reflect_node(Box::new(HTMLUnknownElement::new_inherited(local_name, prefix, document)), - document, - HTMLUnknownElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLUnknownElement> { + Node::reflect_node( + Box::new(HTMLUnknownElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLUnknownElementBinding::Wrap, + ) } } diff --git a/components/script/dom/htmlvideoelement.rs b/components/script/dom/htmlvideoelement.rs index f1f556f1bb4..8561aa051e1 100644 --- a/components/script/dom/htmlvideoelement.rs +++ b/components/script/dom/htmlvideoelement.rs @@ -12,23 +12,32 @@ use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLVideoElement { - htmlmediaelement: HTMLMediaElement + htmlmediaelement: HTMLMediaElement, } impl HTMLVideoElement { - fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLVideoElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> HTMLVideoElement { HTMLVideoElement { - htmlmediaelement: - HTMLMediaElement::new_inherited(local_name, prefix, document) + htmlmediaelement: HTMLMediaElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<HTMLVideoElement> { - Node::reflect_node(Box::new(HTMLVideoElement::new_inherited(local_name, prefix, document)), - document, - HTMLVideoElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<HTMLVideoElement> { + Node::reflect_node( + Box::new(HTMLVideoElement::new_inherited( + local_name, prefix, document, + )), + document, + HTMLVideoElementBinding::Wrap, + ) } } diff --git a/components/script/dom/imagedata.rs b/components/script/dom/imagedata.rs index e80914d8aea..d37e0092ba4 100644 --- a/components/script/dom/imagedata.rs +++ b/components/script/dom/imagedata.rs @@ -28,11 +28,12 @@ pub struct ImageData { impl ImageData { #[allow(unsafe_code)] - pub fn new(global: &GlobalScope, - width: u32, - height: u32, - mut data: Option<Vec<u8>>) - -> Fallible<DomRoot<ImageData>> { + pub fn new( + global: &GlobalScope, + width: u32, + height: u32, + mut data: Option<Vec<u8>>, + ) -> Fallible<DomRoot<ImageData>> { let len = width * height * 4; unsafe { let cx = global.get_cx(); @@ -50,11 +51,12 @@ impl ImageData { } #[allow(unsafe_code)] - unsafe fn new_with_jsobject(global: &GlobalScope, - width: u32, - mut opt_height: Option<u32>, - opt_jsobject: Option<*mut JSObject>) - -> Fallible<DomRoot<ImageData>> { + unsafe fn new_with_jsobject( + global: &GlobalScope, + width: u32, + mut opt_height: Option<u32>, + opt_jsobject: Option<*mut JSObject>, + ) -> Fallible<DomRoot<ImageData>> { assert!(opt_jsobject.is_some() || opt_height.is_some()); if width == 0 { @@ -65,8 +67,9 @@ impl ImageData { if let Some(jsobject) = opt_jsobject { let cx = global.get_cx(); typedarray!(in(cx) let array_res: Uint8ClampedArray = jsobject); - let array = array_res - .map_err(|_| Error::Type("Argument to Image data is not an Uint8ClampedArray".to_owned()))?; + let array = array_res.map_err(|_| { + Error::Type("Argument to Image data is not an Uint8ClampedArray".to_owned()) + })?; let byte_len = array.as_slice().len() as u32; if byte_len % 4 != 0 { @@ -108,7 +111,11 @@ impl ImageData { (*imagedata).data.set(array.get()); } - Ok(reflect_dom_object(imagedata, global, ImageDataBinding::Wrap)) + Ok(reflect_dom_object( + imagedata, + global, + ImageDataBinding::Wrap, + )) } // https://html.spec.whatwg.org/multipage/#pixel-manipulation:dom-imagedata-3 @@ -120,12 +127,13 @@ impl ImageData { // https://html.spec.whatwg.org/multipage/#pixel-manipulation:dom-imagedata-4 #[allow(unsafe_code)] #[allow(unused_variables)] - pub unsafe fn Constructor_(cx: *mut JSContext, - global: &GlobalScope, - jsobject: *mut JSObject, - width: u32, - opt_height: Option<u32>) - -> Fallible<DomRoot<Self>> { + pub unsafe fn Constructor_( + cx: *mut JSContext, + global: &GlobalScope, + jsobject: *mut JSObject, + width: u32, + opt_height: Option<u32>, + ) -> Fallible<DomRoot<Self>> { Self::new_with_jsobject(global, width, opt_height, Some(jsobject)) } diff --git a/components/script/dom/inputevent.rs b/components/script/dom/inputevent.rs index 3d855d08b41..aa4befe8f8a 100644 --- a/components/script/dom/inputevent.rs +++ b/components/script/dom/inputevent.rs @@ -20,37 +20,45 @@ pub struct InputEvent { } impl InputEvent { - pub fn new(window: &Window, - type_: DOMString, - can_bubble: bool, - cancelable: bool, - view: Option<&Window>, - detail: i32, - data: Option<DOMString>, - is_composing: bool) -> DomRoot<InputEvent> { - let ev = reflect_dom_object(Box::new(InputEvent { - uievent: UIEvent::new_inherited(), - data: data, - is_composing: is_composing, - }), - window, - InputEventBinding::Wrap); - ev.uievent.InitUIEvent(type_, can_bubble, cancelable, view, detail); + pub fn new( + window: &Window, + type_: DOMString, + can_bubble: bool, + cancelable: bool, + view: Option<&Window>, + detail: i32, + data: Option<DOMString>, + is_composing: bool, + ) -> DomRoot<InputEvent> { + let ev = reflect_dom_object( + Box::new(InputEvent { + uievent: UIEvent::new_inherited(), + data: data, + is_composing: is_composing, + }), + window, + InputEventBinding::Wrap, + ); + ev.uievent + .InitUIEvent(type_, can_bubble, cancelable, view, detail); ev } - pub fn Constructor(window: &Window, - type_: DOMString, - init: &InputEventBinding::InputEventInit) - -> Fallible<DomRoot<InputEvent>> { - let event = InputEvent::new(window, - type_, - init.parent.parent.bubbles, - init.parent.parent.cancelable, - init.parent.view.r(), - init.parent.detail, - init.data.clone(), - init.isComposing); + pub fn Constructor( + window: &Window, + type_: DOMString, + init: &InputEventBinding::InputEventInit, + ) -> Fallible<DomRoot<InputEvent>> { + let event = InputEvent::new( + window, + type_, + init.parent.parent.bubbles, + init.parent.parent.cancelable, + init.parent.view.r(), + init.parent.detail, + init.data.clone(), + init.isComposing, + ); Ok(event) } } diff --git a/components/script/dom/keyboardevent.rs b/components/script/dom/keyboardevent.rs index 707c6b64afe..81986eaf5b2 100644 --- a/components/script/dom/keyboardevent.rs +++ b/components/script/dom/keyboardevent.rs @@ -60,33 +60,46 @@ impl KeyboardEvent { } pub fn new_uninitialized(window: &Window) -> DomRoot<KeyboardEvent> { - reflect_dom_object(Box::new(KeyboardEvent::new_inherited()), - window, - KeyboardEventBinding::Wrap) + reflect_dom_object( + Box::new(KeyboardEvent::new_inherited()), + window, + KeyboardEventBinding::Wrap, + ) } - pub fn new(window: &Window, - type_: DOMString, - can_bubble: bool, - cancelable: bool, - view: Option<&Window>, - _detail: i32, - ch: Option<char>, - key: Option<Key>, - key_string: DOMString, - code: DOMString, - location: u32, - repeat: bool, - is_composing: bool, - ctrl_key: bool, - alt_key: bool, - shift_key: bool, - meta_key: bool, - char_code: Option<u32>, - key_code: u32) -> DomRoot<KeyboardEvent> { + pub fn new( + window: &Window, + type_: DOMString, + can_bubble: bool, + cancelable: bool, + view: Option<&Window>, + _detail: i32, + ch: Option<char>, + key: Option<Key>, + key_string: DOMString, + code: DOMString, + location: u32, + repeat: bool, + is_composing: bool, + ctrl_key: bool, + alt_key: bool, + shift_key: bool, + meta_key: bool, + char_code: Option<u32>, + key_code: u32, + ) -> DomRoot<KeyboardEvent> { let ev = KeyboardEvent::new_uninitialized(window); - ev.InitKeyboardEvent(type_, can_bubble, cancelable, view, key_string, location, - DOMString::new(), repeat, DOMString::new()); + ev.InitKeyboardEvent( + type_, + can_bubble, + cancelable, + view, + key_string, + location, + DOMString::new(), + repeat, + DOMString::new(), + ); ev.key.set(key); *ev.code.borrow_mut() = code; ev.ctrl.set(ctrl_key); @@ -100,37 +113,46 @@ impl KeyboardEvent { ev } - pub fn Constructor(window: &Window, - type_: DOMString, - init: &KeyboardEventBinding::KeyboardEventInit) -> Fallible<DomRoot<KeyboardEvent>> { - let event = KeyboardEvent::new(window, - type_, - init.parent.parent.parent.bubbles, - init.parent.parent.parent.cancelable, - init.parent.parent.view.r(), - init.parent.parent.detail, - None, - key_from_string(&init.key, init.location), - init.key.clone(), init.code.clone(), init.location, - init.repeat, init.isComposing, init.parent.ctrlKey, - init.parent.altKey, init.parent.shiftKey, init.parent.metaKey, - None, 0); + pub fn Constructor( + window: &Window, + type_: DOMString, + init: &KeyboardEventBinding::KeyboardEventInit, + ) -> Fallible<DomRoot<KeyboardEvent>> { + let event = KeyboardEvent::new( + window, + type_, + init.parent.parent.parent.bubbles, + init.parent.parent.parent.cancelable, + init.parent.parent.view.r(), + init.parent.parent.detail, + None, + key_from_string(&init.key, init.location), + init.key.clone(), + init.code.clone(), + init.location, + init.repeat, + init.isComposing, + init.parent.ctrlKey, + init.parent.altKey, + init.parent.shiftKey, + init.parent.metaKey, + None, + 0, + ); Ok(event) } - pub fn key_properties(ch: Option<char>, key: Key, mods: KeyModifiers) - -> KeyEventProperties { - KeyEventProperties { - key_string: key_value(ch, key, mods), - code: code_value(key), - location: key_location(key), - char_code: ch.map(|ch| ch as u32), - key_code: key_keycode(key), - } + pub fn key_properties(ch: Option<char>, key: Key, mods: KeyModifiers) -> KeyEventProperties { + KeyEventProperties { + key_string: key_value(ch, key, mods), + code: code_value(key), + location: key_location(key), + char_code: ch.map(|ch| ch as u32), + key_code: key_keycode(key), + } } } - impl KeyboardEvent { pub fn printable(&self) -> Option<char> { self.printable.get() @@ -436,7 +458,9 @@ fn key_from_string(key_string: &str, location: u32) -> Option<Key> { "}" => Some(Key::RightBracket), "]" => Some(Key::RightBracket), "Escape" => Some(Key::Escape), - "Enter" if location == KeyboardEventConstants::DOM_KEY_LOCATION_STANDARD => Some(Key::Enter), + "Enter" if location == KeyboardEventConstants::DOM_KEY_LOCATION_STANDARD => { + Some(Key::Enter) + }, "Tab" => Some(Key::Tab), "Backspace" => Some(Key::Backspace), "Insert" => Some(Key::Insert), @@ -494,20 +518,34 @@ fn key_from_string(key_string: &str, location: u32) -> Option<Key> { "*" if location == KeyboardEventConstants::DOM_KEY_LOCATION_NUMPAD => Some(Key::KpMultiply), "-" if location == KeyboardEventConstants::DOM_KEY_LOCATION_NUMPAD => Some(Key::KpSubtract), "+" if location == KeyboardEventConstants::DOM_KEY_LOCATION_NUMPAD => Some(Key::KpAdd), - "Enter" if location == KeyboardEventConstants::DOM_KEY_LOCATION_NUMPAD => Some(Key::KpEnter), + "Enter" if location == KeyboardEventConstants::DOM_KEY_LOCATION_NUMPAD => { + Some(Key::KpEnter) + }, "=" if location == KeyboardEventConstants::DOM_KEY_LOCATION_NUMPAD => Some(Key::KpEqual), - "Shift" if location == KeyboardEventConstants::DOM_KEY_LOCATION_LEFT => Some(Key::LeftShift), - "Control" if location == KeyboardEventConstants::DOM_KEY_LOCATION_LEFT => Some(Key::LeftControl), + "Shift" if location == KeyboardEventConstants::DOM_KEY_LOCATION_LEFT => { + Some(Key::LeftShift) + }, + "Control" if location == KeyboardEventConstants::DOM_KEY_LOCATION_LEFT => { + Some(Key::LeftControl) + }, "Alt" if location == KeyboardEventConstants::DOM_KEY_LOCATION_LEFT => Some(Key::LeftAlt), - "Super" if location == KeyboardEventConstants::DOM_KEY_LOCATION_LEFT => Some(Key::LeftSuper), - "Shift" if location == KeyboardEventConstants::DOM_KEY_LOCATION_RIGHT => Some(Key::RightShift), - "Control" if location == KeyboardEventConstants::DOM_KEY_LOCATION_RIGHT => Some(Key::RightControl), + "Super" if location == KeyboardEventConstants::DOM_KEY_LOCATION_LEFT => { + Some(Key::LeftSuper) + }, + "Shift" if location == KeyboardEventConstants::DOM_KEY_LOCATION_RIGHT => { + Some(Key::RightShift) + }, + "Control" if location == KeyboardEventConstants::DOM_KEY_LOCATION_RIGHT => { + Some(Key::RightControl) + }, "Alt" if location == KeyboardEventConstants::DOM_KEY_LOCATION_RIGHT => Some(Key::RightAlt), - "Super" if location == KeyboardEventConstants::DOM_KEY_LOCATION_RIGHT => Some(Key::RightSuper), + "Super" if location == KeyboardEventConstants::DOM_KEY_LOCATION_RIGHT => { + Some(Key::RightSuper) + }, "ContextMenu" => Some(Key::Menu), "BrowserForward" => Some(Key::NavigateForward), "BrowserBack" => Some(Key::NavigateBackward), - _ => None + _ => None, } } @@ -563,8 +601,7 @@ fn code_value(key: Key) -> &'static str { Key::Backslash => "Backslash", Key::RightBracket => "BracketRight", - Key::World1 | - Key::World2 => panic!("unknown char code for {:?}", key), + Key::World1 | Key::World2 => panic!("unknown char code for {:?}", key), Key::Escape => "Escape", Key::Enter => "Enter", @@ -640,22 +677,31 @@ fn code_value(key: Key) -> &'static str { fn key_location(key: Key) -> u32 { match key { - Key::Kp0 | Key::Kp1 | Key::Kp2 | - Key::Kp3 | Key::Kp4 | Key::Kp5 | - Key::Kp6 | Key::Kp7 | Key::Kp8 | - Key::Kp9 | Key::KpDecimal | - Key::KpDivide | Key::KpMultiply | - Key::KpSubtract | Key::KpAdd | - Key::KpEnter | Key::KpEqual => - KeyboardEventConstants::DOM_KEY_LOCATION_NUMPAD, - - Key::LeftShift | Key::LeftAlt | - Key::LeftControl | Key::LeftSuper => - KeyboardEventConstants::DOM_KEY_LOCATION_LEFT, - - Key::RightShift | Key::RightAlt | - Key::RightControl | Key::RightSuper => - KeyboardEventConstants::DOM_KEY_LOCATION_RIGHT, + Key::Kp0 | + Key::Kp1 | + Key::Kp2 | + Key::Kp3 | + Key::Kp4 | + Key::Kp5 | + Key::Kp6 | + Key::Kp7 | + Key::Kp8 | + Key::Kp9 | + Key::KpDecimal | + Key::KpDivide | + Key::KpMultiply | + Key::KpSubtract | + Key::KpAdd | + Key::KpEnter | + Key::KpEqual => KeyboardEventConstants::DOM_KEY_LOCATION_NUMPAD, + + Key::LeftShift | Key::LeftAlt | Key::LeftControl | Key::LeftSuper => { + KeyboardEventConstants::DOM_KEY_LOCATION_LEFT + }, + + Key::RightShift | Key::RightAlt | Key::RightControl | Key::RightSuper => { + KeyboardEventConstants::DOM_KEY_LOCATION_RIGHT + }, _ => KeyboardEventConstants::DOM_KEY_LOCATION_STANDARD, } @@ -737,7 +783,7 @@ fn key_keycode(key: Key) -> u32 { Key::Z => key as u32 - Key::A as u32 + 'A' as u32, //§ B.2.1.8 - _ => 0 + _ => 0, } } @@ -758,16 +804,18 @@ impl KeyEventProperties { impl KeyboardEventMethods for KeyboardEvent { // https://w3c.github.io/uievents/#widl-KeyboardEvent-initKeyboardEvent - fn InitKeyboardEvent(&self, - type_arg: DOMString, - can_bubble_arg: bool, - cancelable_arg: bool, - view_arg: Option<&Window>, - key_arg: DOMString, - location_arg: u32, - _modifiers_list_arg: DOMString, - repeat: bool, - _locale: DOMString) { + fn InitKeyboardEvent( + &self, + type_arg: DOMString, + can_bubble_arg: bool, + cancelable_arg: bool, + view_arg: Option<&Window>, + key_arg: DOMString, + location_arg: u32, + _modifiers_list_arg: DOMString, + repeat: bool, + _locale: DOMString, + ) { if self.upcast::<Event>().dispatching() { return; } @@ -831,8 +879,8 @@ impl KeyboardEventMethods for KeyboardEvent { "Alt" => self.AltKey(), "Shift" => self.ShiftKey(), "Meta" => self.MetaKey(), - "AltGraph" | "CapsLock" | "NumLock" | "ScrollLock" | "Accel" | - "Fn" | "FnLock" | "Hyper" | "OS" | "Symbol" | "SymbolLock" => false, //FIXME + "AltGraph" | "CapsLock" | "NumLock" | "ScrollLock" | "Accel" | "Fn" | "FnLock" | + "Hyper" | "OS" | "Symbol" | "SymbolLock" => false, //FIXME _ => false, } } diff --git a/components/script/dom/location.rs b/components/script/dom/location.rs index af66934802a..696819b9b47 100644 --- a/components/script/dom/location.rs +++ b/components/script/dom/location.rs @@ -25,22 +25,23 @@ impl Location { fn new_inherited(window: &Window) -> Location { Location { reflector_: Reflector::new(), - window: Dom::from_ref(window) + window: Dom::from_ref(window), } } pub fn new(window: &Window) -> DomRoot<Location> { - reflect_dom_object(Box::new(Location::new_inherited(window)), - window, - LocationBinding::Wrap) + reflect_dom_object( + Box::new(Location::new_inherited(window)), + window, + LocationBinding::Wrap, + ) } fn get_url(&self) -> ServoUrl { self.window.get_url() } - fn set_url_component(&self, value: USVString, - setter: fn(&mut ServoUrl, USVString)) { + fn set_url_component(&self, value: USVString, setter: fn(&mut ServoUrl, USVString)) { let mut url = self.window.get_url(); setter(&mut url, value); self.window.load_url(url, false, false, None); @@ -49,7 +50,10 @@ impl Location { fn check_same_origin_domain(&self) -> ErrorResult { let entry_document = GlobalScope::entry().as_window().Document(); let this_document = self.window.Document(); - if entry_document.origin().same_origin_domain(this_document.origin()) { + if entry_document + .origin() + .same_origin_domain(this_document.origin()) + { Ok(()) } else { Err(Error::Security) diff --git a/components/script/dom/macros.rs b/components/script/dom/macros.rs index 5362b09214e..601426b91ea 100644 --- a/components/script/dom/macros.rs +++ b/components/script/dom/macros.rs @@ -573,7 +573,7 @@ macro_rules! rooted_vec { (let mut $name:ident <- $iter:expr) => { let mut root = $crate::dom::bindings::trace::RootableVec::new_unrooted(); let mut $name = $crate::dom::bindings::trace::RootedVec::from_iter(&mut root, $iter); - } + }; } /// DOM struct implementation for simple interfaces inheriting from PerformanceEntry. @@ -622,11 +622,10 @@ macro_rules! handle_potential_webgl_error { Err(error) => { $context.webgl_error(error); $return_on_error - } + }, } }; ($context:expr, $call:expr) => { handle_potential_webgl_error!($context, $call, ()); }; } - diff --git a/components/script/dom/mediaerror.rs b/components/script/dom/mediaerror.rs index 09edba17888..11521af2fcc 100644 --- a/components/script/dom/mediaerror.rs +++ b/components/script/dom/mediaerror.rs @@ -24,9 +24,11 @@ impl MediaError { } pub fn new(window: &Window, code: u16) -> DomRoot<MediaError> { - reflect_dom_object(Box::new(MediaError::new_inherited(code)), - window, - MediaErrorBinding::Wrap) + reflect_dom_object( + Box::new(MediaError::new_inherited(code)), + window, + MediaErrorBinding::Wrap, + ) } } diff --git a/components/script/dom/medialist.rs b/components/script/dom/medialist.rs index 99800f1beb1..cf918e236d4 100644 --- a/components/script/dom/medialist.rs +++ b/components/script/dom/medialist.rs @@ -30,8 +30,10 @@ pub struct MediaList { impl MediaList { #[allow(unrooted_must_root)] - pub fn new_inherited(parent_stylesheet: &CSSStyleSheet, - media_queries: Arc<Locked<StyleMediaList>>) -> MediaList { + pub fn new_inherited( + parent_stylesheet: &CSSStyleSheet, + media_queries: Arc<Locked<StyleMediaList>>, + ) -> MediaList { MediaList { parent_stylesheet: Dom::from_ref(parent_stylesheet), reflector_: Reflector::new(), @@ -40,12 +42,16 @@ impl MediaList { } #[allow(unrooted_must_root)] - pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, - media_queries: Arc<Locked<StyleMediaList>>) - -> DomRoot<MediaList> { - reflect_dom_object(Box::new(MediaList::new_inherited(parent_stylesheet, media_queries)), - window, - MediaListBinding::Wrap) + pub fn new( + window: &Window, + parent_stylesheet: &CSSStyleSheet, + media_queries: Arc<Locked<StyleMediaList>>, + ) -> DomRoot<MediaList> { + reflect_dom_object( + Box::new(MediaList::new_inherited(parent_stylesheet, media_queries)), + window, + MediaListBinding::Wrap, + ) } fn shared_lock(&self) -> &SharedRwLock { @@ -135,7 +141,10 @@ impl MediaListMethods for MediaList { let m_serialized = m.clone().unwrap().to_css_string(); let mut guard = self.shared_lock().write(); let mq = self.media_queries.write_with(&mut guard); - let any = mq.media_queries.iter().any(|q| m_serialized == q.to_css_string()); + let any = mq + .media_queries + .iter() + .any(|q| m_serialized == q.to_css_string()); if any { return; } @@ -169,9 +178,11 @@ impl MediaListMethods for MediaList { let m_serialized = m.unwrap().to_css_string(); let mut guard = self.shared_lock().write(); let media_list = self.media_queries.write_with(&mut guard); - let new_vec = media_list.media_queries.drain(..) - .filter(|q| m_serialized != q.to_css_string()) - .collect(); + let new_vec = media_list + .media_queries + .drain(..) + .filter(|q| m_serialized != q.to_css_string()) + .collect(); media_list.media_queries = new_vec; } } diff --git a/components/script/dom/mediaquerylist.rs b/components/script/dom/mediaquerylist.rs index 63e743fde2e..93941cf2163 100644 --- a/components/script/dom/mediaquerylist.rs +++ b/components/script/dom/mediaquerylist.rs @@ -28,7 +28,7 @@ pub struct MediaQueryList { eventtarget: EventTarget, document: Dom<Document>, media_query_list: MediaList, - last_match_state: Cell<Option<bool>> + last_match_state: Cell<Option<bool>>, } impl MediaQueryList { @@ -42,9 +42,11 @@ impl MediaQueryList { } pub fn new(document: &Document, media_query_list: MediaList) -> DomRoot<MediaQueryList> { - reflect_dom_object(Box::new(MediaQueryList::new_inherited(document, media_query_list)), - document.window(), - MediaQueryListBinding::Wrap) + reflect_dom_object( + Box::new(MediaQueryList::new_inherited(document, media_query_list)), + document.window(), + MediaQueryListBinding::Wrap, + ) } } @@ -68,7 +70,8 @@ impl MediaQueryList { pub fn evaluate(&self) -> bool { self.document.device().map_or(false, |device| { - self.media_query_list.evaluate(&device, self.document.quirks_mode()) + self.media_query_list + .evaluate(&device, self.document.quirks_mode()) }) } } @@ -92,7 +95,9 @@ impl MediaQueryListMethods for MediaQueryList { self.upcast::<EventTarget>().add_event_listener( DOMString::from_string("change".to_owned()), listener, - AddEventListenerOptions { parent: EventListenerOptions { capture: false } }, + AddEventListenerOptions { + parent: EventListenerOptions { capture: false }, + }, ); } diff --git a/components/script/dom/mediaquerylistevent.rs b/components/script/dom/mediaquerylistevent.rs index c06da109d6d..42db9ec5f2d 100644 --- a/components/script/dom/mediaquerylistevent.rs +++ b/components/script/dom/mediaquerylistevent.rs @@ -23,24 +23,31 @@ use std::cell::Cell; pub struct MediaQueryListEvent { event: Event, media: DOMString, - matches: Cell<bool> + matches: Cell<bool>, } impl MediaQueryListEvent { - pub fn new_initialized(global: &GlobalScope, - media: DOMString, - matches: bool) -> DomRoot<MediaQueryListEvent> { + pub fn new_initialized( + global: &GlobalScope, + media: DOMString, + matches: bool, + ) -> DomRoot<MediaQueryListEvent> { let ev = Box::new(MediaQueryListEvent { event: Event::new_inherited(), media: media, - matches: Cell::new(matches) + matches: Cell::new(matches), }); reflect_dom_object(ev, global, MediaQueryListEventBinding::Wrap) } - pub fn new(global: &GlobalScope, type_: Atom, - bubbles: bool, cancelable: bool, - media: DOMString, matches: bool) -> DomRoot<MediaQueryListEvent> { + pub fn new( + global: &GlobalScope, + type_: Atom, + bubbles: bool, + cancelable: bool, + media: DOMString, + matches: bool, + ) -> DomRoot<MediaQueryListEvent> { let ev = MediaQueryListEvent::new_initialized(global, media, matches); { let event = ev.upcast::<Event>(); @@ -49,13 +56,20 @@ impl MediaQueryListEvent { ev } - pub fn Constructor(window: &Window, type_: DOMString, - init: &MediaQueryListEventInit) - -> Fallible<DomRoot<MediaQueryListEvent>> { + pub fn Constructor( + window: &Window, + type_: DOMString, + init: &MediaQueryListEventInit, + ) -> Fallible<DomRoot<MediaQueryListEvent>> { let global = window.upcast::<GlobalScope>(); - Ok(MediaQueryListEvent::new(global, Atom::from(type_), - init.parent.bubbles, init.parent.cancelable, - init.media.clone(), init.matches)) + Ok(MediaQueryListEvent::new( + global, + Atom::from(type_), + init.parent.bubbles, + init.parent.cancelable, + init.media.clone(), + init.matches, + )) } } diff --git a/components/script/dom/messageevent.rs b/components/script/dom/messageevent.rs index f7a47488558..9e357f1b4d0 100644 --- a/components/script/dom/messageevent.rs +++ b/components/script/dom/messageevent.rs @@ -30,16 +30,20 @@ pub struct MessageEvent { impl MessageEvent { pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<MessageEvent> { - MessageEvent::new_initialized(global, - HandleValue::undefined(), - DOMString::new(), - DOMString::new()) + MessageEvent::new_initialized( + global, + HandleValue::undefined(), + DOMString::new(), + DOMString::new(), + ) } - pub fn new_initialized(global: &GlobalScope, - data: HandleValue, - origin: DOMString, - lastEventId: DOMString) -> DomRoot<MessageEvent> { + pub fn new_initialized( + global: &GlobalScope, + data: HandleValue, + origin: DOMString, + lastEventId: DOMString, + ) -> DomRoot<MessageEvent> { let ev = Box::new(MessageEvent { event: Event::new_inherited(), data: Heap::default(), @@ -52,10 +56,15 @@ impl MessageEvent { ev } - pub fn new(global: &GlobalScope, type_: Atom, - bubbles: bool, cancelable: bool, - data: HandleValue, origin: DOMString, lastEventId: DOMString) - -> DomRoot<MessageEvent> { + pub fn new( + global: &GlobalScope, + type_: Atom, + bubbles: bool, + cancelable: bool, + data: HandleValue, + origin: DOMString, + lastEventId: DOMString, + ) -> DomRoot<MessageEvent> { let ev = MessageEvent::new_initialized(global, data, origin, lastEventId); { let event = ev.upcast::<Event>(); @@ -64,26 +73,31 @@ impl MessageEvent { ev } - pub fn Constructor(global: &GlobalScope, - type_: DOMString, - init: RootedTraceableBox<MessageEventBinding::MessageEventInit>) - -> Fallible<DomRoot<MessageEvent>> { - let ev = MessageEvent::new(global, - Atom::from(type_), - init.parent.bubbles, - init.parent.cancelable, - init.data.handle(), - init.origin.clone(), - init.lastEventId.clone()); + pub fn Constructor( + global: &GlobalScope, + type_: DOMString, + init: RootedTraceableBox<MessageEventBinding::MessageEventInit>, + ) -> Fallible<DomRoot<MessageEvent>> { + let ev = MessageEvent::new( + global, + Atom::from(type_), + init.parent.bubbles, + init.parent.cancelable, + init.data.handle(), + init.origin.clone(), + init.lastEventId.clone(), + ); Ok(ev) } } impl MessageEvent { - pub fn dispatch_jsval(target: &EventTarget, - scope: &GlobalScope, - message: HandleValue, - origin: Option<&str>) { + pub fn dispatch_jsval( + target: &EventTarget, + scope: &GlobalScope, + message: HandleValue, + origin: Option<&str>, + ) { let messageevent = MessageEvent::new( scope, atom!("message"), @@ -91,7 +105,8 @@ impl MessageEvent { false, message, DOMString::from(origin.unwrap_or("")), - DOMString::new()); + DOMString::new(), + ); messageevent.upcast::<Event>().fire(target); } } diff --git a/components/script/dom/mimetypearray.rs b/components/script/dom/mimetypearray.rs index 82528fc62ff..e53df85db64 100644 --- a/components/script/dom/mimetypearray.rs +++ b/components/script/dom/mimetypearray.rs @@ -19,14 +19,16 @@ pub struct MimeTypeArray { impl MimeTypeArray { pub fn new_inherited() -> MimeTypeArray { MimeTypeArray { - reflector_: Reflector::new() + reflector_: Reflector::new(), } } pub fn new(global: &GlobalScope) -> DomRoot<MimeTypeArray> { - reflect_dom_object(Box::new(MimeTypeArray::new_inherited()), - global, - MimeTypeArrayBinding::Wrap) + reflect_dom_object( + Box::new(MimeTypeArray::new_inherited()), + global, + MimeTypeArrayBinding::Wrap, + ) } } diff --git a/components/script/dom/mouseevent.rs b/components/script/dom/mouseevent.rs index 62ec6f16ed3..7524846c839 100644 --- a/components/script/dom/mouseevent.rs +++ b/components/script/dom/mouseevent.rs @@ -33,7 +33,7 @@ pub struct MouseEvent { meta_key: Cell<bool>, button: Cell<i16>, related_target: MutNullableDom<EventTarget>, - point_in_target: Cell<Option<Point2D<f32>>> + point_in_target: Cell<Option<Point2D<f32>>>, } impl MouseEvent { @@ -55,9 +55,11 @@ impl MouseEvent { } pub fn new_uninitialized(window: &Window) -> DomRoot<MouseEvent> { - reflect_dom_object(Box::new(MouseEvent::new_inherited()), - window, - MouseEventBinding::Wrap) + reflect_dom_object( + Box::new(MouseEvent::new_inherited()), + window, + MouseEventBinding::Wrap, + ) } pub fn new( @@ -77,23 +79,35 @@ impl MouseEvent { meta_key: bool, button: i16, related_target: Option<&EventTarget>, - point_in_target: Option<Point2D<f32>> + point_in_target: Option<Point2D<f32>>, ) -> DomRoot<MouseEvent> { let ev = MouseEvent::new_uninitialized(window); ev.InitMouseEvent( - type_, bool::from(can_bubble), bool::from(cancelable), - view, detail, - screen_x, screen_y, client_x, client_y, - ctrl_key, alt_key, shift_key, meta_key, - button, related_target, + type_, + bool::from(can_bubble), + bool::from(cancelable), + view, + detail, + screen_x, + screen_y, + client_x, + client_y, + ctrl_key, + alt_key, + shift_key, + meta_key, + button, + related_target, ); ev.point_in_target.set(point_in_target); ev } - pub fn Constructor(window: &Window, - type_: DOMString, - init: &MouseEventBinding::MouseEventInit) -> Fallible<DomRoot<MouseEvent>> { + pub fn Constructor( + window: &Window, + type_: DOMString, + init: &MouseEventBinding::MouseEventInit, + ) -> Fallible<DomRoot<MouseEvent>> { let bubbles = EventBubbles::from(init.parent.parent.parent.bubbles); let cancelable = EventCancelable::from(init.parent.parent.parent.cancelable); let event = MouseEvent::new( @@ -103,10 +117,17 @@ impl MouseEvent { cancelable, init.parent.parent.view.r(), init.parent.parent.detail, - init.screenX, init.screenY, - init.clientX, init.clientY, init.parent.ctrlKey, - init.parent.altKey, init.parent.shiftKey, init.parent.metaKey, - init.button, init.relatedTarget.r(), None + init.screenX, + init.screenY, + init.clientX, + init.clientY, + init.parent.ctrlKey, + init.parent.altKey, + init.parent.shiftKey, + init.parent.metaKey, + init.button, + init.relatedTarget.r(), + None, ); Ok(event) } @@ -173,7 +194,11 @@ impl MouseEventMethods for MouseEvent { // This returns the same result as current gecko. // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which fn Which(&self) -> i32 { - if PREFS.get("dom.mouseevent.which.enabled").as_boolean().unwrap_or(false) { + if PREFS + .get("dom.mouseevent.which.enabled") + .as_boolean() + .unwrap_or(false) + { (self.button.get() + 1) as i32 } else { 0 @@ -203,8 +228,13 @@ impl MouseEventMethods for MouseEvent { return; } - self.upcast::<UIEvent>() - .InitUIEvent(type_arg, can_bubble_arg, cancelable_arg, view_arg, detail_arg); + self.upcast::<UIEvent>().InitUIEvent( + type_arg, + can_bubble_arg, + cancelable_arg, + view_arg, + detail_arg, + ); self.screen_x.set(screen_x_arg); self.screen_y.set(screen_y_arg); self.client_x.set(client_x_arg); diff --git a/components/script/dom/mutationobserver.rs b/components/script/dom/mutationobserver.rs index 65f8081c900..57f5cf80168 100644 --- a/components/script/dom/mutationobserver.rs +++ b/components/script/dom/mutationobserver.rs @@ -31,10 +31,20 @@ pub struct MutationObserver { } pub enum Mutation<'a> { - Attribute { name: LocalName, namespace: Namespace, old_value: Option<DOMString> }, - CharacterData { old_value: DOMString }, - ChildList { added: Option<&'a [&'a Node]>, removed: Option<&'a [&'a Node]>, - prev: Option<&'a Node>, next: Option<&'a Node> }, + Attribute { + name: LocalName, + namespace: Namespace, + old_value: Option<DOMString>, + }, + CharacterData { + old_value: DOMString, + }, + ChildList { + added: Option<&'a [&'a Node]>, + removed: Option<&'a [&'a Node]>, + prev: Option<&'a Node>, + next: Option<&'a Node>, + }, } #[derive(JSTraceable, MallocSizeOf)] @@ -69,7 +79,10 @@ impl MutationObserver { } } - pub fn Constructor(global: &Window, callback: Rc<MutationCallback>) -> Fallible<DomRoot<MutationObserver>> { + pub fn Constructor( + global: &Window, + callback: Rc<MutationCallback>, + ) -> Fallible<DomRoot<MutationObserver>> { global.set_exists_mut_observer(); let observer = MutationObserver::new(global, callback); ScriptThread::add_mutation_observer(&*observer); @@ -101,7 +114,9 @@ impl MutationObserver { mo.record_queue.borrow_mut().clear(); // TODO: Step 5.3 Remove all transient registered observers whose observer is mo. if !queue.is_empty() { - let _ = mo.callback.Call_(&**mo, queue, &**mo, ExceptionHandling::Report); + let _ = mo + .callback + .Call_(&**mo, queue, &**mo, ExceptionHandling::Report); } } // TODO: Step 6 (slot signals) @@ -123,7 +138,11 @@ impl MutationObserver { } match attr_type { - Mutation::Attribute { ref name, ref namespace, ref old_value } => { + Mutation::Attribute { + ref name, + ref namespace, + ref old_value, + } => { // Step 3.1 if !registered.options.attributes { continue; @@ -132,8 +151,12 @@ impl MutationObserver { if *namespace != ns!() { continue; } - if !registered.options.attribute_filter.iter() - .any(|s| &**s == &**name) { + if !registered + .options + .attribute_filter + .iter() + .any(|s| &**s == &**name) + { continue; } } @@ -144,13 +167,14 @@ impl MutationObserver { None }; // Step 3.1.1 - let idx = interested_observers.iter().position(|&(ref o, _)| - &**o as *const _ == &*registered.observer as *const _); + let idx = interested_observers.iter().position(|&(ref o, _)| { + &**o as *const _ == &*registered.observer as *const _ + }); if let Some(idx) = idx { interested_observers[idx].1 = paired_string; } else { - interested_observers.push((DomRoot::from_ref(&*registered.observer), - paired_string)); + interested_observers + .push((DomRoot::from_ref(&*registered.observer), paired_string)); } }, Mutation::CharacterData { ref old_value } => { @@ -164,13 +188,14 @@ impl MutationObserver { None }; // Step 3.1.1 - let idx = interested_observers.iter().position(|&(ref o, _)| - &**o as *const _ == &*registered.observer as *const _); + let idx = interested_observers.iter().position(|&(ref o, _)| { + &**o as *const _ == &*registered.observer as *const _ + }); if let Some(idx) = idx { interested_observers[idx].1 = paired_string; } else { - interested_observers.push((DomRoot::from_ref(&*registered.observer), - paired_string)); + interested_observers + .push((DomRoot::from_ref(&*registered.observer), paired_string)); } }, Mutation::ChildList { .. } => { @@ -178,7 +203,7 @@ impl MutationObserver { continue; } interested_observers.push((DomRoot::from_ref(&*registered.observer), None)); - } + }, } } } @@ -187,7 +212,11 @@ impl MutationObserver { for (observer, paired_string) in interested_observers { // Steps 4.1-4.7 let record = match attr_type { - Mutation::Attribute { ref name, ref namespace, .. } => { + Mutation::Attribute { + ref name, + ref namespace, + .. + } => { let namespace = if *namespace != ns!() { Some(namespace) } else { @@ -197,10 +226,13 @@ impl MutationObserver { }, Mutation::CharacterData { .. } => { MutationRecord::character_data_mutated(target, paired_string) - } - Mutation::ChildList { ref added, ref removed, ref next, ref prev } => { - MutationRecord::child_list_mutated(target, *added, *removed, *next, *prev) - } + }, + Mutation::ChildList { + ref added, + ref removed, + ref next, + ref prev, + } => MutationRecord::child_list_mutated(target, *added, *removed, *next, *prev), }; // Step 4.8 observer.record_queue.borrow_mut().push(record); @@ -209,7 +241,6 @@ impl MutationObserver { // Step 5 MutationObserver::queue_mutation_observer_compound_microtask(); } - } impl MutationObserverMethods for MutationObserver { @@ -225,7 +256,8 @@ impl MutationObserverMethods for MutationObserver { // Step 1 if (options.attributeOldValue.is_some() || options.attributeFilter.is_some()) && - options.attributes.is_none() { + options.attributes.is_none() + { attributes = true; } @@ -236,29 +268,39 @@ impl MutationObserverMethods for MutationObserver { // Step 3 if !child_list && !attributes && !character_data { - return Err(Error::Type("One of childList, attributes, or characterData must be true".into())); + return Err(Error::Type( + "One of childList, attributes, or characterData must be true".into(), + )); } // Step 4 if attribute_old_value && !attributes { - return Err(Error::Type("attributeOldValue is true but attributes is false".into())); + return Err(Error::Type( + "attributeOldValue is true but attributes is false".into(), + )); } // Step 5 if options.attributeFilter.is_some() && !attributes { - return Err(Error::Type("attributeFilter is present but attributes is false".into())); + return Err(Error::Type( + "attributeFilter is present but attributes is false".into(), + )); } // Step 6 if character_data_old_value && !character_data { - return Err(Error::Type("characterDataOldValue is true but characterData is false".into())); + return Err(Error::Type( + "characterDataOldValue is true but characterData is false".into(), + )); } // Step 7 let add_new_observer = { let mut replaced = false; for registered in &mut *target.registered_mutation_observers() { - if &*registered.observer as *const MutationObserver != self as *const MutationObserver { + if &*registered.observer as *const MutationObserver != + self as *const MutationObserver + { continue; } // TODO: remove matching transient registered observers @@ -276,18 +318,20 @@ impl MutationObserverMethods for MutationObserver { // Step 8 if add_new_observer { - target.registered_mutation_observers().push(RegisteredObserver { - observer: DomRoot::from_ref(self), - options: ObserverOptions { - attributes, - attribute_old_value, - character_data, - character_data_old_value, - subtree, - attribute_filter, - child_list - }, - }); + target + .registered_mutation_observers() + .push(RegisteredObserver { + observer: DomRoot::from_ref(self), + options: ObserverOptions { + attributes, + attribute_old_value, + character_data, + character_data_old_value, + subtree, + attribute_filter, + child_list, + }, + }); self.node_list.borrow_mut().push(DomRoot::from_ref(target)); } diff --git a/components/script/dom/mutationrecord.rs b/components/script/dom/mutationrecord.rs index bc41b384a8a..a3f988e1732 100644 --- a/components/script/dom/mutationrecord.rs +++ b/components/script/dom/mutationrecord.rs @@ -40,9 +40,16 @@ impl MutationRecord { Some(DOMString::from(&**attribute_name)), attribute_namespace.map(|n| DOMString::from(&**n)), old_value, - None, None, None, None + None, + None, + None, + None, )); - reflect_dom_object(record, &*window_from_node(target), MutationRecordBinding::Wrap) + reflect_dom_object( + record, + &*window_from_node(target), + MutationRecordBinding::Wrap, + ) } pub fn character_data_mutated( @@ -53,12 +60,16 @@ impl MutationRecord { Box::new(MutationRecord::new_inherited( "characterData", target, - None, None, + None, + None, old_value, - None, None, None, None + None, + None, + None, + None, )), &*window_from_node(target), - MutationRecordBinding::Wrap + MutationRecordBinding::Wrap, ) } @@ -71,20 +82,23 @@ impl MutationRecord { ) -> DomRoot<MutationRecord> { let window = window_from_node(target); let added_nodes = added_nodes.map(|list| NodeList::new_simple_list_slice(&window, list)); - let removed_nodes = removed_nodes.map(|list| NodeList::new_simple_list_slice(&window, list)); + let removed_nodes = + removed_nodes.map(|list| NodeList::new_simple_list_slice(&window, list)); reflect_dom_object( Box::new(MutationRecord::new_inherited( "childList", target, - None, None, None, + None, + None, + None, added_nodes.as_ref().map(|list| &**list), removed_nodes.as_ref().map(|list| &**list), next_sibling, - prev_sibling + prev_sibling, )), &*window, - MutationRecordBinding::Wrap + MutationRecordBinding::Wrap, ) } @@ -158,12 +172,15 @@ impl MutationRecordMethods for MutationRecord { // https://dom.spec.whatwg.org/#dom-mutationrecord-previoussibling fn GetPreviousSibling(&self) -> Option<DomRoot<Node>> { - self.prev_sibling.as_ref().map(|node| DomRoot::from_ref(&**node)) + self.prev_sibling + .as_ref() + .map(|node| DomRoot::from_ref(&**node)) } // https://dom.spec.whatwg.org/#dom-mutationrecord-previoussibling fn GetNextSibling(&self) -> Option<DomRoot<Node>> { - self.next_sibling.as_ref().map(|node| DomRoot::from_ref(&**node)) + self.next_sibling + .as_ref() + .map(|node| DomRoot::from_ref(&**node)) } - } diff --git a/components/script/dom/namednodemap.rs b/components/script/dom/namednodemap.rs index 81540854584..c0ed5744355 100644 --- a/components/script/dom/namednodemap.rs +++ b/components/script/dom/namednodemap.rs @@ -31,8 +31,11 @@ impl NamedNodeMap { } pub fn new(window: &Window, elem: &Element) -> DomRoot<NamedNodeMap> { - reflect_dom_object(Box::new(NamedNodeMap::new_inherited(elem)), - window, NamedNodeMapBinding::Wrap) + reflect_dom_object( + Box::new(NamedNodeMap::new_inherited(elem)), + window, + NamedNodeMapBinding::Wrap, + ) } } @@ -44,7 +47,10 @@ impl NamedNodeMapMethods for NamedNodeMap { // https://dom.spec.whatwg.org/#dom-namednodemap-item fn Item(&self, index: u32) -> Option<DomRoot<Attr>> { - self.owner.attrs().get(index as usize).map(|js| DomRoot::from_ref(&**js)) + self.owner + .attrs() + .get(index as usize) + .map(|js| DomRoot::from_ref(&**js)) } // https://dom.spec.whatwg.org/#dom-namednodemap-getnameditem @@ -53,8 +59,11 @@ impl NamedNodeMapMethods for NamedNodeMap { } // https://dom.spec.whatwg.org/#dom-namednodemap-getnameditemns - fn GetNamedItemNS(&self, namespace: Option<DOMString>, local_name: DOMString) - -> Option<DomRoot<Attr>> { + fn GetNamedItemNS( + &self, + namespace: Option<DOMString>, + local_name: DOMString, + ) -> Option<DomRoot<Attr>> { let ns = namespace_from_domstring(namespace); self.owner.get_attribute(&ns, &LocalName::from(local_name)) } @@ -72,14 +81,20 @@ impl NamedNodeMapMethods for NamedNodeMap { // https://dom.spec.whatwg.org/#dom-namednodemap-removenameditem fn RemoveNamedItem(&self, name: DOMString) -> Fallible<DomRoot<Attr>> { let name = self.owner.parsed_name(name); - self.owner.remove_attribute_by_name(&name).ok_or(Error::NotFound) + self.owner + .remove_attribute_by_name(&name) + .ok_or(Error::NotFound) } // https://dom.spec.whatwg.org/#dom-namednodemap-removenameditemns - fn RemoveNamedItemNS(&self, namespace: Option<DOMString>, local_name: DOMString) - -> Fallible<DomRoot<Attr>> { + fn RemoveNamedItemNS( + &self, + namespace: Option<DOMString>, + local_name: DOMString, + ) -> Fallible<DomRoot<Attr>> { let ns = namespace_from_domstring(namespace); - self.owner.remove_attribute(&ns, &LocalName::from(local_name)) + self.owner + .remove_attribute(&ns, &LocalName::from(local_name)) .ok_or(Error::NotFound) } @@ -95,12 +110,12 @@ impl NamedNodeMapMethods for NamedNodeMap { // https://heycam.github.io/webidl/#dfn-supported-property-names fn SupportedPropertyNames(&self) -> Vec<DOMString> { - let mut names = vec!(); + let mut names = vec![]; let html_element_in_html_document = self.owner.html_element_in_html_document(); for attr in self.owner.attrs().iter() { let s = &**attr.name(); if html_element_in_html_document && !s.bytes().all(|b| b.to_ascii_lowercase() == b) { - continue + continue; } if !names.iter().any(|name| &*name == s) { diff --git a/components/script/dom/navigator.rs b/components/script/dom/navigator.rs index ea50d3b2db6..486692062e4 100644 --- a/components/script/dom/navigator.rs +++ b/components/script/dom/navigator.rs @@ -48,9 +48,11 @@ impl Navigator { } pub fn new(window: &Window) -> DomRoot<Navigator> { - reflect_dom_object(Box::new(Navigator::new_inherited()), - window, - NavigatorBinding::Wrap) + reflect_dom_object( + Box::new(Navigator::new_inherited()), + window, + NavigatorBinding::Wrap, + ) } } @@ -107,7 +109,8 @@ impl NavigatorMethods for Navigator { // https://html.spec.whatwg.org/multipage/#dom-navigator-mimetypes fn MimeTypes(&self) -> DomRoot<MimeTypeArray> { - self.mime_types.or_init(|| MimeTypeArray::new(&self.global())) + self.mime_types + .or_init(|| MimeTypeArray::new(&self.global())) } // https://html.spec.whatwg.org/multipage/#dom-navigator-javaenabled @@ -117,9 +120,8 @@ impl NavigatorMethods for Navigator { // https://w3c.github.io/ServiceWorker/#navigator-service-worker-attribute fn ServiceWorker(&self) -> DomRoot<ServiceWorkerContainer> { - self.service_worker.or_init(|| { - ServiceWorkerContainer::new(&self.global()) - }) + self.service_worker + .or_init(|| ServiceWorkerContainer::new(&self.global())) } // https://html.spec.whatwg.org/multipage/#dom-navigator-cookieenabled @@ -129,9 +131,9 @@ impl NavigatorMethods for Navigator { // https://www.w3.org/TR/gamepad/#navigator-interface-extension fn GetGamepads(&self) -> DomRoot<GamepadList> { - let root = self.gamepads.or_init(|| { - GamepadList::new(&self.global(), &[]) - }); + let root = self + .gamepads + .or_init(|| GamepadList::new(&self.global(), &[])); let vr_gamepads = self.Vr().get_gamepads(); root.add_if_not_exists(&vr_gamepads); @@ -140,7 +142,8 @@ impl NavigatorMethods for Navigator { } // https://w3c.github.io/permissions/#navigator-and-workernavigator-extension fn Permissions(&self) -> DomRoot<Permissions> { - self.permissions.or_init(|| Permissions::new(&self.global())) + self.permissions + .or_init(|| Permissions::new(&self.global())) } // https://w3c.github.io/webvr/spec/1.1/#navigator-getvrdisplays-attribute diff --git a/components/script/dom/node.rs b/components/script/dom/node.rs index c94f590c42b..edb49a4834a 100644 --- a/components/script/dom/node.rs +++ b/components/script/dom/node.rs @@ -200,7 +200,7 @@ impl Drop for Node { #[derive(Clone, Copy, MallocSizeOf)] enum SuppressObserver { Suppressed, - Unsuppressed + Unsuppressed, } impl Node { @@ -209,7 +209,11 @@ impl Node { debug_assert!(thread_state::get().is_script()); let win = window_from_node(self); self.style_and_layout_data.set(None); - if win.layout_chan().send(Msg::ReapStyleAndLayoutData(data)).is_err() { + if win + .layout_chan() + .send(Msg::ReapStyleAndLayoutData(data)) + .is_err() + { warn!("layout thread unreachable - leaking layout data"); } } @@ -246,7 +250,7 @@ impl Node { assert!(last_child.next_sibling.get().is_none()); last_child.next_sibling.set(Some(new_child)); new_child.prev_sibling.set(Some(&last_child)); - } + }, } self.last_child.set(Some(new_child)); @@ -274,19 +278,19 @@ impl Node { match prev_sibling { None => { self.first_child.set(child.next_sibling.get().r()); - } + }, Some(ref prev_sibling) => { prev_sibling.next_sibling.set(child.next_sibling.get().r()); - } + }, } let next_sibling = child.GetNextSibling(); match next_sibling { None => { self.last_child.set(child.prev_sibling.get().r()); - } + }, Some(ref next_sibling) => { next_sibling.prev_sibling.set(child.prev_sibling.get().r()); - } + }, } let context = UnbindContext::new(self, prev_sibling.r(), cached_index); @@ -298,9 +302,13 @@ impl Node { for node in child.traverse_preorder() { // Out-of-document elements never have the descendants flag set. - node.set_flag(NodeFlags::IS_IN_DOC | NodeFlags::HAS_DIRTY_DESCENDANTS | - NodeFlags::HAS_SNAPSHOT | NodeFlags::HANDLED_SNAPSHOT, - false); + node.set_flag( + NodeFlags::IS_IN_DOC | + NodeFlags::HAS_DIRTY_DESCENDANTS | + NodeFlags::HAS_SNAPSHOT | + NodeFlags::HANDLED_SNAPSHOT, + false, + ); } for node in child.traverse_preorder() { // This needs to be in its own loop, because unbind_from_tree may @@ -310,7 +318,11 @@ impl Node { node.style_and_layout_data.get().map(|d| node.dispose(d)); // https://dom.spec.whatwg.org/#concept-node-remove step 14 if let Some(element) = node.as_custom_element() { - ScriptThread::enqueue_callback_reaction(&*element, CallbackReaction::Disconnected, None); + ScriptThread::enqueue_callback_reaction( + &*element, + CallbackReaction::Disconnected, + None, + ); } } } @@ -320,12 +332,13 @@ impl Node { } pub fn as_custom_element(&self) -> Option<DomRoot<Element>> { - self.downcast::<Element>() - .and_then(|element| if element.get_custom_element_definition().is_some() { + self.downcast::<Element>().and_then(|element| { + if element.get_custom_element_definition().is_some() { Some(DomRoot::from_ref(element)) } else { None - }) + } + }) } } @@ -335,8 +348,7 @@ pub struct QuerySelectorIterator { } impl<'a> QuerySelectorIterator { - fn new(iter: TreeIterator, selectors: SelectorList<SelectorImpl>) - -> QuerySelectorIterator { + fn new(iter: TreeIterator, selectors: SelectorList<SelectorImpl>) -> QuerySelectorIterator { QuerySelectorIterator { selectors: selectors, iterator: iter, @@ -350,24 +362,29 @@ impl<'a> Iterator for QuerySelectorIterator { fn next(&mut self) -> Option<DomRoot<Node>> { let selectors = &self.selectors; - self.iterator.by_ref().filter_map(|node| { - // TODO(cgaebel): Is it worth it to build a bloom filter here - // (instead of passing `None`)? Probably. - // - // FIXME(bholley): Consider an nth-index cache here. - let mut ctx = MatchingContext::new(MatchingMode::Normal, None, None, - node.owner_doc().quirks_mode()); - if let Some(element) = DomRoot::downcast(node) { - if matches_selector_list(selectors, &element, &mut ctx) { - return Some(DomRoot::upcast(element)); + self.iterator + .by_ref() + .filter_map(|node| { + // TODO(cgaebel): Is it worth it to build a bloom filter here + // (instead of passing `None`)? Probably. + // + // FIXME(bholley): Consider an nth-index cache here. + let mut ctx = MatchingContext::new( + MatchingMode::Normal, + None, + None, + node.owner_doc().quirks_mode(), + ); + if let Some(element) = DomRoot::downcast(node) { + if matches_selector_list(selectors, &element, &mut ctx) { + return Some(DomRoot::upcast(element)); + } } - } - None - }).next() + None + }).next() } } - impl Node { pub fn teardown(&self) { self.style_and_layout_data.get().map(|d| self.dispose(d)); @@ -389,14 +406,14 @@ impl Node { /// Return all registered mutation observers for this node. pub fn registered_mutation_observers(&self) -> RefMut<Vec<RegisteredObserver>> { - self.mutation_observers.borrow_mut() + self.mutation_observers.borrow_mut() } /// Removes the mutation observer for a given node. pub fn remove_mutation_observer(&self, observer: &MutationObserver) { - self.mutation_observers.borrow_mut().retain(|reg_obs| { - &*reg_obs.observer != observer - }) + self.mutation_observers + .borrow_mut() + .retain(|reg_obs| &*reg_obs.observer != observer) } /// Dumps the subtree rooted at this node, for debugging. @@ -441,9 +458,7 @@ impl Node { pub fn len(&self) -> u32 { match self.type_id() { NodeTypeId::DocumentType => 0, - NodeTypeId::CharacterData(_) => { - self.downcast::<CharacterData>().unwrap().Length() - }, + NodeTypeId::CharacterData(_) => self.downcast::<CharacterData>().unwrap().Length(), _ => self.children_count(), } } @@ -510,7 +525,10 @@ impl Node { // the document's version, but we do have to deal with the case where the node has moved // document, so may have a higher version count than its owning document. let doc: DomRoot<Node> = DomRoot::upcast(self.owner_doc()); - let version = cmp::max(self.inclusive_descendants_version(), doc.inclusive_descendants_version()) + 1; + let version = cmp::max( + self.inclusive_descendants_version(), + doc.inclusive_descendants_version(), + ) + 1; for ancestor in self.inclusive_ancestors() { ancestor.inclusive_descendants_version.set(version); } @@ -524,10 +542,14 @@ impl Node { } match self.type_id() { - NodeTypeId::CharacterData(CharacterDataTypeId::Text) => - self.parent_node.get().unwrap().downcast::<Element>().unwrap().restyle(damage), - NodeTypeId::Element(_) => - self.downcast::<Element>().unwrap().restyle(damage), + NodeTypeId::CharacterData(CharacterDataTypeId::Text) => self + .parent_node + .get() + .unwrap() + .downcast::<Element>() + .unwrap() + .restyle(damage), + NodeTypeId::Element(_) => self.downcast::<Element>().unwrap().restyle(damage), _ => {}, }; } @@ -542,14 +564,14 @@ impl Node { TreeIterator::new(self) } - pub fn inclusively_following_siblings(&self) -> impl Iterator<Item=DomRoot<Node>> { + pub fn inclusively_following_siblings(&self) -> impl Iterator<Item = DomRoot<Node>> { SimpleNodeIterator { current: Some(DomRoot::from_ref(self)), next_node: |n| n.GetNextSibling(), } } - pub fn inclusively_preceding_siblings(&self) -> impl Iterator<Item=DomRoot<Node>> { + pub fn inclusively_preceding_siblings(&self) -> impl Iterator<Item = DomRoot<Node>> { SimpleNodeIterator { current: Some(DomRoot::from_ref(self)), next_node: |n| n.GetPreviousSibling(), @@ -564,14 +586,14 @@ impl Node { parent.ancestors().any(|ancestor| &*ancestor == self) } - pub fn following_siblings(&self) -> impl Iterator<Item=DomRoot<Node>> { + pub fn following_siblings(&self) -> impl Iterator<Item = DomRoot<Node>> { SimpleNodeIterator { current: self.GetNextSibling(), next_node: |n| n.GetNextSibling(), } } - pub fn preceding_siblings(&self) -> impl Iterator<Item=DomRoot<Node>> { + pub fn preceding_siblings(&self) -> impl Iterator<Item = DomRoot<Node>> { SimpleNodeIterator { current: self.GetPreviousSibling(), next_node: |n| n.GetPreviousSibling(), @@ -592,7 +614,7 @@ impl Node { } } - pub fn descending_last_children(&self) -> impl Iterator<Item=DomRoot<Node>> { + pub fn descending_last_children(&self) -> impl Iterator<Item = DomRoot<Node>> { SimpleNodeIterator { current: self.GetLastChild(), next_node: |n| n.GetLastChild(), @@ -600,7 +622,10 @@ impl Node { } pub fn is_parent_of(&self, child: &Node) -> bool { - child.parent_node.get().map_or(false, |parent| &*parent == self) + child + .parent_node + .get() + .map_or(false, |parent| &*parent == self) } pub fn to_trusted_node_address(&self) -> TrustedNodeAddress { @@ -610,8 +635,7 @@ impl Node { /// Returns the rendered bounding content box if the element is rendered, /// and none otherwise. pub fn bounding_content_box(&self) -> Option<Rect<Au>> { - window_from_node(self) - .content_box_query(self.to_trusted_node_address()) + window_from_node(self).content_box_query(self.to_trusted_node_address()) } pub fn bounding_content_box_or_zero(&self) -> Rect<Au> { @@ -636,23 +660,30 @@ impl Node { let html_element = document.GetDocumentElement(); - let is_body_element = self.downcast::<HTMLBodyElement>() - .map_or(false, |e| e.is_the_html_body_element()); + let is_body_element = self + .downcast::<HTMLBodyElement>() + .map_or(false, |e| e.is_the_html_body_element()); let scroll_area = window.scroll_area_query(self.to_trusted_node_address()); - match (document != window.Document(), is_body_element, document.quirks_mode(), - html_element.r() == self.downcast::<Element>()) { + match ( + document != window.Document(), + is_body_element, + document.quirks_mode(), + html_element.r() == self.downcast::<Element>(), + ) { // Step 2 && Step 5 (true, _, _, _) | (_, false, QuirksMode::Quirks, true) => Rect::zero(), // Step 6 && Step 7 - (false, false, _, true) | (false, true, QuirksMode::Quirks, _) => { - Rect::new(Point2D::new(window.ScrollX(), window.ScrollY()), - Size2D::new(cmp::max(window.InnerWidth(), scroll_area.size.width), - cmp::max(window.InnerHeight(), scroll_area.size.height))) - }, + (false, false, _, true) | (false, true, QuirksMode::Quirks, _) => Rect::new( + Point2D::new(window.ScrollX(), window.ScrollY()), + Size2D::new( + cmp::max(window.InnerWidth(), scroll_area.size.width), + cmp::max(window.InnerHeight(), scroll_area.size.height), + ), + ), // Step 9 - _ => scroll_area + _ => scroll_area, } } @@ -765,12 +796,17 @@ impl Node { // Step 3. Ok(selectors) => { // FIXME(bholley): Consider an nth-index cache here. - let mut ctx = MatchingContext::new(MatchingMode::Normal, None, None, - self.owner_doc().quirks_mode()); - Ok(self.traverse_preorder().filter_map(DomRoot::downcast).find(|element| { - matches_selector_list(&selectors, element, &mut ctx) - })) - } + let mut ctx = MatchingContext::new( + MatchingMode::Normal, + None, + None, + self.owner_doc().quirks_mode(), + ); + Ok(self + .traverse_preorder() + .filter_map(DomRoot::downcast) + .find(|element| matches_selector_list(&selectors, element, &mut ctx))) + }, } } @@ -778,8 +814,7 @@ impl Node { /// Get an iterator over all nodes which match a set of selectors /// Be careful not to do anything which may manipulate the DOM tree /// whilst iterating, otherwise the iterator may be invalidated. - pub fn query_selector_iter(&self, selectors: DOMString) - -> Fallible<QuerySelectorIterator> { + pub fn query_selector_iter(&self, selectors: DOMString) -> Fallible<QuerySelectorIterator> { // Step 1. match SelectorParser::parse_author_origin_no_namespace(&selectors) { // Step 2. @@ -790,7 +825,7 @@ impl Node { // Skip the root of the tree. assert!(&*descendants.next().unwrap() == self); Ok(QuerySelectorIterator::new(descendants, selectors)) - } + }, } } @@ -802,14 +837,14 @@ impl Node { Ok(NodeList::new_simple_list(&window, iter)) } - pub fn ancestors(&self) -> impl Iterator<Item=DomRoot<Node>> { + pub fn ancestors(&self) -> impl Iterator<Item = DomRoot<Node>> { SimpleNodeIterator { current: self.GetParentNode(), next_node: |n| n.GetParentNode(), } } - pub fn inclusive_ancestors(&self) -> impl Iterator<Item=DomRoot<Node>> { + pub fn inclusive_ancestors(&self) -> impl Iterator<Item = DomRoot<Node>> { SimpleNodeIterator { current: Some(DomRoot::from_ref(self)), next_node: |n| n.GetParentNode(), @@ -832,22 +867,24 @@ impl Node { self.is_in_doc() && self.owner_doc().browsing_context().is_some() } - pub fn children(&self) -> impl Iterator<Item=DomRoot<Node>> { + pub fn children(&self) -> impl Iterator<Item = DomRoot<Node>> { SimpleNodeIterator { current: self.GetFirstChild(), next_node: |n| n.GetNextSibling(), } } - pub fn rev_children(&self) -> impl Iterator<Item=DomRoot<Node>> { + pub fn rev_children(&self) -> impl Iterator<Item = DomRoot<Node>> { SimpleNodeIterator { current: self.GetLastChild(), next_node: |n| n.GetPreviousSibling(), } } - pub fn child_elements(&self) -> impl Iterator<Item=DomRoot<Element>> { - self.children().filter_map(DomRoot::downcast as fn(_) -> _).peekable() + pub fn child_elements(&self) -> impl Iterator<Item = DomRoot<Element>> { + self.children() + .filter_map(DomRoot::downcast as fn(_) -> _) + .peekable() } pub fn remove_self(&self) { @@ -865,7 +902,9 @@ impl Node { NodeInfo { uniqueId: self.unique_id(), baseURI: base_uri, - parent: self.GetParentNode().map_or("".to_owned(), |node| node.unique_id()), + parent: self + .GetParentNode() + .map_or("".to_owned(), |node| node.unique_id()), nodeType: self.NodeType(), namespaceURI: String::new(), //FIXME nodeName: String::from(self.NodeName()), @@ -877,10 +916,10 @@ impl Node { systemId: String::new(), attrs: self.downcast().map(Element::summarize).unwrap_or(vec![]), - isDocumentElement: - self.owner_doc() - .GetDocumentElement() - .map_or(false, |elem| elem.upcast::<Node>() == self), + isDocumentElement: self + .owner_doc() + .GetDocumentElement() + .map_or(false, |elem| elem.upcast::<Node>() == self), shortValue: self.GetNodeValue().map(String::from).unwrap_or_default(), //FIXME: truncate incompleteValue: false, //FIXME: reflect truncation @@ -888,10 +927,16 @@ impl Node { } /// Used by `HTMLTableSectionElement::InsertRow` and `HTMLTableRowElement::InsertCell` - pub fn insert_cell_or_row<F, G, I>(&self, index: i32, get_items: F, new_child: G) -> Fallible<DomRoot<HTMLElement>> - where F: Fn() -> DomRoot<HTMLCollection>, - G: Fn() -> DomRoot<I>, - I: DerivedFrom<Node> + DerivedFrom<HTMLElement> + DomObject, + pub fn insert_cell_or_row<F, G, I>( + &self, + index: i32, + get_items: F, + new_child: G, + ) -> Fallible<DomRoot<HTMLElement>> + where + F: Fn() -> DomRoot<HTMLCollection>, + G: Fn() -> DomRoot<I>, + I: DerivedFrom<Node> + DerivedFrom<HTMLElement> + DomObject, { if index < -1 { return Err(Error::IndexSize); @@ -899,18 +944,19 @@ impl Node { let tr = new_child(); - { let tr_node = tr.upcast::<Node>(); if index == -1 { self.InsertBefore(tr_node, None)?; } else { let items = get_items(); - let node = match items.elements_iter() - .map(DomRoot::upcast::<Node>) - .map(Some) - .chain(iter::once(None)) - .nth(index as usize) { + let node = match items + .elements_iter() + .map(DomRoot::upcast::<Node>) + .map(Some) + .chain(iter::once(None)) + .nth(index as usize) + { None => return Err(Error::IndexSize), Some(node) => node, }; @@ -922,18 +968,26 @@ impl Node { } /// Used by `HTMLTableSectionElement::DeleteRow` and `HTMLTableRowElement::DeleteCell` - pub fn delete_cell_or_row<F, G>(&self, index: i32, get_items: F, is_delete_type: G) -> ErrorResult - where F: Fn() -> DomRoot<HTMLCollection>, - G: Fn(&Element) -> bool + pub fn delete_cell_or_row<F, G>( + &self, + index: i32, + get_items: F, + is_delete_type: G, + ) -> ErrorResult + where + F: Fn() -> DomRoot<HTMLCollection>, + G: Fn(&Element) -> bool, { let element = match index { index if index < -1 => return Err(Error::IndexSize), -1 => { let last_child = self.upcast::<Node>().GetLastChild(); - match last_child.and_then(|node| node.inclusively_preceding_siblings() - .filter_map(DomRoot::downcast::<Element>) - .filter(|elem| is_delete_type(elem)) - .next()) { + match last_child.and_then(|node| { + node.inclusively_preceding_siblings() + .filter_map(DomRoot::downcast::<Element>) + .filter(|elem| is_delete_type(elem)) + .next() + }) { Some(element) => element, None => return Ok(()), } @@ -973,17 +1027,15 @@ impl Node { } } - /// Iterate through `nodes` until we find a `Node` that is not in `not_in` fn first_node_not_in<I>(mut nodes: I, not_in: &[NodeOrString]) -> Option<DomRoot<Node>> - where I: Iterator<Item=DomRoot<Node>> +where + I: Iterator<Item = DomRoot<Node>>, { nodes.find(|node| { - not_in.iter().all(|n| { - match *n { - NodeOrString::Node(ref n) => n != node, - _ => true, - } + not_in.iter().all(|n| match *n { + NodeOrString::Node(ref n) => n != node, + _ => true, }) }) } @@ -991,12 +1043,14 @@ fn first_node_not_in<I>(mut nodes: I, not_in: &[NodeOrString]) -> Option<DomRoot /// If the given untrusted node address represents a valid DOM node in the given runtime, /// returns it. #[allow(unsafe_code)] -pub unsafe fn from_untrusted_node_address(_runtime: *mut JSRuntime, candidate: UntrustedNodeAddress) - -> DomRoot<Node> { +pub unsafe fn from_untrusted_node_address( + _runtime: *mut JSRuntime, + candidate: UntrustedNodeAddress, +) -> DomRoot<Node> { // https://github.com/servo/servo/issues/6383 let candidate: uintptr_t = mem::transmute(candidate.0); -// let object: *mut JSObject = jsfriendapi::bindgen::JS_GetAddressableObject(runtime, -// candidate); + // let object: *mut JSObject = jsfriendapi::bindgen::JS_GetAddressableObject(runtime, + // candidate); let object: *mut JSObject = mem::transmute(candidate); if object.is_null() { panic!("Attempted to create a `Dom<Node>` from an invalid pointer!") @@ -1084,7 +1138,10 @@ impl LayoutNodeHelpers for LayoutDom<Node> { #[inline] #[allow(unsafe_code)] unsafe fn owner_doc_for_layout(&self) -> LayoutDom<Document> { - (*self.unsafe_get()).owner_doc.get_inner_as_layout().unwrap() + (*self.unsafe_get()) + .owner_doc + .get_inner_as_layout() + .unwrap() } #[inline] @@ -1189,31 +1246,29 @@ impl LayoutNodeHelpers for LayoutDom<Node> { } fn svg_data(&self) -> Option<SVGSVGData> { - self.downcast::<SVGSVGElement>() - .map(|svg| svg.data()) + self.downcast::<SVGSVGElement>().map(|svg| svg.data()) } fn iframe_browsing_context_id(&self) -> Option<BrowsingContextId> { - let iframe_element = self.downcast::<HTMLIFrameElement>() + let iframe_element = self + .downcast::<HTMLIFrameElement>() .expect("not an iframe element!"); iframe_element.browsing_context_id() } fn iframe_pipeline_id(&self) -> Option<PipelineId> { - let iframe_element = self.downcast::<HTMLIFrameElement>() + let iframe_element = self + .downcast::<HTMLIFrameElement>() .expect("not an iframe element!"); iframe_element.pipeline_id() } #[allow(unsafe_code)] fn opaque(&self) -> OpaqueNode { - unsafe { - OpaqueNode(self.get_jsobject() as usize) - } + unsafe { OpaqueNode(self.get_jsobject() as usize) } } } - // // Iteration and traversal // @@ -1238,7 +1293,7 @@ impl FollowingNodeIterator { if let Some(next_sibling) = current.GetNextSibling() { self.current = Some(next_sibling); - return current.GetNextSibling() + return current.GetNextSibling(); } for ancestor in current.inclusive_ancestors() { @@ -1247,7 +1302,7 @@ impl FollowingNodeIterator { } if let Some(next_sibling) = ancestor.GetNextSibling() { self.current = Some(next_sibling); - return ancestor.GetNextSibling() + return ancestor.GetNextSibling(); } } self.current = None; @@ -1264,7 +1319,7 @@ impl Iterator for FollowingNodeIterator { if let Some(first_child) = current.GetFirstChild() { self.current = Some(first_child); - return current.GetFirstChild() + return current.GetFirstChild(); } self.next_skipping_children_impl(current) @@ -1301,14 +1356,16 @@ impl Iterator for PrecedingNodeIterator { } struct SimpleNodeIterator<I> - where I: Fn(&Node) -> Option<DomRoot<Node>> +where + I: Fn(&Node) -> Option<DomRoot<Node>>, { current: Option<DomRoot<Node>>, next_node: I, } impl<I> Iterator for SimpleNodeIterator<I> - where I: Fn(&Node) -> Option<DomRoot<Node>> +where + I: Fn(&Node) -> Option<DomRoot<Node>>, { type Item = DomRoot<Node>; @@ -1375,18 +1432,21 @@ impl Iterator for TreeIterator { #[derive(Clone, Copy, MallocSizeOf, PartialEq)] pub enum CloneChildrenFlag { CloneChildren, - DoNotCloneChildren + DoNotCloneChildren, } -fn as_uintptr<T>(t: &T) -> uintptr_t { t as *const T as uintptr_t } +fn as_uintptr<T>(t: &T) -> uintptr_t { + t as *const T as uintptr_t +} impl Node { pub fn reflect_node<N>( - node: Box<N>, - document: &Document, - wrap_fn: unsafe extern "Rust" fn(*mut JSContext, &GlobalScope, Box<N>) -> DomRoot<N>) - -> DomRoot<N> - where N: DerivedFrom<Node> + DomObject + node: Box<N>, + document: &Document, + wrap_fn: unsafe fn(*mut JSContext, &GlobalScope, Box<N>) -> DomRoot<N>, + ) -> DomRoot<N> + where + N: DerivedFrom<Node> + DomObject, { let window = document.window(); reflect_dom_object(node, window, wrap_fn) @@ -1438,10 +1498,16 @@ impl Node { for descendant in node.traverse_preorder() { descendant.set_owner_doc(document); } - for descendant in node.traverse_preorder().filter_map(|d| d.as_custom_element()) { + for descendant in node + .traverse_preorder() + .filter_map(|d| d.as_custom_element()) + { // Step 3.2. - ScriptThread::enqueue_callback_reaction(&*descendant, - CallbackReaction::Adopted(old_doc.clone(), DomRoot::from_ref(document)), None); + ScriptThread::enqueue_callback_reaction( + &*descendant, + CallbackReaction::Adopted(old_doc.clone(), DomRoot::from_ref(document)), + None, + ); } for descendant in node.traverse_preorder() { // Step 3.3. @@ -1451,15 +1517,15 @@ impl Node { } // https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity - pub fn ensure_pre_insertion_validity(node: &Node, - parent: &Node, - child: Option<&Node>) -> ErrorResult { + pub fn ensure_pre_insertion_validity( + node: &Node, + parent: &Node, + child: Option<&Node>, + ) -> ErrorResult { // Step 1. match parent.type_id() { - NodeTypeId::Document(_) | - NodeTypeId::DocumentFragment | - NodeTypeId::Element(..) => (), - _ => return Err(Error::HierarchyRequest) + NodeTypeId::Document(_) | NodeTypeId::DocumentFragment | NodeTypeId::Element(..) => (), + _ => return Err(Error::HierarchyRequest), } // Step 2. @@ -1490,7 +1556,7 @@ impl Node { NodeTypeId::Element(_) | NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) | NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => (), - NodeTypeId::Document(_) => return Err(Error::HierarchyRequest) + NodeTypeId::Document(_) => return Err(Error::HierarchyRequest), } // Step 6. @@ -1499,9 +1565,7 @@ impl Node { // Step 6.1 NodeTypeId::DocumentFragment => { // Step 6.1.1(b) - if node.children() - .any(|c| c.is::<Text>()) - { + if node.children().any(|c| c.is::<Text>()) { return Err(Error::HierarchyRequest); } match node.child_elements().count() { @@ -1512,9 +1576,11 @@ impl Node { return Err(Error::HierarchyRequest); } if let Some(child) = child { - if child.inclusively_following_siblings() - .any(|child| child.is_doctype()) { - return Err(Error::HierarchyRequest); + if child + .inclusively_following_siblings() + .any(|child| child.is_doctype()) + { + return Err(Error::HierarchyRequest); } } }, @@ -1528,24 +1594,25 @@ impl Node { return Err(Error::HierarchyRequest); } if let Some(ref child) = child { - if child.inclusively_following_siblings() - .any(|child| child.is_doctype()) { - return Err(Error::HierarchyRequest); + if child + .inclusively_following_siblings() + .any(|child| child.is_doctype()) + { + return Err(Error::HierarchyRequest); } } }, // Step 6.3 NodeTypeId::DocumentType => { - if parent.children() - .any(|c| c.is_doctype()) - { + if parent.children().any(|c| c.is_doctype()) { return Err(Error::HierarchyRequest); } match child { Some(child) => { - if parent.children() - .take_while(|c| &**c != child) - .any(|c| c.is::<Element>()) + if parent + .children() + .take_while(|c| &**c != child) + .any(|c| c.is::<Element>()) { return Err(Error::HierarchyRequest); } @@ -1565,8 +1632,7 @@ impl Node { } // https://dom.spec.whatwg.org/#concept-node-pre-insert - pub fn pre_insert(node: &Node, parent: &Node, child: Option<&Node>) - -> Fallible<DomRoot<Node>> { + pub fn pre_insert(node: &Node, parent: &Node, child: Option<&Node>) -> Fallible<DomRoot<Node>> { // Step 1. Node::ensure_pre_insertion_validity(node, parent, child)?; @@ -1577,7 +1643,7 @@ impl Node { reference_child_root = node.GetNextSibling(); reference_child_root.r() }, - _ => child + _ => child, }; // Step 4. @@ -1585,17 +1651,24 @@ impl Node { Node::adopt(node, &document); // Step 5. - Node::insert(node, parent, reference_child, SuppressObserver::Unsuppressed); + Node::insert( + node, + parent, + reference_child, + SuppressObserver::Unsuppressed, + ); // Step 6. Ok(DomRoot::from_ref(node)) } // https://dom.spec.whatwg.org/#concept-node-insert - fn insert(node: &Node, - parent: &Node, - child: Option<&Node>, - suppress_observers: SuppressObserver) { + fn insert( + node: &Node, + parent: &Node, + child: Option<&Node>, + suppress_observers: SuppressObserver, + ) { debug_assert!(&*node.owner_doc() == &*parent.owner_doc()); debug_assert!(child.map_or(true, |child| Some(parent) == child.GetParentNode().r())); @@ -1639,11 +1712,9 @@ impl Node { }; // Step 6. let previous_sibling = match suppress_observers { - SuppressObserver::Unsuppressed => { - match child { - Some(child) => child.GetPreviousSibling(), - None => parent.GetLastChild(), - } + SuppressObserver::Unsuppressed => match child { + Some(child) => child.GetPreviousSibling(), + None => parent.GetLastChild(), }, SuppressObserver::Suppressed => None, }; @@ -1652,12 +1723,19 @@ impl Node { // Step 7.1. parent.add_child(*kid, child); // Step 7.7. - for descendant in kid.traverse_preorder().filter_map(DomRoot::downcast::<Element>) { + for descendant in kid + .traverse_preorder() + .filter_map(DomRoot::downcast::<Element>) + { // Step 7.7.2. if descendant.is_connected() { if descendant.get_custom_element_definition().is_some() { // Step 7.7.2.1. - ScriptThread::enqueue_callback_reaction(&*descendant, CallbackReaction::Connected, None); + ScriptThread::enqueue_callback_reaction( + &*descendant, + CallbackReaction::Connected, + None, + ); } else { // Step 7.7.2.2. try_upgrade_element(&*descendant); @@ -1666,8 +1744,11 @@ impl Node { } } if let SuppressObserver::Unsuppressed = suppress_observers { - vtable_for(&parent).children_changed( - &ChildrenMutation::insert(previous_sibling.r(), new_nodes, child)); + vtable_for(&parent).children_changed(&ChildrenMutation::insert( + previous_sibling.r(), + new_nodes, + child, + )); let mutation = Mutation::ChildList { added: Some(new_nodes), @@ -1708,8 +1789,10 @@ impl Node { Node::insert(node, parent, None, SuppressObserver::Suppressed); } // Step 6. - vtable_for(&parent).children_changed( - &ChildrenMutation::replace_all(removed_nodes.r(), added_nodes)); + vtable_for(&parent).children_changed(&ChildrenMutation::replace_all( + removed_nodes.r(), + added_nodes, + )); if !removed_nodes.is_empty() || !added_nodes.is_empty() { let mutation = Mutation::ChildList { @@ -1728,7 +1811,7 @@ impl Node { match child.GetParentNode() { Some(ref node) if &**node != parent => return Err(Error::NotFound), None => return Err(Error::NotFound), - _ => () + _ => (), } // Step 2. @@ -1740,7 +1823,10 @@ impl Node { // https://dom.spec.whatwg.org/#concept-node-remove fn remove(node: &Node, parent: &Node, suppress_observers: SuppressObserver) { - assert!(node.GetParentNode().map_or(false, |node_parent| &*node_parent == parent)); + assert!( + node.GetParentNode() + .map_or(false, |node_parent| &*node_parent == parent) + ); let cached_index = { if parent.ranges.is_empty() { None @@ -1766,10 +1852,12 @@ impl Node { // Step 11. transient registered observers // Step 12. if let SuppressObserver::Unsuppressed = suppress_observers { - vtable_for(&parent).children_changed( - &ChildrenMutation::replace(old_previous_sibling.r(), - &Some(&node), &[], - old_next_sibling.r())); + vtable_for(&parent).children_changed(&ChildrenMutation::replace( + old_previous_sibling.r(), + &Some(&node), + &[], + old_next_sibling.r(), + )); let removed = [node]; let mutation = Mutation::ChildList { @@ -1783,12 +1871,15 @@ impl Node { } // https://dom.spec.whatwg.org/#concept-node-clone - pub fn clone(node: &Node, maybe_doc: Option<&Document>, - clone_children: CloneChildrenFlag) -> DomRoot<Node> { + pub fn clone( + node: &Node, + maybe_doc: Option<&Document>, + clone_children: CloneChildrenFlag, + ) -> DomRoot<Node> { // Step 1. let document = match maybe_doc { Some(doc) => DomRoot::from_ref(doc), - None => node.owner_doc() + None => node.owner_doc(), }; // Step 2. @@ -1796,10 +1887,12 @@ impl Node { let copy: DomRoot<Node> = match node.type_id() { NodeTypeId::DocumentType => { let doctype = node.downcast::<DocumentType>().unwrap(); - let doctype = DocumentType::new(doctype.name().clone(), - Some(doctype.public_id().clone()), - Some(doctype.system_id().clone()), - &document); + let doctype = DocumentType::new( + doctype.name().clone(), + Some(doctype.public_id().clone()), + Some(doctype.system_id().clone()), + &document, + ); DomRoot::upcast::<Node>(doctype) }, NodeTypeId::DocumentFragment => { @@ -1819,14 +1912,22 @@ impl Node { }; let window = document.window(); let loader = DocumentLoader::new(&*document.loader()); - let document = Document::new(window, HasBrowsingContext::No, - Some(document.url()), - // https://github.com/whatwg/dom/issues/378 - document.origin().clone(), - is_html_doc, None, - None, DocumentActivity::Inactive, - DocumentSource::NotFromParser, loader, - None, None, Default::default()); + let document = Document::new( + window, + HasBrowsingContext::No, + Some(document.url()), + // https://github.com/whatwg/dom/issues/378 + document.origin().clone(), + is_html_doc, + None, + None, + DocumentActivity::Inactive, + DocumentSource::NotFromParser, + loader, + None, + None, + Default::default(), + ); DomRoot::upcast::<Node>(document) }, NodeTypeId::Element(..) => { @@ -1834,13 +1935,15 @@ impl Node { let name = QualName { prefix: element.prefix().as_ref().map(|p| Prefix::from(&**p)), ns: element.namespace().clone(), - local: element.local_name().clone() + local: element.local_name().clone(), }; - let element = Element::create(name, - element.get_is(), - &document, - ElementCreator::ScriptCreated, - CustomElementCreationMode::Asynchronous); + let element = Element::create( + name, + element.get_is(), + &document, + ElementCreator::ScriptCreated, + CustomElementCreationMode::Asynchronous, + ); DomRoot::upcast::<Node>(element) }, }; @@ -1865,14 +1968,16 @@ impl Node { let copy_elem = copy.downcast::<Element>().unwrap(); for attr in node_elem.attrs().iter() { - copy_elem.push_new_attribute(attr.local_name().clone(), - attr.value().clone(), - attr.name().clone(), - attr.namespace().clone(), - attr.prefix().cloned()); + copy_elem.push_new_attribute( + attr.local_name().clone(), + attr.value().clone(), + attr.name().clone(), + attr.namespace().clone(), + attr.prefix().cloned(), + ); } }, - _ => () + _ => (), } // Step 5: cloning steps. @@ -1881,8 +1986,7 @@ impl Node { // Step 6. if clone_children == CloneChildrenFlag::CloneChildren { for child in node.children() { - let child_copy = Node::clone(&child, Some(&document), - clone_children); + let child_copy = Node::clone(&child, Some(&document), clone_children); let _inserted_node = Node::pre_insert(&child_copy, ©, None); } } @@ -1896,7 +2000,7 @@ impl Node { Node::collect_text_contents(self.children()) } - pub fn collect_text_contents<T: Iterator<Item=DomRoot<Node>>>(iterator: T) -> DOMString { + pub fn collect_text_contents<T: Iterator<Item = DomRoot<Node>>>(iterator: T) -> DOMString { let mut content = String::new(); for node in iterator { if let Some(ref text) = node.downcast::<Text>() { @@ -1910,26 +2014,25 @@ impl Node { match namespace { ns!() => None, // FIXME(ajeffrey): convert directly from Namespace to DOMString - _ => Some(DOMString::from(&*namespace)) + _ => Some(DOMString::from(&*namespace)), } } // https://dom.spec.whatwg.org/#locate-a-namespace pub fn locate_namespace(node: &Node, prefix: Option<DOMString>) -> Namespace { match node.type_id() { - NodeTypeId::Element(_) => { - node.downcast::<Element>().unwrap().locate_namespace(prefix) - }, - NodeTypeId::Document(_) => { - node.downcast::<Document>().unwrap() - .GetDocumentElement().as_ref() - .map_or(ns!(), |elem| elem.locate_namespace(prefix)) - }, + NodeTypeId::Element(_) => node.downcast::<Element>().unwrap().locate_namespace(prefix), + NodeTypeId::Document(_) => node + .downcast::<Document>() + .unwrap() + .GetDocumentElement() + .as_ref() + .map_or(ns!(), |elem| elem.locate_namespace(prefix)), NodeTypeId::DocumentType | NodeTypeId::DocumentFragment => ns!(), - _ => { - node.GetParentElement().as_ref() - .map_or(ns!(), |elem| elem.locate_namespace(prefix)) - } + _ => node + .GetParentElement() + .as_ref() + .map_or(ns!(), |elem| elem.locate_namespace(prefix)), } } } @@ -1938,39 +2041,30 @@ impl NodeMethods for Node { // https://dom.spec.whatwg.org/#dom-node-nodetype fn NodeType(&self) -> u16 { match self.type_id() { - NodeTypeId::CharacterData(CharacterDataTypeId::Text) => - NodeConstants::TEXT_NODE, - NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => - NodeConstants::PROCESSING_INSTRUCTION_NODE, - NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => - NodeConstants::COMMENT_NODE, - NodeTypeId::Document(_) => - NodeConstants::DOCUMENT_NODE, - NodeTypeId::DocumentType => - NodeConstants::DOCUMENT_TYPE_NODE, - NodeTypeId::DocumentFragment => - NodeConstants::DOCUMENT_FRAGMENT_NODE, - NodeTypeId::Element(_) => - NodeConstants::ELEMENT_NODE, + NodeTypeId::CharacterData(CharacterDataTypeId::Text) => NodeConstants::TEXT_NODE, + NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => { + NodeConstants::PROCESSING_INSTRUCTION_NODE + }, + NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => NodeConstants::COMMENT_NODE, + NodeTypeId::Document(_) => NodeConstants::DOCUMENT_NODE, + NodeTypeId::DocumentType => NodeConstants::DOCUMENT_TYPE_NODE, + NodeTypeId::DocumentFragment => NodeConstants::DOCUMENT_FRAGMENT_NODE, + NodeTypeId::Element(_) => NodeConstants::ELEMENT_NODE, } } // https://dom.spec.whatwg.org/#dom-node-nodename fn NodeName(&self) -> DOMString { match self.type_id() { - NodeTypeId::Element(..) => { - self.downcast::<Element>().unwrap().TagName() - } + NodeTypeId::Element(..) => self.downcast::<Element>().unwrap().TagName(), NodeTypeId::CharacterData(CharacterDataTypeId::Text) => DOMString::from("#text"), NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => { self.downcast::<ProcessingInstruction>().unwrap().Target() - } - NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => DOMString::from("#comment"), - NodeTypeId::DocumentType => { - self.downcast::<DocumentType>().unwrap().name().clone() }, + NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => DOMString::from("#comment"), + NodeTypeId::DocumentType => self.downcast::<DocumentType>().unwrap().name().clone(), NodeTypeId::DocumentFragment => DOMString::from("#document-fragment"), - NodeTypeId::Document(_) => DOMString::from("#document") + NodeTypeId::Document(_) => DOMString::from("#document"), } } @@ -1986,7 +2080,7 @@ impl NodeMethods for Node { NodeTypeId::Element(..) | NodeTypeId::DocumentType | NodeTypeId::DocumentFragment => Some(self.owner_doc()), - NodeTypeId::Document(_) => None + NodeTypeId::Document(_) => None, } } @@ -2054,19 +2148,15 @@ impl NodeMethods for Node { // https://dom.spec.whatwg.org/#dom-node-textcontent fn GetTextContent(&self) -> Option<DOMString> { match self.type_id() { - NodeTypeId::DocumentFragment | - NodeTypeId::Element(..) => { + NodeTypeId::DocumentFragment | NodeTypeId::Element(..) => { let content = Node::collect_text_contents(self.traverse_preorder()); Some(content) - } + }, NodeTypeId::CharacterData(..) => { let characterdata = self.downcast::<CharacterData>().unwrap(); Some(characterdata.Data()) - } - NodeTypeId::DocumentType | - NodeTypeId::Document(_) => { - None - } + }, + NodeTypeId::DocumentType | NodeTypeId::Document(_) => None, } } @@ -2074,8 +2164,7 @@ impl NodeMethods for Node { fn SetTextContent(&self, value: Option<DOMString>) { let value = value.unwrap_or_default(); match self.type_id() { - NodeTypeId::DocumentFragment | - NodeTypeId::Element(..) => { + NodeTypeId::DocumentFragment | NodeTypeId::Element(..) => { // Step 1-2. let node = if value.is_empty() { None @@ -2085,13 +2174,12 @@ impl NodeMethods for Node { // Step 3. Node::replace_all(node.r(), self); - } + }, NodeTypeId::CharacterData(..) => { let characterdata = self.downcast::<CharacterData>().unwrap(); characterdata.SetData(value); - } - NodeTypeId::DocumentType | - NodeTypeId::Document(_) => {} + }, + NodeTypeId::DocumentType | NodeTypeId::Document(_) => {}, } } @@ -2109,10 +2197,8 @@ impl NodeMethods for Node { fn ReplaceChild(&self, node: &Node, child: &Node) -> Fallible<DomRoot<Node>> { // Step 1. match self.type_id() { - NodeTypeId::Document(_) | - NodeTypeId::DocumentFragment | - NodeTypeId::Element(..) => (), - _ => return Err(Error::HierarchyRequest) + NodeTypeId::Document(_) | NodeTypeId::DocumentFragment | NodeTypeId::Element(..) => (), + _ => return Err(Error::HierarchyRequest), } // Step 2. @@ -2127,11 +2213,14 @@ impl NodeMethods for Node { // Step 4-5. match node.type_id() { - NodeTypeId::CharacterData(CharacterDataTypeId::Text) if self.is::<Document>() => - return Err(Error::HierarchyRequest), - NodeTypeId::DocumentType if !self.is::<Document>() => return Err(Error::HierarchyRequest), + NodeTypeId::CharacterData(CharacterDataTypeId::Text) if self.is::<Document>() => { + return Err(Error::HierarchyRequest) + }, + NodeTypeId::DocumentType if !self.is::<Document>() => { + return Err(Error::HierarchyRequest) + }, NodeTypeId::Document(_) => return Err(Error::HierarchyRequest), - _ => () + _ => (), } // Step 6. @@ -2140,9 +2229,7 @@ impl NodeMethods for Node { // Step 6.1 NodeTypeId::DocumentFragment => { // Step 6.1.1(b) - if node.children() - .any(|c| c.is::<Text>()) - { + if node.children().any(|c| c.is::<Text>()) { return Err(Error::HierarchyRequest); } match node.child_elements().count() { @@ -2152,38 +2239,32 @@ impl NodeMethods for Node { if self.child_elements().any(|c| c.upcast::<Node>() != child) { return Err(Error::HierarchyRequest); } - if child.following_siblings() - .any(|child| child.is_doctype()) { + if child.following_siblings().any(|child| child.is_doctype()) { return Err(Error::HierarchyRequest); } }, // Step 6.1.1(a) - _ => return Err(Error::HierarchyRequest) + _ => return Err(Error::HierarchyRequest), } }, // Step 6.2 NodeTypeId::Element(..) => { - if self.child_elements() - .any(|c| c.upcast::<Node>() != child) { + if self.child_elements().any(|c| c.upcast::<Node>() != child) { return Err(Error::HierarchyRequest); } - if child.following_siblings() - .any(|child| child.is_doctype()) - { + if child.following_siblings().any(|child| child.is_doctype()) { return Err(Error::HierarchyRequest); } }, // Step 6.3 NodeTypeId::DocumentType => { - if self.children() - .any(|c| c.is_doctype() && - &*c != child) - { + if self.children().any(|c| c.is_doctype() && &*c != child) { return Err(Error::HierarchyRequest); } - if self.children() - .take_while(|c| &**c != child) - .any(|c| c.is::<Element>()) + if self + .children() + .take_while(|c| &**c != child) + .any(|c| c.is::<Element>()) { return Err(Error::HierarchyRequest); } @@ -2230,10 +2311,12 @@ impl NodeMethods for Node { Node::insert(node, self, reference_child, SuppressObserver::Suppressed); // Step 14. - vtable_for(&self).children_changed( - &ChildrenMutation::replace(previous_sibling.r(), - &removed_child, nodes, - reference_child)); + vtable_for(&self).children_changed(&ChildrenMutation::replace( + previous_sibling.r(), + &removed_child, + nodes, + reference_child, + )); let removed = removed_child.map(|r| [r]); let mutation = Mutation::ChildList { added: Some(nodes), @@ -2248,8 +2331,7 @@ impl NodeMethods for Node { } // https://dom.spec.whatwg.org/#dom-node-removechild - fn RemoveChild(&self, node: &Node) - -> Fallible<DomRoot<Node>> { + fn RemoveChild(&self, node: &Node) -> Fallible<DomRoot<Node>> { Node::pre_remove(node, self) } @@ -2264,10 +2346,16 @@ impl NodeMethods for Node { Node::remove(&node, self, SuppressObserver::Unsuppressed); continue; } - while children.peek().map_or(false, |&(_, ref sibling)| sibling.is::<Text>()) { + while children + .peek() + .map_or(false, |&(_, ref sibling)| sibling.is::<Text>()) + { let (index, sibling) = children.next().unwrap(); - sibling.ranges.drain_to_preceding_text_sibling(&sibling, &node, length); - self.ranges.move_to_text_child_at(self, index as u32, &node, length as u32); + sibling + .ranges + .drain_to_preceding_text_sibling(&sibling, &node, length); + self.ranges + .move_to_text_child_at(self, index as u32, &node, length as u32); let sibling_cdata = sibling.downcast::<CharacterData>().unwrap(); length += sibling_cdata.Length(); cdata.append_data(&sibling_cdata.data()); @@ -2281,11 +2369,15 @@ impl NodeMethods for Node { // https://dom.spec.whatwg.org/#dom-node-clonenode fn CloneNode(&self, deep: bool) -> DomRoot<Node> { - Node::clone(self, None, if deep { - CloneChildrenFlag::CloneChildren - } else { - CloneChildrenFlag::DoNotCloneChildren - }) + Node::clone( + self, + None, + if deep { + CloneChildrenFlag::CloneChildren + } else { + CloneChildrenFlag::DoNotCloneChildren + }, + ) } // https://dom.spec.whatwg.org/#dom-node-isequalnode @@ -2294,22 +2386,23 @@ impl NodeMethods for Node { let doctype = node.downcast::<DocumentType>().unwrap(); let other_doctype = other.downcast::<DocumentType>().unwrap(); (*doctype.name() == *other_doctype.name()) && - (*doctype.public_id() == *other_doctype.public_id()) && - (*doctype.system_id() == *other_doctype.system_id()) + (*doctype.public_id() == *other_doctype.public_id()) && + (*doctype.system_id() == *other_doctype.system_id()) } fn is_equal_element(node: &Node, other: &Node) -> bool { let element = node.downcast::<Element>().unwrap(); let other_element = other.downcast::<Element>().unwrap(); (*element.namespace() == *other_element.namespace()) && - (*element.prefix() == *other_element.prefix()) && - (*element.local_name() == *other_element.local_name()) && - (element.attrs().len() == other_element.attrs().len()) + (*element.prefix() == *other_element.prefix()) && + (*element.local_name() == *other_element.local_name()) && + (element.attrs().len() == other_element.attrs().len()) } fn is_equal_processinginstruction(node: &Node, other: &Node) -> bool { let pi = node.downcast::<ProcessingInstruction>().unwrap(); let other_pi = other.downcast::<ProcessingInstruction>().unwrap(); (*pi.target() == *other_pi.target()) && - (*pi.upcast::<CharacterData>().data() == *other_pi.upcast::<CharacterData>().data()) + (*pi.upcast::<CharacterData>().data() == + *other_pi.upcast::<CharacterData>().data()) } fn is_equal_characterdata(node: &Node, other: &Node) -> bool { let characterdata = node.downcast::<CharacterData>().unwrap(); @@ -2323,8 +2416,8 @@ impl NodeMethods for Node { element.attrs().iter().all(|attr| { other_element.attrs().iter().any(|other_attr| { (*attr.namespace() == *other_attr.namespace()) && - (attr.local_name() == other_attr.local_name()) && - (**attr.value() == **other_attr.value()) + (attr.local_name() == other_attr.local_name()) && + (**attr.value() == **other_attr.value()) }) }) } @@ -2336,19 +2429,22 @@ impl NodeMethods for Node { match node.type_id() { // Step 3. - NodeTypeId::DocumentType - if !is_equal_doctype(this, node) => return false, - NodeTypeId::Element(..) - if !is_equal_element(this, node) => return false, + NodeTypeId::DocumentType if !is_equal_doctype(this, node) => return false, + NodeTypeId::Element(..) if !is_equal_element(this, node) => return false, NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) - if !is_equal_processinginstruction(this, node) => return false, + if !is_equal_processinginstruction(this, node) => + { + return false + }, NodeTypeId::CharacterData(CharacterDataTypeId::Text) | NodeTypeId::CharacterData(CharacterDataTypeId::Comment) - if !is_equal_characterdata(this, node) => return false, + if !is_equal_characterdata(this, node) => + { + return false + }, // Step 4. - NodeTypeId::Element(..) - if !is_equal_element_attrs(this, node) => return false, - _ => () + NodeTypeId::Element(..) if !is_equal_element_attrs(this, node) => return false, + _ => (), } // Step 5. @@ -2357,15 +2453,15 @@ impl NodeMethods for Node { } // Step 6. - this.children().zip(node.children()).all(|(child, other_child)| { - is_equal_node(&child, &other_child) - }) + this.children() + .zip(node.children()) + .all(|(child, other_child)| is_equal_node(&child, &other_child)) } match maybe_node { // Step 1. None => false, // Step 2-6. - Some(node) => is_equal_node(self, node) + Some(node) => is_equal_node(self, node), } } @@ -2381,20 +2477,17 @@ impl NodeMethods for Node { fn CompareDocumentPosition(&self, other: &Node) -> u16 { // step 1. if self == other { - return 0 + return 0; } // FIXME(emilio): This will eventually need to handle attribute nodes. - let mut self_and_ancestors = - self.inclusive_ancestors().collect::<SmallVec<[_; 20]>>(); - let mut other_and_ancestors = - other.inclusive_ancestors().collect::<SmallVec<[_; 20]>>(); + let mut self_and_ancestors = self.inclusive_ancestors().collect::<SmallVec<[_; 20]>>(); + let mut other_and_ancestors = other.inclusive_ancestors().collect::<SmallVec<[_; 20]>>(); if self_and_ancestors.last() != other_and_ancestors.last() { - let random = - as_uintptr(self_and_ancestors.last().unwrap()) - < as_uintptr(other_and_ancestors.last().unwrap()); + let random = as_uintptr(self_and_ancestors.last().unwrap()) < + as_uintptr(other_and_ancestors.last().unwrap()); let random = if random { NodeConstants::DOCUMENT_POSITION_FOLLOWING } else { @@ -2418,9 +2511,8 @@ impl NodeMethods for Node { let child_2 = other_and_ancestors.pop().unwrap(); if child_1 != child_2 { - let is_before = - parent.children().position(|c| c == child_1).unwrap() - < parent.children().position(|c| c == child_2).unwrap(); + let is_before = parent.children().position(|c| c == child_1).unwrap() < + parent.children().position(|c| c == child_2).unwrap(); // If I am before, `other` is following, and the other way // around. return if is_before { @@ -2439,18 +2531,17 @@ impl NodeMethods for Node { // If we're the container, return that `other` is contained by us. return if self_and_ancestors.len() < other_and_ancestors.len() { NodeConstants::DOCUMENT_POSITION_FOLLOWING + - NodeConstants::DOCUMENT_POSITION_CONTAINED_BY + NodeConstants::DOCUMENT_POSITION_CONTAINED_BY } else { - NodeConstants::DOCUMENT_POSITION_PRECEDING + - NodeConstants::DOCUMENT_POSITION_CONTAINS - } + NodeConstants::DOCUMENT_POSITION_PRECEDING + NodeConstants::DOCUMENT_POSITION_CONTAINS + }; } // https://dom.spec.whatwg.org/#dom-node-contains fn Contains(&self, maybe_other: Option<&Node>) -> bool { match maybe_other { None => false, - Some(other) => self.is_inclusive_ancestor_of(other) + Some(other) => self.is_inclusive_ancestor_of(other), } } @@ -2465,20 +2556,16 @@ impl NodeMethods for Node { // Step 2. match self.type_id() { - NodeTypeId::Element(..) => { - self.downcast::<Element>().unwrap().lookup_prefix(namespace) - }, - NodeTypeId::Document(_) => { - self.downcast::<Document>().unwrap().GetDocumentElement().and_then(|element| { - element.lookup_prefix(namespace) - }) - }, + NodeTypeId::Element(..) => self.downcast::<Element>().unwrap().lookup_prefix(namespace), + NodeTypeId::Document(_) => self + .downcast::<Document>() + .unwrap() + .GetDocumentElement() + .and_then(|element| element.lookup_prefix(namespace)), NodeTypeId::DocumentType | NodeTypeId::DocumentFragment => None, - _ => { - self.GetParentElement().and_then(|element| { - element.lookup_prefix(namespace) - }) - } + _ => self + .GetParentElement() + .and_then(|element| element.lookup_prefix(namespace)), } } @@ -2487,7 +2574,7 @@ impl NodeMethods for Node { // Step 1. let prefix = match prefix { Some(ref p) if p.is_empty() => None, - pre => pre + pre => pre, }; // Step 2. @@ -2545,16 +2632,29 @@ pub enum NodeDamage { } pub enum ChildrenMutation<'a> { - Append { prev: &'a Node, added: &'a [&'a Node] }, - Insert { prev: &'a Node, added: &'a [&'a Node], next: &'a Node }, - Prepend { added: &'a [&'a Node], next: &'a Node }, + Append { + prev: &'a Node, + added: &'a [&'a Node], + }, + Insert { + prev: &'a Node, + added: &'a [&'a Node], + next: &'a Node, + }, + Prepend { + added: &'a [&'a Node], + next: &'a Node, + }, Replace { prev: Option<&'a Node>, removed: &'a Node, added: &'a [&'a Node], next: Option<&'a Node>, }, - ReplaceAll { removed: &'a [&'a Node], added: &'a [&'a Node] }, + ReplaceAll { + removed: &'a [&'a Node], + added: &'a [&'a Node], + }, /// Mutation for when a Text node's data is modified. /// This doesn't change the structure of the list, which is what the other /// variants' fields are stored for at the moment, so this can just have no @@ -2563,29 +2663,38 @@ pub enum ChildrenMutation<'a> { } impl<'a> ChildrenMutation<'a> { - fn insert(prev: Option<&'a Node>, added: &'a [&'a Node], next: Option<&'a Node>) - -> ChildrenMutation<'a> { + fn insert( + prev: Option<&'a Node>, + added: &'a [&'a Node], + next: Option<&'a Node>, + ) -> ChildrenMutation<'a> { match (prev, next) { - (None, None) => { - ChildrenMutation::ReplaceAll { removed: &[], added: added } + (None, None) => ChildrenMutation::ReplaceAll { + removed: &[], + added: added, }, - (Some(prev), None) => { - ChildrenMutation::Append { prev: prev, added: added } + (Some(prev), None) => ChildrenMutation::Append { + prev: prev, + added: added, }, - (None, Some(next)) => { - ChildrenMutation::Prepend { added: added, next: next } + (None, Some(next)) => ChildrenMutation::Prepend { + added: added, + next: next, }, - (Some(prev), Some(next)) => { - ChildrenMutation::Insert { prev: prev, added: added, next: next } + (Some(prev), Some(next)) => ChildrenMutation::Insert { + prev: prev, + added: added, + next: next, }, } } - fn replace(prev: Option<&'a Node>, - removed: &'a Option<&'a Node>, - added: &'a [&'a Node], - next: Option<&'a Node>) - -> ChildrenMutation<'a> { + fn replace( + prev: Option<&'a Node>, + removed: &'a Option<&'a Node>, + added: &'a [&'a Node], + next: Option<&'a Node>, + ) -> ChildrenMutation<'a> { if let Some(ref removed) = *removed { if let (None, None) = (prev, next) { ChildrenMutation::ReplaceAll { @@ -2605,9 +2714,11 @@ impl<'a> ChildrenMutation<'a> { } } - fn replace_all(removed: &'a [&'a Node], added: &'a [&'a Node]) - -> ChildrenMutation<'a> { - ChildrenMutation::ReplaceAll { removed: removed, added: added } + fn replace_all(removed: &'a [&'a Node], added: &'a [&'a Node]) -> ChildrenMutation<'a> { + ChildrenMutation::ReplaceAll { + removed: removed, + added: added, + } } /// Get the child that follows the added or removed children. @@ -2635,29 +2746,57 @@ impl<'a> ChildrenMutation<'a> { match *self { // Add/remove at start of container: Return the first following element. ChildrenMutation::Prepend { next, .. } | - ChildrenMutation::Replace { prev: None, next: Some(next), .. } => { - next.inclusively_following_siblings().filter(|node| node.is::<Element>()).next() - } + ChildrenMutation::Replace { + prev: None, + next: Some(next), + .. + } => next + .inclusively_following_siblings() + .filter(|node| node.is::<Element>()) + .next(), // Add/remove at end of container: Return the last preceding element. ChildrenMutation::Append { prev, .. } | - ChildrenMutation::Replace { prev: Some(prev), next: None, .. } => { - prev.inclusively_preceding_siblings().filter(|node| node.is::<Element>()).next() - } + ChildrenMutation::Replace { + prev: Some(prev), + next: None, + .. + } => prev + .inclusively_preceding_siblings() + .filter(|node| node.is::<Element>()) + .next(), // Insert or replace in the middle: ChildrenMutation::Insert { prev, next, .. } | - ChildrenMutation::Replace { prev: Some(prev), next: Some(next), .. } => { - if prev.inclusively_preceding_siblings().all(|node| !node.is::<Element>()) { + ChildrenMutation::Replace { + prev: Some(prev), + next: Some(next), + .. + } => { + if prev + .inclusively_preceding_siblings() + .all(|node| !node.is::<Element>()) + { // Before the first element: Return the first following element. - next.inclusively_following_siblings().filter(|node| node.is::<Element>()).next() - } else if next.inclusively_following_siblings().all(|node| !node.is::<Element>()) { + next.inclusively_following_siblings() + .filter(|node| node.is::<Element>()) + .next() + } else if next + .inclusively_following_siblings() + .all(|node| !node.is::<Element>()) + { // After the last element: Return the last preceding element. - prev.inclusively_preceding_siblings().filter(|node| node.is::<Element>()).next() + prev.inclusively_preceding_siblings() + .filter(|node| node.is::<Element>()) + .next() } else { None } - } + }, - ChildrenMutation::Replace { prev: None, next: None, .. } => unreachable!(), + ChildrenMutation::Replace { + prev: None, + next: None, + .. + } => unreachable!(), ChildrenMutation::ReplaceAll { .. } => None, ChildrenMutation::ChangeText => None, } @@ -2679,9 +2818,7 @@ pub struct UnbindContext<'a> { impl<'a> UnbindContext<'a> { /// Create a new `UnbindContext` value. - fn new(parent: &'a Node, - prev_sibling: Option<&'a Node>, - cached_index: Option<u32>) -> Self { + fn new(parent: &'a Node, prev_sibling: Option<&'a Node>, cached_index: Option<u32>) -> Self { UnbindContext { index: Cell::new(cached_index), parent: parent, @@ -2713,7 +2850,7 @@ impl MallocSizeOf for UniqueId { #[allow(unsafe_code)] fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { if let &Some(ref uuid) = unsafe { &*self.cell.get() } { - unsafe { ops.malloc_size_of(&** uuid) } + unsafe { ops.malloc_size_of(&**uuid) } } else { 0 } @@ -2723,7 +2860,9 @@ impl MallocSizeOf for UniqueId { impl UniqueId { /// Create a new `UniqueId` value. The underlying `Uuid` is lazily created. fn new() -> UniqueId { - UniqueId { cell: UnsafeCell::new(None) } + UniqueId { + cell: UnsafeCell::new(None), + } } /// The Uuid of that unique ID. @@ -2743,10 +2882,8 @@ impl Into<LayoutNodeType> for NodeTypeId { #[inline(always)] fn into(self) -> LayoutNodeType { match self { - NodeTypeId::Element(e) => - LayoutNodeType::Element(e.into()), - NodeTypeId::CharacterData(CharacterDataTypeId::Text) => - LayoutNodeType::Text, + NodeTypeId::Element(e) => LayoutNodeType::Element(e.into()), + NodeTypeId::CharacterData(CharacterDataTypeId::Text) => LayoutNodeType::Text, x => unreachable!("Layout should not traverse nodes of type {:?}", x), } } @@ -2756,34 +2893,48 @@ impl Into<LayoutElementType> for ElementTypeId { #[inline(always)] fn into(self) -> LayoutElementType { match self { - ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBRElement) => - LayoutElementType::HTMLBRElement, - ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLCanvasElement) => - LayoutElementType::HTMLCanvasElement, - ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLIFrameElement) => - LayoutElementType::HTMLIFrameElement, - ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLImageElement) => - LayoutElementType::HTMLImageElement, - ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement) => - LayoutElementType::HTMLInputElement, - ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLObjectElement) => - LayoutElementType::HTMLObjectElement, - ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLParagraphElement) => - LayoutElementType::HTMLParagraphElement, - ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableCellElement(_)) => - LayoutElementType::HTMLTableCellElement, - ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableColElement) => - LayoutElementType::HTMLTableColElement, - ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableElement) => - LayoutElementType::HTMLTableElement, - ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableRowElement) => - LayoutElementType::HTMLTableRowElement, - ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableSectionElement) => - LayoutElementType::HTMLTableSectionElement, - ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement) => - LayoutElementType::HTMLTextAreaElement, - ElementTypeId::SVGElement(SVGElementTypeId::SVGGraphicsElement(SVGGraphicsElementTypeId::SVGSVGElement)) => - LayoutElementType::SVGSVGElement, + ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBRElement) => { + LayoutElementType::HTMLBRElement + }, + ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLCanvasElement) => { + LayoutElementType::HTMLCanvasElement + }, + ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLIFrameElement) => { + LayoutElementType::HTMLIFrameElement + }, + ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLImageElement) => { + LayoutElementType::HTMLImageElement + }, + ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement) => { + LayoutElementType::HTMLInputElement + }, + ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLObjectElement) => { + LayoutElementType::HTMLObjectElement + }, + ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLParagraphElement) => { + LayoutElementType::HTMLParagraphElement + }, + ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableCellElement(_)) => { + LayoutElementType::HTMLTableCellElement + }, + ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableColElement) => { + LayoutElementType::HTMLTableColElement + }, + ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableElement) => { + LayoutElementType::HTMLTableElement + }, + ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableRowElement) => { + LayoutElementType::HTMLTableRowElement + }, + ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableSectionElement) => { + LayoutElementType::HTMLTableSectionElement + }, + ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement) => { + LayoutElementType::HTMLTextAreaElement + }, + ElementTypeId::SVGElement(SVGElementTypeId::SVGGraphicsElement( + SVGGraphicsElementTypeId::SVGSVGElement, + )) => LayoutElementType::SVGSVGElement, _ => LayoutElementType::Element, } } @@ -2796,7 +2947,8 @@ pub trait VecPreOrderInsertionHelper<T> { } impl<T> VecPreOrderInsertionHelper<T> for Vec<Dom<T>> - where T: DerivedFrom<Node> + DomObject +where + T: DerivedFrom<Node> + DomObject, { /// This algorithm relies on the following assumptions: /// * any elements inserted in this vector share the same tree root diff --git a/components/script/dom/nodeiterator.rs b/components/script/dom/nodeiterator.rs index 5da1bffb6d8..155bfa980f1 100644 --- a/components/script/dom/nodeiterator.rs +++ b/components/script/dom/nodeiterator.rs @@ -31,9 +31,7 @@ pub struct NodeIterator { } impl NodeIterator { - fn new_inherited(root_node: &Node, - what_to_show: u32, - filter: Filter) -> NodeIterator { + fn new_inherited(root_node: &Node, what_to_show: u32, filter: Filter) -> NodeIterator { NodeIterator { reflector_: Reflector::new(), root_node: Dom::from_ref(root_node), @@ -45,22 +43,28 @@ impl NodeIterator { } } - pub fn new_with_filter(document: &Document, - root_node: &Node, - what_to_show: u32, - filter: Filter) -> DomRoot<NodeIterator> { - reflect_dom_object(Box::new(NodeIterator::new_inherited(root_node, what_to_show, filter)), - document.window(), - NodeIteratorBinding::Wrap) + pub fn new_with_filter( + document: &Document, + root_node: &Node, + what_to_show: u32, + filter: Filter, + ) -> DomRoot<NodeIterator> { + reflect_dom_object( + Box::new(NodeIterator::new_inherited(root_node, what_to_show, filter)), + document.window(), + NodeIteratorBinding::Wrap, + ) } - pub fn new(document: &Document, - root_node: &Node, - what_to_show: u32, - node_filter: Option<Rc<NodeFilter>>) -> DomRoot<NodeIterator> { + pub fn new( + document: &Document, + root_node: &Node, + what_to_show: u32, + node_filter: Option<Rc<NodeFilter>>, + ) -> DomRoot<NodeIterator> { let filter = match node_filter { None => Filter::None, - Some(jsfilter) => Filter::Callback(jsfilter) + Some(jsfilter) => Filter::Callback(jsfilter), }; NodeIterator::new_with_filter(document, root_node, what_to_show, filter) } @@ -189,7 +193,6 @@ impl NodeIteratorMethods for NodeIterator { } } - impl NodeIterator { // https://dom.spec.whatwg.org/#concept-node-filter fn accept_node(&self, node: &Node) -> Fallible<u16> { @@ -201,7 +204,7 @@ impl NodeIterator { let n = node.NodeType() - 1; // Step 3. if (self.what_to_show & (1 << n)) == 0 { - return Ok(NodeFilterConstants::FILTER_SKIP) + return Ok(NodeFilterConstants::FILTER_SKIP); } match self.filter { @@ -216,14 +219,13 @@ impl NodeIterator { self.active.set(false); // Step 8. result - } + }, } } } - #[derive(JSTraceable)] pub enum Filter { None, - Callback(Rc<NodeFilter>) + Callback(Rc<NodeFilter>), } diff --git a/components/script/dom/nodelist.rs b/components/script/dom/nodelist.rs index 24165267480..6d3fed9a5af 100644 --- a/components/script/dom/nodelist.rs +++ b/components/script/dom/nodelist.rs @@ -37,18 +37,28 @@ impl NodeList { #[allow(unrooted_must_root)] pub fn new(window: &Window, list_type: NodeListType) -> DomRoot<NodeList> { - reflect_dom_object(Box::new(NodeList::new_inherited(list_type)), - window, - NodeListBinding::Wrap) + reflect_dom_object( + Box::new(NodeList::new_inherited(list_type)), + window, + NodeListBinding::Wrap, + ) } pub fn new_simple_list<T>(window: &Window, iter: T) -> DomRoot<NodeList> - where T: Iterator<Item=DomRoot<Node>> { - NodeList::new(window, NodeListType::Simple(iter.map(|r| Dom::from_ref(&*r)).collect())) + where + T: Iterator<Item = DomRoot<Node>>, + { + NodeList::new( + window, + NodeListType::Simple(iter.map(|r| Dom::from_ref(&*r)).collect()), + ) } pub fn new_simple_list_slice(window: &Window, slice: &[&Node]) -> DomRoot<NodeList> { - NodeList::new(window, NodeListType::Simple(slice.iter().map(|r| Dom::from_ref(*r)).collect())) + NodeList::new( + window, + NodeListType::Simple(slice.iter().map(|r| Dom::from_ref(*r)).collect()), + ) } pub fn new_child_list(window: &Window, node: &Node) -> DomRoot<NodeList> { @@ -72,9 +82,9 @@ impl NodeListMethods for NodeList { // https://dom.spec.whatwg.org/#dom-nodelist-item fn Item(&self, index: u32) -> Option<DomRoot<Node>> { match self.list_type { - NodeListType::Simple(ref elems) => { - elems.get(index as usize).map(|node| DomRoot::from_ref(&**node)) - }, + NodeListType::Simple(ref elems) => elems + .get(index as usize) + .map(|node| DomRoot::from_ref(&**node)), NodeListType::Children(ref list) => list.item(index), } } @@ -85,7 +95,6 @@ impl NodeListMethods for NodeList { } } - impl NodeList { pub fn as_children_list(&self) -> &ChildrenList { if let NodeListType::Children(ref list) = self.list_type { @@ -103,7 +112,7 @@ impl NodeList { } } - pub fn iter<'a>(&'a self) -> impl Iterator<Item=DomRoot<Node>> + 'a { + pub fn iter<'a>(&'a self) -> impl Iterator<Item = DomRoot<Node>> + 'a { let len = self.Length(); (0..len).flat_map(move |i| self.Item(i)) } @@ -153,7 +162,11 @@ impl ChildrenList { self.last_visited.get().unwrap().GetNextSibling().unwrap() } else if last_index > 0 && index == last_index - 1u32 { // Item is last visited's previous sibling. - self.last_visited.get().unwrap().GetPreviousSibling().unwrap() + self.last_visited + .get() + .unwrap() + .GetPreviousSibling() + .unwrap() } else if index > last_index { if index == len - 1u32 { // Item is parent's last child, not worth updating last visited. @@ -161,28 +174,39 @@ impl ChildrenList { } if index <= last_index + (len - last_index) / 2u32 { // Item is closer to the last visited child and follows it. - self.last_visited.get().unwrap() - .inclusively_following_siblings() - .nth((index - last_index) as usize).unwrap() + self.last_visited + .get() + .unwrap() + .inclusively_following_siblings() + .nth((index - last_index) as usize) + .unwrap() } else { // Item is closer to parent's last child and obviously // precedes it. - self.node.GetLastChild().unwrap() + self.node + .GetLastChild() + .unwrap() .inclusively_preceding_siblings() - .nth((len - index - 1u32) as usize).unwrap() + .nth((len - index - 1u32) as usize) + .unwrap() } } else if index >= last_index / 2u32 { // Item is closer to the last visited child and precedes it. - self.last_visited.get().unwrap() - .inclusively_preceding_siblings() - .nth((last_index - index) as usize).unwrap() + self.last_visited + .get() + .unwrap() + .inclusively_preceding_siblings() + .nth((last_index - index) as usize) + .unwrap() } else { // Item is closer to parent's first child and obviously follows it. debug_assert!(index < last_index / 2u32); - self.node.GetFirstChild().unwrap() - .inclusively_following_siblings() - .nth(index as usize) - .unwrap() + self.node + .GetFirstChild() + .unwrap() + .inclusively_following_siblings() + .nth(index as usize) + .unwrap() }; self.last_visited.set(Some(&last_visited)); self.last_index.set(index); @@ -211,11 +235,13 @@ impl ChildrenList { } } - fn replace(list: &ChildrenList, - prev: Option<&Node>, - removed: &Node, - added: &[&Node], - next: Option<&Node>) { + fn replace( + list: &ChildrenList, + prev: Option<&Node>, + removed: &Node, + added: &[&Node], + next: Option<&Node>, + ) { let index = list.last_index.get(); if removed == &*list.last_visited.get().unwrap() { let visited = match (prev, added, next) { @@ -259,7 +285,12 @@ impl ChildrenList { ChildrenMutation::Prepend { added, next } => { prepend(self, added, next); }, - ChildrenMutation::Replace { prev, removed, added, next } => { + ChildrenMutation::Replace { + prev, + removed, + added, + next, + } => { replace(self, prev, removed, added, next); }, ChildrenMutation::ReplaceAll { added, .. } => { diff --git a/components/script/dom/offlineaudiocontext.rs b/components/script/dom/offlineaudiocontext.rs index 21376c11a4d..899574e35e4 100644 --- a/components/script/dom/offlineaudiocontext.rs +++ b/components/script/dom/offlineaudiocontext.rs @@ -41,17 +41,14 @@ pub struct OfflineAudioContext { impl OfflineAudioContext { #[allow(unrooted_must_root)] - fn new_inherited(channel_count: u32, - length: u32, - sample_rate: f32) -> OfflineAudioContext { + fn new_inherited(channel_count: u32, length: u32, sample_rate: f32) -> OfflineAudioContext { let options = ServoMediaOfflineAudioContextOptions { channels: channel_count as u8, length: length as usize, sample_rate, }; - let context = BaseAudioContext::new_inherited( - BaseAudioContextOptions::OfflineAudioContext(options), - ); + let context = + BaseAudioContext::new_inherited(BaseAudioContextOptions::OfflineAudioContext(options)); OfflineAudioContext { context, channel_count, @@ -62,10 +59,12 @@ impl OfflineAudioContext { } #[allow(unrooted_must_root)] - fn new(window: &Window, - channel_count: u32, - length: u32, - sample_rate: f32) -> DomRoot<OfflineAudioContext> { + fn new( + window: &Window, + channel_count: u32, + length: u32, + sample_rate: f32, + ) -> DomRoot<OfflineAudioContext> { let context = OfflineAudioContext::new_inherited(channel_count, length, sample_rate); reflect_dom_object(Box::new(context), window, OfflineAudioContextBinding::Wrap) } @@ -74,7 +73,12 @@ impl OfflineAudioContext { window: &Window, options: &OfflineAudioContextOptions, ) -> Fallible<DomRoot<OfflineAudioContext>> { - Ok(OfflineAudioContext::new(window, options.numberOfChannels, options.length, *options.sampleRate)) + Ok(OfflineAudioContext::new( + window, + options.numberOfChannels, + options.length, + *options.sampleRate, + )) } pub fn Constructor_( @@ -92,7 +96,12 @@ impl OfflineAudioContext { return Err(Error::NotSupported); } - Ok(OfflineAudioContext::new(window, number_of_channels, length, *sample_rate)) + Ok(OfflineAudioContext::new( + window, + number_of_channels, + length, + *sample_rate, + )) } } diff --git a/components/script/dom/oscillatornode.rs b/components/script/dom/oscillatornode.rs index 6f6ce8b9f72..b79368cbf38 100644 --- a/components/script/dom/oscillatornode.rs +++ b/components/script/dom/oscillatornode.rs @@ -35,9 +35,10 @@ impl OscillatorNode { context: &BaseAudioContext, options: &OscillatorOptions, ) -> Fallible<OscillatorNode> { - let node_options = options.parent - .unwrap_or(2, ChannelCountMode::Max, - ChannelInterpretation::Speakers); + let node_options = + options + .parent + .unwrap_or(2, ChannelCountMode::Max, ChannelInterpretation::Speakers); let source_node = AudioScheduledSourceNode::new_inherited( AudioNodeInit::OscillatorNode(options.into()), context, @@ -82,7 +83,11 @@ impl OscillatorNode { options: &OscillatorOptions, ) -> Fallible<DomRoot<OscillatorNode>> { let node = OscillatorNode::new_inherited(window, context, options)?; - Ok(reflect_dom_object(Box::new(node), window, OscillatorNodeBinding::Wrap)) + Ok(reflect_dom_object( + Box::new(node), + window, + OscillatorNodeBinding::Wrap, + )) } pub fn Constructor( diff --git a/components/script/dom/pagetransitionevent.rs b/components/script/dom/pagetransitionevent.rs index e9ef86a626d..6bcedd977b1 100644 --- a/components/script/dom/pagetransitionevent.rs +++ b/components/script/dom/pagetransitionevent.rs @@ -32,17 +32,20 @@ impl PageTransitionEvent { } pub fn new_uninitialized(window: &Window) -> DomRoot<PageTransitionEvent> { - reflect_dom_object(Box::new(PageTransitionEvent::new_inherited()), - window, - PageTransitionEventBinding::Wrap) + reflect_dom_object( + Box::new(PageTransitionEvent::new_inherited()), + window, + PageTransitionEventBinding::Wrap, + ) } - pub fn new(window: &Window, - type_: Atom, - bubbles: bool, - cancelable: bool, - persisted: bool) - -> DomRoot<PageTransitionEvent> { + pub fn new( + window: &Window, + type_: Atom, + bubbles: bool, + cancelable: bool, + persisted: bool, + ) -> DomRoot<PageTransitionEvent> { let ev = PageTransitionEvent::new_uninitialized(window); ev.persisted.set(persisted); { @@ -52,15 +55,18 @@ impl PageTransitionEvent { ev } - pub fn Constructor(window: &Window, - type_: DOMString, - init: &PageTransitionEventBinding::PageTransitionEventInit) - -> Fallible<DomRoot<PageTransitionEvent>> { - Ok(PageTransitionEvent::new(window, - Atom::from(type_), - init.parent.bubbles, - init.parent.cancelable, - init.persisted)) + pub fn Constructor( + window: &Window, + type_: DOMString, + init: &PageTransitionEventBinding::PageTransitionEventInit, + ) -> Fallible<DomRoot<PageTransitionEvent>> { + Ok(PageTransitionEvent::new( + window, + Atom::from(type_), + init.parent.bubbles, + init.parent.cancelable, + init.persisted, + )) } } diff --git a/components/script/dom/paintrenderingcontext2d.rs b/components/script/dom/paintrenderingcontext2d.rs index 49bf0da6024..43124e30c76 100644 --- a/components/script/dom/paintrenderingcontext2d.rs +++ b/components/script/dom/paintrenderingcontext2d.rs @@ -47,19 +47,30 @@ impl PaintRenderingContext2D { let image_cache = global.image_cache(); let base_url = global.upcast::<WorkletGlobalScope>().base_url(); PaintRenderingContext2D { - context: CanvasRenderingContext2D::new_inherited(global.upcast(), None, image_cache, base_url, size), + context: CanvasRenderingContext2D::new_inherited( + global.upcast(), + None, + image_cache, + base_url, + size, + ), device_pixel_ratio: Cell::new(TypedScale::new(1.0)), } } pub fn new(global: &PaintWorkletGlobalScope) -> DomRoot<PaintRenderingContext2D> { - reflect_dom_object(Box::new(PaintRenderingContext2D::new_inherited(global)), - global, - PaintRenderingContext2DBinding::Wrap) + reflect_dom_object( + Box::new(PaintRenderingContext2D::new_inherited(global)), + global, + PaintRenderingContext2DBinding::Wrap, + ) } pub fn send_data(&self, sender: IpcSender<CanvasImageData>) { - let msg = CanvasMsg::FromLayout(FromLayoutMsg::SendData(sender), self.context.get_canvas_id()); + let msg = CanvasMsg::FromLayout( + FromLayoutMsg::SendData(sender), + self.context.get_canvas_id(), + ); let _ = self.context.get_ipc_renderer().send(msg); } @@ -67,13 +78,15 @@ impl PaintRenderingContext2D { self.context.take_missing_image_urls() } - pub fn set_bitmap_dimensions(&self, - size: TypedSize2D<f32, CSSPixel>, - device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>) - { + pub fn set_bitmap_dimensions( + &self, + size: TypedSize2D<f32, CSSPixel>, + device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>, + ) { let size = size * device_pixel_ratio; self.device_pixel_ratio.set(device_pixel_ratio); - self.context.set_bitmap_dimensions(size.to_untyped().to_i32()); + self.context + .set_bitmap_dimensions(size.to_untyped().to_i32()); self.scale_by_device_pixel_ratio(); } @@ -194,12 +207,7 @@ impl PaintRenderingContext2DMethods for PaintRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage - fn DrawImage( - &self, - image: CanvasImageSource, - dx: f64, - dy: f64, - ) -> ErrorResult { + fn DrawImage(&self, image: CanvasImageSource, dx: f64, dy: f64) -> ErrorResult { self.context.DrawImage(image, dx, dy) } @@ -228,7 +236,8 @@ impl PaintRenderingContext2DMethods for PaintRenderingContext2D { dw: f64, dh: f64, ) -> ErrorResult { - self.context.DrawImage__(image, sx, sy, sw, sh, dx, dy, dw, dh) + self.context + .DrawImage__(image, sx, sy, sw, sh, dx, dy, dw, dh) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-moveto @@ -267,8 +276,19 @@ impl PaintRenderingContext2DMethods for PaintRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-ellipse - fn Ellipse(&self, x: f64, y: f64, rx: f64, ry: f64, rotation: f64, start: f64, end: f64, ccw: bool) -> ErrorResult { - self.context.Ellipse(x, y, rx, ry, rotation, start, end, ccw) + fn Ellipse( + &self, + x: f64, + y: f64, + rx: f64, + ry: f64, + rotation: f64, + start: f64, + end: f64, + ccw: bool, + ) -> ErrorResult { + self.context + .Ellipse(x, y, rx, ry, rotation, start, end, ccw) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-imagesmoothingenabled @@ -302,24 +322,26 @@ impl PaintRenderingContext2DMethods for PaintRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-createlineargradient - fn CreateLinearGradient(&self, - x0: Finite<f64>, - y0: Finite<f64>, - x1: Finite<f64>, - y1: Finite<f64>) - -> DomRoot<CanvasGradient> { + fn CreateLinearGradient( + &self, + x0: Finite<f64>, + y0: Finite<f64>, + x1: Finite<f64>, + y1: Finite<f64>, + ) -> DomRoot<CanvasGradient> { self.context.CreateLinearGradient(x0, y0, x1, y1) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-createradialgradient - fn CreateRadialGradient(&self, - x0: Finite<f64>, - y0: Finite<f64>, - r0: Finite<f64>, - x1: Finite<f64>, - y1: Finite<f64>, - r1: Finite<f64>) - -> Fallible<DomRoot<CanvasGradient>> { + fn CreateRadialGradient( + &self, + x0: Finite<f64>, + y0: Finite<f64>, + r0: Finite<f64>, + x1: Finite<f64>, + y1: Finite<f64>, + r1: Finite<f64>, + ) -> Fallible<DomRoot<CanvasGradient>> { self.context.CreateRadialGradient(x0, y0, r0, x1, y1, r1) } @@ -411,5 +433,4 @@ impl PaintRenderingContext2DMethods for PaintRenderingContext2D { fn SetShadowColor(&self, value: DOMString) { self.context.SetShadowColor(value) } - } diff --git a/components/script/dom/paintsize.rs b/components/script/dom/paintsize.rs index 3d3c386bc6c..cc8458c2856 100644 --- a/components/script/dom/paintsize.rs +++ b/components/script/dom/paintsize.rs @@ -29,8 +29,15 @@ impl PaintSize { } } - pub fn new(global: &PaintWorkletGlobalScope, size: TypedSize2D<f32, CSSPixel>) -> DomRoot<PaintSize> { - reflect_dom_object(Box::new(PaintSize::new_inherited(size)), global, PaintSizeBinding::Wrap) + pub fn new( + global: &PaintWorkletGlobalScope, + size: TypedSize2D<f32, CSSPixel>, + ) -> DomRoot<PaintSize> { + reflect_dom_object( + Box::new(PaintSize::new_inherited(size)), + global, + PaintSizeBinding::Wrap, + ) } } diff --git a/components/script/dom/paintworkletglobalscope.rs b/components/script/dom/paintworkletglobalscope.rs index 352eae0ed0e..cc58a07b960 100644 --- a/components/script/dom/paintworkletglobalscope.rs +++ b/components/script/dom/paintworkletglobalscope.rs @@ -94,15 +94,24 @@ pub struct PaintWorkletGlobalScope { impl PaintWorkletGlobalScope { #[allow(unsafe_code)] - pub fn new(runtime: &Runtime, - pipeline_id: PipelineId, - base_url: ServoUrl, - executor: WorkletExecutor, - init: &WorkletGlobalScopeInit) - -> DomRoot<PaintWorkletGlobalScope> { - debug!("Creating paint worklet global scope for pipeline {}.", pipeline_id); + pub fn new( + runtime: &Runtime, + pipeline_id: PipelineId, + base_url: ServoUrl, + executor: WorkletExecutor, + init: &WorkletGlobalScopeInit, + ) -> DomRoot<PaintWorkletGlobalScope> { + debug!( + "Creating paint worklet global scope for pipeline {}.", + pipeline_id + ); let global = Box::new(PaintWorkletGlobalScope { - worklet_global: WorkletGlobalScope::new_inherited(pipeline_id, base_url, executor, init), + worklet_global: WorkletGlobalScope::new_inherited( + pipeline_id, + base_url, + executor, + init, + ), image_cache: init.image_cache.clone(), paint_definitions: Default::default(), paint_class_instances: Default::default(), @@ -128,7 +137,14 @@ impl PaintWorkletGlobalScope { pub fn perform_a_worklet_task(&self, task: PaintWorkletTask) { match task { - PaintWorkletTask::DrawAPaintImage(name, size, device_pixel_ratio, properties, arguments, sender) => { + PaintWorkletTask::DrawAPaintImage( + name, + size, + device_pixel_ratio, + properties, + arguments, + sender, + ) => { let cache_hit = (&*self.cached_name.borrow() == &name) && (self.cached_size.get() == size) && (self.cached_device_pixel_ratio.get() == device_pixel_ratio) && @@ -139,8 +155,17 @@ impl PaintWorkletGlobalScope { self.cached_result.borrow().clone() } else { debug!("Cache miss on paint worklet {}!", name); - let map = StylePropertyMapReadOnly::from_iter(self.upcast(), properties.iter().cloned()); - let result = self.draw_a_paint_image(&name, size, device_pixel_ratio, &*map, &*arguments); + let map = StylePropertyMapReadOnly::from_iter( + self.upcast(), + properties.iter().cloned(), + ); + let result = self.draw_a_paint_image( + &name, + size, + device_pixel_ratio, + &*map, + &*arguments, + ); if (result.image_key.is_some()) && (result.missing_image_urls.is_empty()) { *self.cached_name.borrow_mut() = name; self.cached_size.set(size); @@ -152,7 +177,7 @@ impl PaintWorkletGlobalScope { result }; let _ = sender.send(result); - } + }, PaintWorkletTask::SpeculativelyDrawAPaintImage(name, properties, arguments) => { let should_speculate = (&*self.cached_name.borrow() != &name) || (&*self.cached_properties.borrow() != &properties) || @@ -160,8 +185,17 @@ impl PaintWorkletGlobalScope { if should_speculate { let size = self.cached_size.get(); let device_pixel_ratio = self.cached_device_pixel_ratio.get(); - let map = StylePropertyMapReadOnly::from_iter(self.upcast(), properties.iter().cloned()); - let result = self.draw_a_paint_image(&name, size, device_pixel_ratio, &*map, &*arguments); + let map = StylePropertyMapReadOnly::from_iter( + self.upcast(), + properties.iter().cloned(), + ); + let result = self.draw_a_paint_image( + &name, + size, + device_pixel_ratio, + &*map, + &*arguments, + ); if (result.image_key.is_some()) && (result.missing_image_urls.is_empty()) { *self.cached_name.borrow_mut() = name; *self.cached_properties.borrow_mut() = properties; @@ -169,41 +203,53 @@ impl PaintWorkletGlobalScope { *self.cached_result.borrow_mut() = result; } } - } + }, } } /// <https://drafts.css-houdini.org/css-paint-api/#draw-a-paint-image> - fn draw_a_paint_image(&self, - name: &Atom, - size_in_px: TypedSize2D<f32, CSSPixel>, - device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>, - properties: &StylePropertyMapReadOnly, - arguments: &[String]) - -> DrawAPaintImageResult - { + fn draw_a_paint_image( + &self, + name: &Atom, + size_in_px: TypedSize2D<f32, CSSPixel>, + device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>, + properties: &StylePropertyMapReadOnly, + arguments: &[String], + ) -> DrawAPaintImageResult { let size_in_dpx = size_in_px * device_pixel_ratio; - let size_in_dpx = TypedSize2D::new(size_in_dpx.width.abs() as u32, size_in_dpx.height.abs() as u32); + let size_in_dpx = TypedSize2D::new( + size_in_dpx.width.abs() as u32, + size_in_dpx.height.abs() as u32, + ); // TODO: Steps 1-5. // TODO: document paint definitions. - self.invoke_a_paint_callback(name, size_in_px, size_in_dpx, device_pixel_ratio, properties, arguments) + self.invoke_a_paint_callback( + name, + size_in_px, + size_in_dpx, + device_pixel_ratio, + properties, + arguments, + ) } /// <https://drafts.css-houdini.org/css-paint-api/#invoke-a-paint-callback> #[allow(unsafe_code)] - fn invoke_a_paint_callback(&self, - name: &Atom, - size_in_px: TypedSize2D<f32, CSSPixel>, - size_in_dpx: TypedSize2D<u32, DevicePixel>, - device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>, - properties: &StylePropertyMapReadOnly, - arguments: &[String]) - -> DrawAPaintImageResult - { - debug!("Invoking a paint callback {}({},{}) at {}.", - name, size_in_px.width, size_in_px.height, device_pixel_ratio); + fn invoke_a_paint_callback( + &self, + name: &Atom, + size_in_px: TypedSize2D<f32, CSSPixel>, + size_in_dpx: TypedSize2D<u32, DevicePixel>, + device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>, + properties: &StylePropertyMapReadOnly, + arguments: &[String], + ) -> DrawAPaintImageResult { + debug!( + "Invoking a paint callback {}({},{}) at {}.", + name, size_in_px.width, size_in_px.height, device_pixel_ratio + ); let cx = self.worklet_global.get_cx(); let _ac = JSAutoCompartment::new(cx, self.worklet_global.reflector().get_jsobject().get()); @@ -217,7 +263,7 @@ impl PaintWorkletGlobalScope { // Step 2.2. warn!("Drawing un-registered paint definition {}.", name); return self.invalid_image(size_in_dpx, vec![]); - } + }, Some(definition) => { // Step 5.1 if !definition.constructor_valid_flag.get() { @@ -227,7 +273,7 @@ impl PaintWorkletGlobalScope { class_constructor.set(definition.class_constructor.get()); paint_function.set(definition.paint_function.get()); DomRoot::from_ref(&*definition.context) - } + }, }; // Steps 5.2-5.4 @@ -242,19 +288,28 @@ impl PaintWorkletGlobalScope { // Step 5.2-5.3 let args = HandleValueArray::new(); rooted!(in(cx) let mut result = null_mut::<JSObject>()); - unsafe { Construct1(cx, class_constructor.handle(), &args, result.handle_mut()); } + unsafe { + Construct1(cx, class_constructor.handle(), &args, result.handle_mut()); + } paint_instance.set(ObjectValue(result.get())); if unsafe { JS_IsExceptionPending(cx) } { debug!("Paint constructor threw an exception {}.", name); - unsafe { JS_ClearPendingException(cx); } - self.paint_definitions.borrow_mut().get_mut(name) + unsafe { + JS_ClearPendingException(cx); + } + self.paint_definitions + .borrow_mut() + .get_mut(name) .expect("Vanishing paint definition.") - .constructor_valid_flag.set(false); + .constructor_valid_flag + .set(false); return self.invalid_image(size_in_dpx, vec![]); } // Step 5.4 - entry.insert(Box::new(Heap::default())).set(paint_instance.get()); - } + entry + .insert(Box::new(Heap::default())) + .set(paint_instance.get()); + }, }; // TODO: Steps 6-7 @@ -271,10 +326,12 @@ impl PaintWorkletGlobalScope { debug!("Invoking paint function {}.", name); rooted_vec!(let arguments_values <- arguments.iter().cloned() .map(|argument| CSSStyleValue::new(self.upcast(), argument))); - let arguments_value_vec: Vec<JSVal> = arguments_values.iter() + let arguments_value_vec: Vec<JSVal> = arguments_values + .iter() .map(|argument| ObjectValue(argument.reflector().get_jsobject().get())) .collect(); - let arguments_value_array = unsafe { HandleValueArray::from_rooted_slice(&*arguments_value_vec) }; + let arguments_value_array = + unsafe { HandleValueArray::from_rooted_slice(&*arguments_value_vec) }; rooted!(in(cx) let argument_object = unsafe { JS_NewArrayObject(cx, &arguments_value_array) }); let args_slice = [ @@ -286,18 +343,28 @@ impl PaintWorkletGlobalScope { let args = unsafe { HandleValueArray::from_rooted_slice(&args_slice) }; rooted!(in(cx) let mut result = UndefinedValue()); - unsafe { Call(cx, paint_instance.handle(), paint_function.handle(), &args, result.handle_mut()); } + unsafe { + Call( + cx, + paint_instance.handle(), + paint_function.handle(), + &args, + result.handle_mut(), + ); + } let missing_image_urls = rendering_context.take_missing_image_urls(); // Step 13. if unsafe { JS_IsExceptionPending(cx) } { debug!("Paint function threw an exception {}.", name); - unsafe { JS_ClearPendingException(cx); } + unsafe { + JS_ClearPendingException(cx); + } return self.invalid_image(size_in_dpx, missing_image_urls); } - let (sender, receiver) = - ipc::channel(self.global().time_profiler_chan().clone()).expect("IPC channel creation."); + let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()) + .expect("IPC channel creation."); rendering_context.send_data(sender); let image_key = match receiver.recv() { Ok(data) => Some(data.image_key), @@ -314,8 +381,11 @@ impl PaintWorkletGlobalScope { } // https://drafts.csswg.org/css-images-4/#invalid-image - fn invalid_image(&self, size: TypedSize2D<u32, DevicePixel>, missing_image_urls: Vec<ServoUrl>) - -> DrawAPaintImageResult { + fn invalid_image( + &self, + size: TypedSize2D<u32, DevicePixel>, + missing_image_urls: Vec<ServoUrl>, + ) -> DrawAPaintImageResult { debug!("Returning an invalid image."); DrawAPaintImageResult { width: size.width as u32, @@ -333,36 +403,47 @@ impl PaintWorkletGlobalScope { executor: Mutex<WorkletExecutor>, } impl SpeculativePainter for WorkletPainter { - fn speculatively_draw_a_paint_image(&self, - properties: Vec<(Atom, String)>, - arguments: Vec<String>) { + fn speculatively_draw_a_paint_image( + &self, + properties: Vec<(Atom, String)>, + arguments: Vec<String>, + ) { let name = self.name.clone(); - let task = PaintWorkletTask::SpeculativelyDrawAPaintImage(name, properties, arguments); - self.executor.lock().expect("Locking a painter.") + let task = + PaintWorkletTask::SpeculativelyDrawAPaintImage(name, properties, arguments); + self.executor + .lock() + .expect("Locking a painter.") .schedule_a_worklet_task(WorkletTask::Paint(task)); } } impl Painter for WorkletPainter { - fn draw_a_paint_image(&self, - size: TypedSize2D<f32, CSSPixel>, - device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>, - properties: Vec<(Atom, String)>, - arguments: Vec<String>) - -> Result<DrawAPaintImageResult, PaintWorkletError> { + fn draw_a_paint_image( + &self, + size: TypedSize2D<f32, CSSPixel>, + device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>, + properties: Vec<(Atom, String)>, + arguments: Vec<String>, + ) -> Result<DrawAPaintImageResult, PaintWorkletError> { let name = self.name.clone(); let (sender, receiver) = channel(); - let task = PaintWorkletTask::DrawAPaintImage(name, - size, - device_pixel_ratio, - properties, - arguments, - sender); - self.executor.lock().expect("Locking a painter.") + let task = PaintWorkletTask::DrawAPaintImage( + name, + size, + device_pixel_ratio, + properties, + arguments, + sender, + ); + self.executor + .lock() + .expect("Locking a painter.") .schedule_a_worklet_task(WorkletTask::Paint(task)); - let timeout = PREFS.get("dom.worklet.timeout_ms") - .as_u64() - .unwrap_or(10u64); + let timeout = PREFS + .get("dom.worklet.timeout_ms") + .as_u64() + .unwrap_or(10u64); select! { recv(base_channel::after(Duration::from_millis(timeout))) => { @@ -381,15 +462,15 @@ impl PaintWorkletGlobalScope { /// Tasks which can be peformed by a paint worklet pub enum PaintWorkletTask { - DrawAPaintImage(Atom, - TypedSize2D<f32, CSSPixel>, - TypedScale<f32, CSSPixel, DevicePixel>, - Vec<(Atom, String)>, - Vec<String>, - Sender<DrawAPaintImageResult>), - SpeculativelyDrawAPaintImage(Atom, - Vec<(Atom, String)>, - Vec<String>), + DrawAPaintImage( + Atom, + TypedSize2D<f32, CSSPixel>, + TypedScale<f32, CSSPixel, DevicePixel>, + Vec<(Atom, String)>, + Vec<String>, + Sender<DrawAPaintImageResult>, + ), + SpeculativelyDrawAPaintImage(Atom, Vec<(Atom, String)>, Vec<String>), } /// A paint definition @@ -412,13 +493,13 @@ struct PaintDefinition { } impl PaintDefinition { - fn new(class_constructor: HandleValue, - paint_function: HandleValue, - alpha: bool, - input_arguments_len: usize, - context: &PaintRenderingContext2D) - -> Box<PaintDefinition> - { + fn new( + class_constructor: HandleValue, + paint_function: HandleValue, + alpha: bool, + input_arguments_len: usize, + context: &PaintRenderingContext2D, + ) -> Box<PaintDefinition> { let result = Box::new(PaintDefinition { class_constructor: Heap::default(), paint_function: Heap::default(), @@ -447,7 +528,7 @@ impl PaintWorkletGlobalScopeMethods for PaintWorkletGlobalScope { // Step 1. if name.is_empty() { - return Err(Error::Type(String::from("Empty paint name."))) ; + return Err(Error::Type(String::from("Empty paint name."))); } // Step 2-3. @@ -458,20 +539,19 @@ impl PaintWorkletGlobalScopeMethods for PaintWorkletGlobalScope { // Step 4-6. let mut property_names: Vec<String> = unsafe { get_property(cx, paint_obj.handle(), "inputProperties", ()) }? - .unwrap_or_default(); + .unwrap_or_default(); let properties = property_names.drain(..).map(Atom::from).collect(); // Step 7-9. let input_arguments: Vec<String> = unsafe { get_property(cx, paint_obj.handle(), "inputArguments", ()) }? - .unwrap_or_default(); + .unwrap_or_default(); // TODO: Steps 10-11. // Steps 12-13. let alpha: bool = - unsafe { get_property(cx, paint_obj.handle(), "alpha", ()) }? - .unwrap_or(true); + unsafe { get_property(cx, paint_obj.handle(), "alpha", ()) }?.unwrap_or(true); // Step 14 if unsafe { !IsConstructor(paint_obj.get()) } { @@ -480,7 +560,9 @@ impl PaintWorkletGlobalScopeMethods for PaintWorkletGlobalScope { // Steps 15-16 rooted!(in(cx) let mut prototype = UndefinedValue()); - unsafe { get_property_jsval(cx, paint_obj.handle(), "prototype", prototype.handle_mut())?; } + unsafe { + get_property_jsval(cx, paint_obj.handle(), "prototype", prototype.handle_mut())?; + } if !prototype.is_object() { return Err(Error::Type(String::from("Prototype is not an object."))); } @@ -488,29 +570,36 @@ impl PaintWorkletGlobalScopeMethods for PaintWorkletGlobalScope { // Steps 17-18 rooted!(in(cx) let mut paint_function = UndefinedValue()); - unsafe { get_property_jsval(cx, prototype.handle(), "paint", paint_function.handle_mut())?; } + unsafe { + get_property_jsval(cx, prototype.handle(), "paint", paint_function.handle_mut())?; + } if !paint_function.is_object() || unsafe { !IsCallable(paint_function.to_object()) } { return Err(Error::Type(String::from("Paint function is not callable."))); } // Step 19. let context = PaintRenderingContext2D::new(self); - let definition = PaintDefinition::new(paint_val.handle(), - paint_function.handle(), - alpha, - input_arguments.len(), - &*context); + let definition = PaintDefinition::new( + paint_val.handle(), + paint_function.handle(), + alpha, + input_arguments.len(), + &*context, + ); // Step 20. debug!("Registering definition {}.", name); - self.paint_definitions.borrow_mut().insert(name.clone(), definition); + self.paint_definitions + .borrow_mut() + .insert(name.clone(), definition); // TODO: Step 21. // Inform layout that there is a registered paint worklet. // TODO: layout will end up getting this message multiple times. let painter = self.painter(name.clone()); - self.worklet_global.register_paint_worklet(name, properties, painter); + self.worklet_global + .register_paint_worklet(name, properties, painter); Ok(()) } diff --git a/components/script/dom/pannernode.rs b/components/script/dom/pannernode.rs index 5f6124826f4..80453693d6a 100644 --- a/components/script/dom/pannernode.rs +++ b/components/script/dom/pannernode.rs @@ -51,26 +51,28 @@ impl PannerNode { context: &BaseAudioContext, options: &PannerOptions, ) -> Fallible<PannerNode> { - let node_options = options.parent - .unwrap_or(2, ChannelCountMode::Clamped_max, - ChannelInterpretation::Speakers); + let node_options = options.parent.unwrap_or( + 2, + ChannelCountMode::Clamped_max, + ChannelInterpretation::Speakers, + ); if node_options.mode == ChannelCountMode::Max { - return Err(Error::NotSupported) + return Err(Error::NotSupported); } if node_options.count > 2 || node_options.count == 0 { - return Err(Error::NotSupported) + return Err(Error::NotSupported); } if *options.maxDistance <= 0. { - return Err(Error::Range("maxDistance should be positive".into())) + return Err(Error::Range("maxDistance should be positive".into())); } if *options.refDistance < 0. { - return Err(Error::Range("refDistance should be non-negative".into())) + return Err(Error::Range("refDistance should be non-negative".into())); } if *options.rolloffFactor < 0. { - return Err(Error::Range("rolloffFactor should be non-negative".into())) + return Err(Error::Range("rolloffFactor should be non-negative".into())); } if *options.coneOuterGain < 0. || *options.coneOuterGain > 1. { - return Err(Error::InvalidState) + return Err(Error::InvalidState); } let options = options.into(); let node = AudioNode::new_inherited( @@ -87,9 +89,9 @@ impl PannerNode { id, ParamType::Position(ParamDir::X), AutomationRate::A_rate, - options.position_x, // default value - f32::MIN, // min value - f32::MAX, // max value + options.position_x, // default value + f32::MIN, // min value + f32::MAX, // max value ); let position_y = AudioParam::new( window, @@ -97,9 +99,9 @@ impl PannerNode { id, ParamType::Position(ParamDir::Y), AutomationRate::A_rate, - options.position_y, // default value - f32::MIN, // min value - f32::MAX, // max value + options.position_y, // default value + f32::MIN, // min value + f32::MAX, // max value ); let position_z = AudioParam::new( window, @@ -107,9 +109,9 @@ impl PannerNode { id, ParamType::Position(ParamDir::Z), AutomationRate::A_rate, - options.position_z, // default value - f32::MIN, // min value - f32::MAX, // max value + options.position_z, // default value + f32::MIN, // min value + f32::MAX, // max value ); let orientation_x = AudioParam::new( window, @@ -117,9 +119,9 @@ impl PannerNode { id, ParamType::Orientation(ParamDir::X), AutomationRate::A_rate, - options.orientation_x, // default value - f32::MIN, // min value - f32::MAX, // max value + options.orientation_x, // default value + f32::MIN, // min value + f32::MAX, // max value ); let orientation_y = AudioParam::new( window, @@ -127,9 +129,9 @@ impl PannerNode { id, ParamType::Orientation(ParamDir::Y), AutomationRate::A_rate, - options.orientation_y, // default value - f32::MIN, // min value - f32::MAX, // max value + options.orientation_y, // default value + f32::MIN, // min value + f32::MAX, // max value ); let orientation_z = AudioParam::new( window, @@ -137,9 +139,9 @@ impl PannerNode { id, ParamType::Orientation(ParamDir::Z), AutomationRate::A_rate, - options.orientation_z, // default value - f32::MIN, // min value - f32::MAX, // max value + options.orientation_z, // default value + f32::MIN, // min value + f32::MAX, // max value ); Ok(PannerNode { node, @@ -167,7 +169,11 @@ impl PannerNode { options: &PannerOptions, ) -> Fallible<DomRoot<PannerNode>> { let node = PannerNode::new_inherited(window, context, options)?; - Ok(reflect_dom_object(Box::new(node), window, PannerNodeBinding::Wrap)) + Ok(reflect_dom_object( + Box::new(node), + window, + PannerNodeBinding::Wrap, + )) } pub fn Constructor( @@ -218,7 +224,8 @@ impl PannerNodeMethods for PannerNode { fn SetDistanceModel(&self, model: DistanceModelType) { self.distance_model.set(model.into()); let msg = PannerNodeMessage::SetDistanceModel(self.distance_model.get()); - self.upcast::<AudioNode>().message(AudioNodeMessage::PannerNode(msg)); + self.upcast::<AudioNode>() + .message(AudioNodeMessage::PannerNode(msg)); } // https://webaudio.github.io/web-audio-api/#dom-pannernode-panningmodel fn PanningModel(&self) -> PanningModelType { @@ -231,7 +238,8 @@ impl PannerNodeMethods for PannerNode { fn SetPanningModel(&self, model: PanningModelType) { self.panning_model.set(model.into()); let msg = PannerNodeMessage::SetPanningModel(self.panning_model.get()); - self.upcast::<AudioNode>().message(AudioNodeMessage::PannerNode(msg)); + self.upcast::<AudioNode>() + .message(AudioNodeMessage::PannerNode(msg)); } // https://webaudio.github.io/web-audio-api/#dom-pannernode-refdistance fn RefDistance(&self) -> Finite<f64> { @@ -240,11 +248,12 @@ impl PannerNodeMethods for PannerNode { // https://webaudio.github.io/web-audio-api/#dom-pannernode-refdistance fn SetRefDistance(&self, val: Finite<f64>) -> Fallible<()> { if *val < 0. { - return Err(Error::Range("value should be non-negative".into())) + return Err(Error::Range("value should be non-negative".into())); } self.ref_distance.set(*val); let msg = PannerNodeMessage::SetRefDistance(self.ref_distance.get()); - self.upcast::<AudioNode>().message(AudioNodeMessage::PannerNode(msg)); + self.upcast::<AudioNode>() + .message(AudioNodeMessage::PannerNode(msg)); Ok(()) } // https://webaudio.github.io/web-audio-api/#dom-pannernode-maxdistance @@ -254,11 +263,12 @@ impl PannerNodeMethods for PannerNode { // https://webaudio.github.io/web-audio-api/#dom-pannernode-maxdistance fn SetMaxDistance(&self, val: Finite<f64>) -> Fallible<()> { if *val <= 0. { - return Err(Error::Range("value should be positive".into())) + return Err(Error::Range("value should be positive".into())); } self.max_distance.set(*val); let msg = PannerNodeMessage::SetMaxDistance(self.max_distance.get()); - self.upcast::<AudioNode>().message(AudioNodeMessage::PannerNode(msg)); + self.upcast::<AudioNode>() + .message(AudioNodeMessage::PannerNode(msg)); Ok(()) } // https://webaudio.github.io/web-audio-api/#dom-pannernode-rollofffactor @@ -268,11 +278,12 @@ impl PannerNodeMethods for PannerNode { // https://webaudio.github.io/web-audio-api/#dom-pannernode-rollofffactor fn SetRolloffFactor(&self, val: Finite<f64>) -> Fallible<()> { if *val < 0. { - return Err(Error::Range("value should be non-negative".into())) + return Err(Error::Range("value should be non-negative".into())); } self.rolloff_factor.set(*val); let msg = PannerNodeMessage::SetRolloff(self.rolloff_factor.get()); - self.upcast::<AudioNode>().message(AudioNodeMessage::PannerNode(msg)); + self.upcast::<AudioNode>() + .message(AudioNodeMessage::PannerNode(msg)); Ok(()) } // https://webaudio.github.io/web-audio-api/#dom-pannernode-coneinnerangle @@ -283,7 +294,8 @@ impl PannerNodeMethods for PannerNode { fn SetConeInnerAngle(&self, val: Finite<f64>) { self.cone_inner_angle.set(*val); let msg = PannerNodeMessage::SetConeInner(self.cone_inner_angle.get()); - self.upcast::<AudioNode>().message(AudioNodeMessage::PannerNode(msg)); + self.upcast::<AudioNode>() + .message(AudioNodeMessage::PannerNode(msg)); } // https://webaudio.github.io/web-audio-api/#dom-pannernode-coneouterangle fn ConeOuterAngle(&self) -> Finite<f64> { @@ -293,7 +305,8 @@ impl PannerNodeMethods for PannerNode { fn SetConeOuterAngle(&self, val: Finite<f64>) { self.cone_outer_angle.set(*val); let msg = PannerNodeMessage::SetConeOuter(self.cone_outer_angle.get()); - self.upcast::<AudioNode>().message(AudioNodeMessage::PannerNode(msg)); + self.upcast::<AudioNode>() + .message(AudioNodeMessage::PannerNode(msg)); } // https://webaudio.github.io/web-audio-api/#dom-pannernode-coneoutergain fn ConeOuterGain(&self) -> Finite<f64> { @@ -302,11 +315,12 @@ impl PannerNodeMethods for PannerNode { // https://webaudio.github.io/web-audio-api/#dom-pannernode-coneoutergain fn SetConeOuterGain(&self, val: Finite<f64>) -> Fallible<()> { if *val < 0. || *val > 1. { - return Err(Error::InvalidState) + return Err(Error::InvalidState); } self.cone_outer_gain.set(*val); let msg = PannerNodeMessage::SetConeGain(self.cone_outer_gain.get()); - self.upcast::<AudioNode>().message(AudioNodeMessage::PannerNode(msg)); + self.upcast::<AudioNode>() + .message(AudioNodeMessage::PannerNode(msg)); Ok(()) } diff --git a/components/script/dom/performance.rs b/components/script/dom/performance.rs index 4a9a9672b4e..f421822fc86 100644 --- a/components/script/dom/performance.rs +++ b/components/script/dom/performance.rs @@ -58,35 +58,54 @@ pub struct PerformanceEntryList { impl PerformanceEntryList { pub fn new(entries: DOMPerformanceEntryList) -> Self { - PerformanceEntryList { - entries, - } + PerformanceEntryList { entries } } - pub fn get_entries_by_name_and_type(&self, name: Option<DOMString>, entry_type: Option<DOMString>) - -> Vec<DomRoot<PerformanceEntry>> { - let mut res = self.entries.iter().filter(|e| - name.as_ref().map_or(true, |name_| *e.name() == *name_) && - entry_type.as_ref().map_or(true, |type_| *e.entry_type() == *type_) - ).map(|e| e.clone()).collect::<Vec<DomRoot<PerformanceEntry>>>(); - res.sort_by(|a, b| a.start_time().partial_cmp(&b.start_time()).unwrap_or(Ordering::Equal)); + pub fn get_entries_by_name_and_type( + &self, + name: Option<DOMString>, + entry_type: Option<DOMString>, + ) -> Vec<DomRoot<PerformanceEntry>> { + let mut res = self + .entries + .iter() + .filter(|e| { + name.as_ref().map_or(true, |name_| *e.name() == *name_) && entry_type + .as_ref() + .map_or(true, |type_| *e.entry_type() == *type_) + }).map(|e| e.clone()) + .collect::<Vec<DomRoot<PerformanceEntry>>>(); + res.sort_by(|a, b| { + a.start_time() + .partial_cmp(&b.start_time()) + .unwrap_or(Ordering::Equal) + }); res } - pub fn clear_entries_by_name_and_type(&mut self, name: Option<DOMString>, - entry_type: Option<DOMString>) { - self.entries.retain(|e| - name.as_ref().map_or(true, |name_| *e.name() == *name_) && - entry_type.as_ref().map_or(true, |type_| *e.entry_type() == *type_) - ); + pub fn clear_entries_by_name_and_type( + &mut self, + name: Option<DOMString>, + entry_type: Option<DOMString>, + ) { + self.entries.retain(|e| { + name.as_ref().map_or(true, |name_| *e.name() == *name_) && entry_type + .as_ref() + .map_or(true, |type_| *e.entry_type() == *type_) + }); } - fn get_last_entry_start_time_with_name_and_type(&self, name: DOMString, - entry_type: DOMString) -> f64 { - match self.entries.iter() - .rev() - .find(|e| *e.entry_type() == *entry_type && - *e.name() == *name) { + fn get_last_entry_start_time_with_name_and_type( + &self, + name: DOMString, + entry_type: DOMString, + ) -> f64 { + match self + .entries + .iter() + .rev() + .find(|e| *e.entry_type() == *entry_type && *e.name() == *name) + { Some(entry) => entry.start_time(), None => 0., } @@ -119,15 +138,19 @@ pub struct Performance { } impl Performance { - fn new_inherited(global: &GlobalScope, - navigation_start: u64, - navigation_start_precise: u64) -> Performance { + fn new_inherited( + global: &GlobalScope, + navigation_start: u64, + navigation_start_precise: u64, + ) -> Performance { Performance { reflector_: Reflector::new(), timing: if global.is::<Window>() { - Some(Dom::from_ref(&*PerformanceTiming::new(global.as_window(), - navigation_start, - navigation_start_precise))) + Some(Dom::from_ref(&*PerformanceTiming::new( + global.as_window(), + navigation_start, + navigation_start_precise, + ))) } else { None }, @@ -138,27 +161,36 @@ impl Performance { } } - pub fn new(global: &GlobalScope, - navigation_start: u64, - navigation_start_precise: u64) -> DomRoot<Performance> { + pub fn new( + global: &GlobalScope, + navigation_start: u64, + navigation_start_precise: u64, + ) -> DomRoot<Performance> { reflect_dom_object( - Box::new(Performance::new_inherited(global, navigation_start, navigation_start_precise)), + Box::new(Performance::new_inherited( + global, + navigation_start, + navigation_start_precise, + )), global, - PerformanceBinding::Wrap + PerformanceBinding::Wrap, ) } /// Add a PerformanceObserver to the list of observers with a set of /// observed entry types. - pub fn add_observer(&self, - observer: &DOMPerformanceObserver, - entry_types: Vec<DOMString>, - buffered: bool) { + pub fn add_observer( + &self, + observer: &DOMPerformanceObserver, + entry_types: Vec<DOMString>, + buffered: bool, + ) { if buffered { let entries = self.entries.borrow(); - let mut new_entries = entry_types.iter() - .flat_map(|e| entries.get_entries_by_name_and_type(None, Some(e.clone()))) - .collect::<DOMPerformanceEntryList>(); + let mut new_entries = entry_types + .iter() + .flat_map(|e| entries.get_entries_by_name_and_type(None, Some(e.clone()))) + .collect::<DOMPerformanceEntryList>(); let mut obs_entries = observer.entries(); obs_entries.append(&mut new_entries); observer.set_entries(obs_entries); @@ -171,8 +203,8 @@ impl Performance { // Otherwise, we create and insert the new PerformanceObserver. None => observers.push(PerformanceObserver { observer: DomRoot::from_ref(observer), - entry_types - }) + entry_types, + }), }; } @@ -193,13 +225,17 @@ impl Performance { /// /// Algorithm spec: /// <https://w3c.github.io/performance-timeline/#queue-a-performanceentry> - pub fn queue_entry(&self, entry: &PerformanceEntry, - add_to_performance_entries_buffer: bool) { + pub fn queue_entry(&self, entry: &PerformanceEntry, add_to_performance_entries_buffer: bool) { // Steps 1-3. // Add the performance entry to the list of performance entries that have not // been notified to each performance observer owner, filtering the ones it's // interested in. - for o in self.observers.borrow().iter().filter(|o| o.entry_types.contains(entry.entry_type())) { + for o in self + .observers + .borrow() + .iter() + .filter(|o| o.entry_types.contains(entry.entry_type())) + { o.observer.queue_entry(entry); } @@ -207,7 +243,10 @@ impl Performance { // If the "add to performance entry buffer flag" is set, add the // new entry to the buffer. if add_to_performance_entries_buffer { - self.entries.borrow_mut().entries.push(DomRoot::from_ref(entry)); + self.entries + .borrow_mut() + .entries + .push(DomRoot::from_ref(entry)); } // Step 5. @@ -235,12 +274,17 @@ impl Performance { // We have to operate over a copy of the performance observers to avoid // the risk of an observer's callback modifying the list of registered // observers. - let observers: Vec<DomRoot<DOMPerformanceObserver>> = - self.observers.borrow().iter() - .map(|o| DOMPerformanceObserver::new(&self.global(), - o.observer.callback(), - o.observer.entries())) - .collect(); + let observers: Vec<DomRoot<DOMPerformanceObserver>> = self + .observers + .borrow() + .iter() + .map(|o| { + DOMPerformanceObserver::new( + &self.global(), + o.observer.callback(), + o.observer.entries(), + ) + }).collect(); // Step 7.3. for o in observers.iter() { @@ -273,18 +317,27 @@ impl PerformanceMethods for Performance { // https://www.w3.org/TR/performance-timeline-2/#dom-performance-getentries fn GetEntries(&self) -> Vec<DomRoot<PerformanceEntry>> { - self.entries.borrow().get_entries_by_name_and_type(None, None) + self.entries + .borrow() + .get_entries_by_name_and_type(None, None) } // https://www.w3.org/TR/performance-timeline-2/#dom-performance-getentriesbytype fn GetEntriesByType(&self, entry_type: DOMString) -> Vec<DomRoot<PerformanceEntry>> { - self.entries.borrow().get_entries_by_name_and_type(None, Some(entry_type)) + self.entries + .borrow() + .get_entries_by_name_and_type(None, Some(entry_type)) } // https://www.w3.org/TR/performance-timeline-2/#dom-performance-getentriesbyname - fn GetEntriesByName(&self, name: DOMString, entry_type: Option<DOMString>) - -> Vec<DomRoot<PerformanceEntry>> { - self.entries.borrow().get_entries_by_name_and_type(Some(name), entry_type) + fn GetEntriesByName( + &self, + name: DOMString, + entry_type: Option<DOMString>, + ) -> Vec<DomRoot<PerformanceEntry>> { + self.entries + .borrow() + .get_entries_by_name_and_type(Some(name), entry_type) } // https://w3c.github.io/user-timing/#dom-performance-mark @@ -296,13 +349,12 @@ impl PerformanceMethods for Performance { } // Steps 2 to 6. - let entry = PerformanceMark::new(&global, - mark_name, - self.now(), - 0.); + let entry = PerformanceMark::new(&global, mark_name, self.now(), 0.); // Steps 7 and 8. - self.queue_entry(&entry.upcast::<PerformanceEntry>(), - true /* buffer performance entry */); + self.queue_entry( + &entry.upcast::<PerformanceEntry>(), + true, /* buffer performance entry */ + ); // Step 9. Ok(()) @@ -310,40 +362,49 @@ impl PerformanceMethods for Performance { // https://w3c.github.io/user-timing/#dom-performance-clearmarks fn ClearMarks(&self, mark_name: Option<DOMString>) { - self.entries.borrow_mut().clear_entries_by_name_and_type(mark_name, - Some(DOMString::from("mark"))); + self.entries + .borrow_mut() + .clear_entries_by_name_and_type(mark_name, Some(DOMString::from("mark"))); } // https://w3c.github.io/user-timing/#dom-performance-measure - fn Measure(&self, - measure_name: DOMString, - start_mark: Option<DOMString>, - end_mark: Option<DOMString>) -> Fallible<()> { + fn Measure( + &self, + measure_name: DOMString, + start_mark: Option<DOMString>, + end_mark: Option<DOMString>, + ) -> Fallible<()> { // Steps 1 and 2. let end_time = match end_mark { - Some(name) => - self.entries.borrow().get_last_entry_start_time_with_name_and_type( - DOMString::from("mark"), name), + Some(name) => self + .entries + .borrow() + .get_last_entry_start_time_with_name_and_type(DOMString::from("mark"), name), None => self.now(), }; // Step 3. let start_time = match start_mark { - Some(name) => - self.entries.borrow().get_last_entry_start_time_with_name_and_type( - DOMString::from("mark"), name), + Some(name) => self + .entries + .borrow() + .get_last_entry_start_time_with_name_and_type(DOMString::from("mark"), name), None => 0., }; // Steps 4 to 8. - let entry = PerformanceMeasure::new(&self.global(), - measure_name, - start_time, - end_time - start_time); + let entry = PerformanceMeasure::new( + &self.global(), + measure_name, + start_time, + end_time - start_time, + ); // Step 9 and 10. - self.queue_entry(&entry.upcast::<PerformanceEntry>(), - true /* buffer performance entry */); + self.queue_entry( + &entry.upcast::<PerformanceEntry>(), + true, /* buffer performance entry */ + ); // Step 11. Ok(()) @@ -351,7 +412,8 @@ impl PerformanceMethods for Performance { // https://w3c.github.io/user-timing/#dom-performance-clearmeasures fn ClearMeasures(&self, measure_name: Option<DOMString>) { - self.entries.borrow_mut().clear_entries_by_name_and_type(measure_name, - Some(DOMString::from("measure"))); + self.entries + .borrow_mut() + .clear_entries_by_name_and_type(measure_name, Some(DOMString::from("measure"))); } } diff --git a/components/script/dom/performanceentry.rs b/components/script/dom/performanceentry.rs index 964a808143b..71ab83fb42b 100644 --- a/components/script/dom/performanceentry.rs +++ b/components/script/dom/performanceentry.rs @@ -21,10 +21,12 @@ pub struct PerformanceEntry { } impl PerformanceEntry { - pub fn new_inherited(name: DOMString, - entry_type: DOMString, - start_time: f64, - duration: f64) -> PerformanceEntry { + pub fn new_inherited( + name: DOMString, + entry_type: DOMString, + start_time: f64, + duration: f64, + ) -> PerformanceEntry { PerformanceEntry { reflector_: Reflector::new(), name, @@ -35,11 +37,13 @@ impl PerformanceEntry { } #[allow(unrooted_must_root)] - pub fn new(global: &GlobalScope, - name: DOMString, - entry_type: DOMString, - start_time: f64, - duration: f64) -> DomRoot<PerformanceEntry> { + pub fn new( + global: &GlobalScope, + name: DOMString, + entry_type: DOMString, + start_time: f64, + duration: f64, + ) -> DomRoot<PerformanceEntry> { let entry = PerformanceEntry::new_inherited(name, entry_type, start_time, duration); reflect_dom_object(Box::new(entry), global, PerformanceEntryBinding::Wrap) } diff --git a/components/script/dom/performancemark.rs b/components/script/dom/performancemark.rs index 36208a98645..27bc31f885d 100644 --- a/components/script/dom/performancemark.rs +++ b/components/script/dom/performancemark.rs @@ -2,6 +2,4 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -impl_performance_entry_struct!(PerformanceMarkBinding, - PerformanceMark, - "mark"); +impl_performance_entry_struct!(PerformanceMarkBinding, PerformanceMark, "mark"); diff --git a/components/script/dom/performancemeasure.rs b/components/script/dom/performancemeasure.rs index 79b185e2e25..61e292196dd 100644 --- a/components/script/dom/performancemeasure.rs +++ b/components/script/dom/performancemeasure.rs @@ -2,6 +2,4 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -impl_performance_entry_struct!(PerformanceMeasureBinding, - PerformanceMeasure, - "measure"); +impl_performance_entry_struct!(PerformanceMeasureBinding, PerformanceMeasure, "measure"); diff --git a/components/script/dom/performanceobserver.rs b/components/script/dom/performanceobserver.rs index af43fe76246..fd51faafbe6 100644 --- a/components/script/dom/performanceobserver.rs +++ b/components/script/dom/performanceobserver.rs @@ -22,7 +22,7 @@ use std::rc::Rc; /// List of allowed performance entry types. const VALID_ENTRY_TYPES: &'static [&'static str] = &[ - "mark", // User Timing API + "mark", // User Timing API "measure", // User Timing API // "resource", XXX Resource Timing API // "server", XXX Server Timing API @@ -38,9 +38,10 @@ pub struct PerformanceObserver { } impl PerformanceObserver { - fn new_inherited(callback: Rc<PerformanceObserverCallback>, - entries: DomRefCell<DOMPerformanceEntryList>) - -> PerformanceObserver { + fn new_inherited( + callback: Rc<PerformanceObserverCallback>, + entries: DomRefCell<DOMPerformanceEntryList>, + ) -> PerformanceObserver { PerformanceObserver { reflector_: Reflector::new(), callback, @@ -49,16 +50,19 @@ impl PerformanceObserver { } #[allow(unrooted_must_root)] - pub fn new(global: &GlobalScope, - callback: Rc<PerformanceObserverCallback>, - entries: DOMPerformanceEntryList) - -> DomRoot<PerformanceObserver> { + pub fn new( + global: &GlobalScope, + callback: Rc<PerformanceObserverCallback>, + entries: DOMPerformanceEntryList, + ) -> DomRoot<PerformanceObserver> { let observer = PerformanceObserver::new_inherited(callback, DomRefCell::new(entries)); reflect_dom_object(Box::new(observer), global, PerformanceObserverBinding::Wrap) } - pub fn Constructor(global: &GlobalScope, callback: Rc<PerformanceObserverCallback>) - -> Fallible<DomRoot<PerformanceObserver>> { + pub fn Constructor( + global: &GlobalScope, + callback: Rc<PerformanceObserverCallback>, + ) -> Fallible<DomRoot<PerformanceObserver>> { Ok(PerformanceObserver::new(global, callback, Vec::new())) } @@ -78,7 +82,9 @@ impl PerformanceObserver { let global = self.global(); let entry_list = PerformanceEntryList::new(entries.drain(..).collect()); let observer_entry_list = PerformanceObserverEntryList::new(&global, entry_list); - let _ = self.callback.Call__(&observer_entry_list, self, ExceptionHandling::Report); + let _ = self + .callback + .Call__(&observer_entry_list, self, ExceptionHandling::Report); } pub fn callback(&self) -> Rc<PerformanceObserverCallback> { @@ -99,10 +105,12 @@ impl PerformanceObserverMethods for PerformanceObserver { fn Observe(&self, options: &PerformanceObserverInit) -> Fallible<()> { // step 1 // Make sure the client is asking to observe events from allowed entry types. - let entry_types = options.entryTypes.iter() - .filter(|e| VALID_ENTRY_TYPES.contains(&e.as_ref())) - .map(|e| e.clone()) - .collect::<Vec<DOMString>>(); + let entry_types = options + .entryTypes + .iter() + .filter(|e| VALID_ENTRY_TYPES.contains(&e.as_ref())) + .map(|e| e.clone()) + .collect::<Vec<DOMString>>(); // step 2 // There must be at least one valid entry type. if entry_types.is_empty() { @@ -110,7 +118,9 @@ impl PerformanceObserverMethods for PerformanceObserver { } // step 3-4-5 - self.global().performance().add_observer(self, entry_types, options.buffered); + self.global() + .performance() + .add_observer(self, entry_types, options.buffered); Ok(()) } diff --git a/components/script/dom/performanceobserverentrylist.rs b/components/script/dom/performanceobserverentrylist.rs index 4721a5bf440..5b45a7267fb 100644 --- a/components/script/dom/performanceobserverentrylist.rs +++ b/components/script/dom/performanceobserverentrylist.rs @@ -28,27 +28,42 @@ impl PerformanceObserverEntryList { } #[allow(unrooted_must_root)] - pub fn new(global: &GlobalScope, entries: PerformanceEntryList) - -> DomRoot<PerformanceObserverEntryList> { + pub fn new( + global: &GlobalScope, + entries: PerformanceEntryList, + ) -> DomRoot<PerformanceObserverEntryList> { let observer_entry_list = PerformanceObserverEntryList::new_inherited(entries); - reflect_dom_object(Box::new(observer_entry_list), global, PerformanceObserverEntryListBinding::Wrap) + reflect_dom_object( + Box::new(observer_entry_list), + global, + PerformanceObserverEntryListBinding::Wrap, + ) } } impl PerformanceObserverEntryListMethods for PerformanceObserverEntryList { // https://w3c.github.io/performance-timeline/#dom-performanceobserver fn GetEntries(&self) -> Vec<DomRoot<PerformanceEntry>> { - self.entries.borrow().get_entries_by_name_and_type(None, None) + self.entries + .borrow() + .get_entries_by_name_and_type(None, None) } // https://w3c.github.io/performance-timeline/#dom-performanceobserver fn GetEntriesByType(&self, entry_type: DOMString) -> Vec<DomRoot<PerformanceEntry>> { - self.entries.borrow().get_entries_by_name_and_type(None, Some(entry_type)) + self.entries + .borrow() + .get_entries_by_name_and_type(None, Some(entry_type)) } // https://w3c.github.io/performance-timeline/#dom-performanceobserver - fn GetEntriesByName(&self, name: DOMString, entry_type: Option<DOMString>) - -> Vec<DomRoot<PerformanceEntry>> { - self.entries.borrow().get_entries_by_name_and_type(Some(name), entry_type) + fn GetEntriesByName( + &self, + name: DOMString, + entry_type: Option<DOMString>, + ) -> Vec<DomRoot<PerformanceEntry>> { + self.entries + .borrow() + .get_entries_by_name_and_type(Some(name), entry_type) } } diff --git a/components/script/dom/performancepainttiming.rs b/components/script/dom/performancepainttiming.rs index 4dc4adb4993..bef691a99cd 100644 --- a/components/script/dom/performancepainttiming.rs +++ b/components/script/dom/performancepainttiming.rs @@ -18,24 +18,33 @@ pub struct PerformancePaintTiming { } impl PerformancePaintTiming { - fn new_inherited(metric_type: ProgressiveWebMetricType, start_time: u64) -> PerformancePaintTiming { + fn new_inherited( + metric_type: ProgressiveWebMetricType, + start_time: u64, + ) -> PerformancePaintTiming { let name = match metric_type { ProgressiveWebMetricType::FirstPaint => DOMString::from("first-paint"), - ProgressiveWebMetricType::FirstContentfulPaint => DOMString::from("first-contentful-paint"), + ProgressiveWebMetricType::FirstContentfulPaint => { + DOMString::from("first-contentful-paint") + }, _ => DOMString::from(""), }; PerformancePaintTiming { - entry: PerformanceEntry::new_inherited(name, - DOMString::from("paint"), - start_time.to_ms(), - 0.) + entry: PerformanceEntry::new_inherited( + name, + DOMString::from("paint"), + start_time.to_ms(), + 0., + ), } } #[allow(unrooted_must_root)] - pub fn new(global: &GlobalScope, - metric_type: ProgressiveWebMetricType, - start_time: u64) -> DomRoot<PerformancePaintTiming> { + pub fn new( + global: &GlobalScope, + metric_type: ProgressiveWebMetricType, + start_time: u64, + ) -> DomRoot<PerformancePaintTiming> { let entry = PerformancePaintTiming::new_inherited(metric_type, start_time); reflect_dom_object(Box::new(entry), global, PerformancePaintTimingBinding::Wrap) } diff --git a/components/script/dom/performancetiming.rs b/components/script/dom/performancetiming.rs index 7df8e9d2c76..22dd840d019 100644 --- a/components/script/dom/performancetiming.rs +++ b/components/script/dom/performancetiming.rs @@ -20,10 +20,11 @@ pub struct PerformanceTiming { } impl PerformanceTiming { - fn new_inherited(nav_start: u64, - nav_start_precise: u64, - document: &Document) - -> PerformanceTiming { + fn new_inherited( + nav_start: u64, + nav_start_precise: u64, + document: &Document, + ) -> PerformanceTiming { PerformanceTiming { reflector_: Reflector::new(), navigation_start: nav_start, @@ -33,16 +34,17 @@ impl PerformanceTiming { } #[allow(unrooted_must_root)] - pub fn new(window: &Window, - navigation_start: u64, - navigation_start_precise: u64) - -> DomRoot<PerformanceTiming> { - let timing = PerformanceTiming::new_inherited(navigation_start, - navigation_start_precise, - &window.Document()); - reflect_dom_object(Box::new(timing), - window, - PerformanceTimingBinding::Wrap) + pub fn new( + window: &Window, + navigation_start: u64, + navigation_start_precise: u64, + ) -> DomRoot<PerformanceTiming> { + let timing = PerformanceTiming::new_inherited( + navigation_start, + navigation_start_precise, + &window.Document(), + ); + reflect_dom_object(Box::new(timing), window, PerformanceTimingBinding::Wrap) } } @@ -94,7 +96,6 @@ impl PerformanceTimingMethods for PerformanceTiming { } } - impl PerformanceTiming { pub fn navigation_start_precise(&self) -> u64 { self.navigation_start_precise diff --git a/components/script/dom/permissions.rs b/components/script/dom/permissions.rs index 04f927322b1..325485ee950 100644 --- a/components/script/dom/permissions.rs +++ b/components/script/dom/permissions.rs @@ -29,18 +29,28 @@ const DIALOG_TITLE: &'static str = "Permission request dialog"; const NONSECURE_DIALOG_MESSAGE: &'static str = "feature is only safe to use in secure context,\ but servo can't guarantee\n that the current context is secure. Do you want to proceed and grant permission?"; const REQUEST_DIALOG_MESSAGE: &'static str = "Do you want to grant permission for"; -const ROOT_DESC_CONVERSION_ERROR: &'static str = "Can't convert to an IDL value of type PermissionDescriptor"; +const ROOT_DESC_CONVERSION_ERROR: &'static str = + "Can't convert to an IDL value of type PermissionDescriptor"; pub trait PermissionAlgorithm { type Descriptor; type Status; - fn create_descriptor(cx: *mut JSContext, - permission_descriptor_obj: *mut JSObject) - -> Result<Self::Descriptor, Error>; - fn permission_query(cx: *mut JSContext, promise: &Rc<Promise>, - descriptor: &Self::Descriptor, status: &Self::Status); - fn permission_request(cx: *mut JSContext, promise: &Rc<Promise>, - descriptor: &Self::Descriptor, status: &Self::Status); + fn create_descriptor( + cx: *mut JSContext, + permission_descriptor_obj: *mut JSObject, + ) -> Result<Self::Descriptor, Error>; + fn permission_query( + cx: *mut JSContext, + promise: &Rc<Promise>, + descriptor: &Self::Descriptor, + status: &Self::Status, + ); + fn permission_request( + cx: *mut JSContext, + promise: &Rc<Promise>, + descriptor: &Self::Descriptor, + status: &Self::Status, + ); fn permission_revoke(descriptor: &Self::Descriptor, status: &Self::Status); } @@ -64,21 +74,24 @@ impl Permissions { } pub fn new(global: &GlobalScope) -> DomRoot<Permissions> { - reflect_dom_object(Box::new(Permissions::new_inherited()), - global, - PermissionsBinding::Wrap) + reflect_dom_object( + Box::new(Permissions::new_inherited()), + global, + PermissionsBinding::Wrap, + ) } #[allow(unrooted_must_root)] // https://w3c.github.io/permissions/#dom-permissions-query // https://w3c.github.io/permissions/#dom-permissions-request // https://w3c.github.io/permissions/#dom-permissions-revoke - fn manipulate(&self, - op: Operation, - cx: *mut JSContext, - permissionDesc: *mut JSObject, - promise: Option<Rc<Promise>>) - -> Rc<Promise> { + fn manipulate( + &self, + op: Operation, + cx: *mut JSContext, + permissionDesc: *mut JSObject, + promise: Option<Rc<Promise>>, + ) -> Rc<Promise> { // (Query, Request) Step 3. let p = match promise { Some(promise) => promise, @@ -113,18 +126,23 @@ impl Permissions { match &op { // (Request) Step 6 - 8. - &Operation::Request => Bluetooth::permission_request(cx, &p, &bluetooth_desc, &result), + &Operation::Request => { + Bluetooth::permission_request(cx, &p, &bluetooth_desc, &result) + }, // (Query) Step 6 - 7. - &Operation::Query => Bluetooth::permission_query(cx, &p, &bluetooth_desc, &result), + &Operation::Query => { + Bluetooth::permission_query(cx, &p, &bluetooth_desc, &result) + }, &Operation::Revoke => { // (Revoke) Step 3. let globalscope = self.global(); - globalscope.as_window() - .permission_state_invocation_results() - .borrow_mut() - .remove(&root_desc.name.to_string()); + globalscope + .as_window() + .permission_state_invocation_results() + .borrow_mut() + .remove(&root_desc.name.to_string()); // (Revoke) Step 4. Bluetooth::permission_revoke(&bluetooth_desc, &result) @@ -153,10 +171,11 @@ impl Permissions { &Operation::Revoke => { // (Revoke) Step 3. let globalscope = self.global(); - globalscope.as_window() - .permission_state_invocation_results() - .borrow_mut() - .remove(&root_desc.name.to_string()); + globalscope + .as_window() + .permission_state_invocation_results() + .borrow_mut() + .remove(&root_desc.name.to_string()); // (Revoke) Step 4. Permissions::permission_revoke(&root_desc, &status); @@ -202,11 +221,14 @@ impl PermissionAlgorithm for Permissions { type Status = PermissionStatus; #[allow(unsafe_code)] - fn create_descriptor(cx: *mut JSContext, - permission_descriptor_obj: *mut JSObject) - -> Result<PermissionDescriptor, Error> { + fn create_descriptor( + cx: *mut JSContext, + permission_descriptor_obj: *mut JSObject, + ) -> Result<PermissionDescriptor, Error> { rooted!(in(cx) let mut property = UndefinedValue()); - property.handle_mut().set(ObjectValue(permission_descriptor_obj)); + property + .handle_mut() + .set(ObjectValue(permission_descriptor_obj)); unsafe { match PermissionDescriptor::new(cx, property.handle()) { Ok(ConversionResult::Success(descriptor)) => Ok(descriptor), @@ -217,19 +239,23 @@ impl PermissionAlgorithm for Permissions { } // https://w3c.github.io/permissions/#boolean-permission-query-algorithm - fn permission_query(_cx: *mut JSContext, - _promise: &Rc<Promise>, - _descriptor: &PermissionDescriptor, - status: &PermissionStatus) { + fn permission_query( + _cx: *mut JSContext, + _promise: &Rc<Promise>, + _descriptor: &PermissionDescriptor, + status: &PermissionStatus, + ) { // Step 1. status.set_state(get_descriptor_permission_state(status.get_query(), None)); } // https://w3c.github.io/permissions/#boolean-permission-request-algorithm - fn permission_request(cx: *mut JSContext, - promise: &Rc<Promise>, - descriptor: &PermissionDescriptor, - status: &PermissionStatus) { + fn permission_request( + cx: *mut JSContext, + promise: &Rc<Promise>, + descriptor: &PermissionDescriptor, + status: &PermissionStatus, + ) { // Step 1. Permissions::permission_query(cx, promise, descriptor, status); @@ -238,14 +264,18 @@ impl PermissionAlgorithm for Permissions { PermissionState::Prompt => { let perm_name = status.get_query(); // https://w3c.github.io/permissions/#request-permission-to-use (Step 3 - 4) - let state = - prompt_user(&format!("{} {} ?", REQUEST_DIALOG_MESSAGE, perm_name.clone())); + let state = prompt_user(&format!( + "{} {} ?", + REQUEST_DIALOG_MESSAGE, + perm_name.clone() + )); let globalscope = GlobalScope::current().expect("No current global object"); - globalscope.as_window() - .permission_state_invocation_results() - .borrow_mut() - .insert(perm_name.to_string(), state); + globalscope + .as_window() + .permission_state_invocation_results() + .borrow_mut() + .insert(perm_name.to_string(), state); }, // Step 2. @@ -260,9 +290,10 @@ impl PermissionAlgorithm for Permissions { } // https://w3c.github.io/permissions/#permission-state -pub fn get_descriptor_permission_state(permission_name: PermissionName, - env_settings_obj: Option<&GlobalScope>) - -> PermissionState { +pub fn get_descriptor_permission_state( + permission_name: PermissionName, + env_settings_obj: Option<&GlobalScope>, +) -> PermissionState { // Step 1. let settings = match env_settings_obj { Some(env_settings_obj) => DomRoot::from_ref(env_settings_obj), @@ -276,33 +307,42 @@ pub fn get_descriptor_permission_state(permission_name: PermissionName, // and let the user decide to grant the permission or not. let state = match allowed_in_nonsecure_contexts(&permission_name) { true => PermissionState::Prompt, - false => { - match PREFS.get("dom.permissions.testing.allowed_in_nonsecure_contexts").as_boolean().unwrap_or(false) { - true => PermissionState::Granted, - false => { - settings.as_window() - .permission_state_invocation_results() - .borrow_mut() - .remove(&permission_name.to_string()); - prompt_user(&format!("The {} {}", permission_name, NONSECURE_DIALOG_MESSAGE)) - }, - } + false => match PREFS + .get("dom.permissions.testing.allowed_in_nonsecure_contexts") + .as_boolean() + .unwrap_or(false) + { + true => PermissionState::Granted, + false => { + settings + .as_window() + .permission_state_invocation_results() + .borrow_mut() + .remove(&permission_name.to_string()); + prompt_user(&format!( + "The {} {}", + permission_name, NONSECURE_DIALOG_MESSAGE + )) + }, }, }; // Step 3. - if let Some(prev_result) = settings.as_window() - .permission_state_invocation_results() - .borrow() - .get(&permission_name.to_string()) { + if let Some(prev_result) = settings + .as_window() + .permission_state_invocation_results() + .borrow() + .get(&permission_name.to_string()) + { return prev_result.clone(); } // Store the invocation result - settings.as_window() - .permission_state_invocation_results() - .borrow_mut() - .insert(permission_name.to_string(), state); + settings + .as_window() + .permission_state_invocation_results() + .borrow_mut() + .insert(permission_name.to_string(), state); // Step 4. state @@ -313,10 +353,12 @@ fn prompt_user(message: &str) -> PermissionState { if opts::get().headless { return PermissionState::Denied; } - match tinyfiledialogs::message_box_yes_no(DIALOG_TITLE, - message, - MessageBoxIcon::Question, - YesNo::No) { + match tinyfiledialogs::message_box_yes_no( + DIALOG_TITLE, + message, + MessageBoxIcon::Question, + YesNo::No, + ) { YesNo::Yes => PermissionState::Granted, YesNo::No => PermissionState::Denied, } diff --git a/components/script/dom/permissionstatus.rs b/components/script/dom/permissionstatus.rs index eea9357d042..6121f8c9496 100644 --- a/components/script/dom/permissionstatus.rs +++ b/components/script/dom/permissionstatus.rs @@ -31,9 +31,11 @@ impl PermissionStatus { } pub fn new(global: &GlobalScope, query: &PermissionDescriptor) -> DomRoot<PermissionStatus> { - reflect_dom_object(Box::new(PermissionStatus::new_inherited(query.name)), - global, - PermissionStatusBinding::Wrap) + reflect_dom_object( + Box::new(PermissionStatus::new_inherited(query.name)), + global, + PermissionStatusBinding::Wrap, + ) } pub fn set_state(&self, state: PermissionState) { diff --git a/components/script/dom/pluginarray.rs b/components/script/dom/pluginarray.rs index e2d0c12da27..38a53baef50 100644 --- a/components/script/dom/pluginarray.rs +++ b/components/script/dom/pluginarray.rs @@ -19,21 +19,22 @@ pub struct PluginArray { impl PluginArray { pub fn new_inherited() -> PluginArray { PluginArray { - reflector_: Reflector::new() + reflector_: Reflector::new(), } } pub fn new(global: &GlobalScope) -> DomRoot<PluginArray> { - reflect_dom_object(Box::new(PluginArray::new_inherited()), - global, - PluginArrayBinding::Wrap) + reflect_dom_object( + Box::new(PluginArray::new_inherited()), + global, + PluginArrayBinding::Wrap, + ) } } impl PluginArrayMethods for PluginArray { // https://html.spec.whatwg.org/multipage/#dom-pluginarray-refresh - fn Refresh(&self, _reload: bool) { - } + fn Refresh(&self, _reload: bool) {} // https://html.spec.whatwg.org/multipage/#dom-pluginarray-length fn Length(&self) -> u32 { diff --git a/components/script/dom/popstateevent.rs b/components/script/dom/popstateevent.rs index f4341777dc6..44b9e0f6e9f 100644 --- a/components/script/dom/popstateevent.rs +++ b/components/script/dom/popstateevent.rs @@ -37,17 +37,20 @@ impl PopStateEvent { } pub fn new_uninitialized(window: &Window) -> DomRoot<PopStateEvent> { - reflect_dom_object(Box::new(PopStateEvent::new_inherited()), - window, - PopStateEventBinding::Wrap) + reflect_dom_object( + Box::new(PopStateEvent::new_inherited()), + window, + PopStateEventBinding::Wrap, + ) } - pub fn new(window: &Window, - type_: Atom, - bubbles: bool, - cancelable: bool, - state: HandleValue) - -> DomRoot<PopStateEvent> { + pub fn new( + window: &Window, + type_: Atom, + bubbles: bool, + cancelable: bool, + state: HandleValue, + ) -> DomRoot<PopStateEvent> { let ev = PopStateEvent::new_uninitialized(window); ev.state.set(state.get()); { @@ -57,20 +60,21 @@ impl PopStateEvent { ev } - pub fn Constructor(window: &Window, - type_: DOMString, - init: RootedTraceableBox<PopStateEventBinding::PopStateEventInit>) - -> Fallible<DomRoot<PopStateEvent>> { - Ok(PopStateEvent::new(window, - Atom::from(type_), - init.parent.bubbles, - init.parent.cancelable, - init.state.handle())) + pub fn Constructor( + window: &Window, + type_: DOMString, + init: RootedTraceableBox<PopStateEventBinding::PopStateEventInit>, + ) -> Fallible<DomRoot<PopStateEvent>> { + Ok(PopStateEvent::new( + window, + Atom::from(type_), + init.parent.bubbles, + init.parent.cancelable, + init.state.handle(), + )) } - pub fn dispatch_jsval(target: &EventTarget, - window: &Window, - state: HandleValue) { + pub fn dispatch_jsval(target: &EventTarget, window: &Window, state: HandleValue) { let event = PopStateEvent::new(window, atom!("popstate"), false, false, state); event.upcast::<Event>().fire(target); } diff --git a/components/script/dom/processinginstruction.rs b/components/script/dom/processinginstruction.rs index d4eee64d2aa..605a6210485 100644 --- a/components/script/dom/processinginstruction.rs +++ b/components/script/dom/processinginstruction.rs @@ -19,20 +19,30 @@ pub struct ProcessingInstruction { } impl ProcessingInstruction { - fn new_inherited(target: DOMString, data: DOMString, document: &Document) -> ProcessingInstruction { + fn new_inherited( + target: DOMString, + data: DOMString, + document: &Document, + ) -> ProcessingInstruction { ProcessingInstruction { characterdata: CharacterData::new_inherited(data, document), - target: target + target: target, } } - pub fn new(target: DOMString, data: DOMString, document: &Document) -> DomRoot<ProcessingInstruction> { - Node::reflect_node(Box::new(ProcessingInstruction::new_inherited(target, data, document)), - document, ProcessingInstructionBinding::Wrap) + pub fn new( + target: DOMString, + data: DOMString, + document: &Document, + ) -> DomRoot<ProcessingInstruction> { + Node::reflect_node( + Box::new(ProcessingInstruction::new_inherited(target, data, document)), + document, + ProcessingInstructionBinding::Wrap, + ) } } - impl ProcessingInstruction { pub fn target(&self) -> &DOMString { &self.target diff --git a/components/script/dom/progressevent.rs b/components/script/dom/progressevent.rs index 84f8004abc7..a2516ea4442 100644 --- a/components/script/dom/progressevent.rs +++ b/components/script/dom/progressevent.rs @@ -20,7 +20,7 @@ pub struct ProgressEvent { event: Event, length_computable: bool, loaded: u64, - total: u64 + total: u64, } impl ProgressEvent { @@ -29,34 +29,56 @@ impl ProgressEvent { event: Event::new_inherited(), length_computable: length_computable, loaded: loaded, - total: total + total: total, } } pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<ProgressEvent> { - reflect_dom_object(Box::new(ProgressEvent::new_inherited(false, 0, 0)), - global, - ProgressEventBinding::Wrap) + reflect_dom_object( + Box::new(ProgressEvent::new_inherited(false, 0, 0)), + global, + ProgressEventBinding::Wrap, + ) } - pub fn new(global: &GlobalScope, type_: Atom, - can_bubble: EventBubbles, cancelable: EventCancelable, - length_computable: bool, loaded: u64, total: u64) -> DomRoot<ProgressEvent> { - let ev = reflect_dom_object(Box::new(ProgressEvent::new_inherited(length_computable, loaded, total)), - global, - ProgressEventBinding::Wrap); + pub fn new( + global: &GlobalScope, + type_: Atom, + can_bubble: EventBubbles, + cancelable: EventCancelable, + length_computable: bool, + loaded: u64, + total: u64, + ) -> DomRoot<ProgressEvent> { + let ev = reflect_dom_object( + Box::new(ProgressEvent::new_inherited( + length_computable, + loaded, + total, + )), + global, + ProgressEventBinding::Wrap, + ); { let event = ev.upcast::<Event>(); event.init_event(type_, bool::from(can_bubble), bool::from(cancelable)); } ev } - pub fn Constructor(global: &GlobalScope, - type_: DOMString, - init: &ProgressEventBinding::ProgressEventInit) - -> Fallible<DomRoot<ProgressEvent>> { + pub fn Constructor( + global: &GlobalScope, + type_: DOMString, + init: &ProgressEventBinding::ProgressEventInit, + ) -> Fallible<DomRoot<ProgressEvent>> { let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::from(init.parent.cancelable); - let ev = ProgressEvent::new(global, Atom::from(type_), bubbles, cancelable, - init.lengthComputable, init.loaded, init.total); + let ev = ProgressEvent::new( + global, + Atom::from(type_), + bubbles, + cancelable, + init.lengthComputable, + init.loaded, + init.total, + ); Ok(ev) } } diff --git a/components/script/dom/promise.rs b/components/script/dom/promise.rs index 0ee8e325154..8112794f1c9 100644 --- a/components/script/dom/promise.rs +++ b/components/script/dom/promise.rs @@ -54,9 +54,11 @@ impl PromiseHelper for Rc<Promise> { unsafe fn initialize(&self, cx: *mut JSContext) { let obj = self.reflector().get_jsobject(); self.permanent_js_root.set(ObjectValue(*obj)); - assert!(AddRawValueRoot(cx, - self.permanent_js_root.get_unsafe(), - b"Promise::root\0".as_c_char_ptr())); + assert!(AddRawValueRoot( + cx, + self.permanent_js_root.get_unsafe(), + b"Promise::root\0".as_c_char_ptr() + )); } } @@ -87,9 +89,7 @@ impl Promise { #[allow(unsafe_code, unrooted_must_root)] pub fn duplicate(&self) -> Rc<Promise> { let cx = self.global().get_cx(); - unsafe { - Promise::new_with_js_promise(self.reflector().get_jsobject(), cx) - } + unsafe { Promise::new_with_js_promise(self.reflector().get_jsobject(), cx) } } #[allow(unsafe_code, unrooted_must_root)] @@ -106,9 +106,18 @@ impl Promise { } #[allow(unsafe_code)] - unsafe fn create_js_promise(cx: *mut JSContext, proto: HandleObject, mut obj: MutableHandleObject) { - let do_nothing_func = JS_NewFunction(cx, Some(do_nothing_promise_executor), /* nargs = */ 2, - /* flags = */ 0, ptr::null()); + unsafe fn create_js_promise( + cx: *mut JSContext, + proto: HandleObject, + mut obj: MutableHandleObject, + ) { + let do_nothing_func = JS_NewFunction( + cx, + Some(do_nothing_promise_executor), + /* nargs = */ 2, + /* flags = */ 0, + ptr::null(), + ); assert!(!do_nothing_func.is_null()); rooted!(in(cx) let do_nothing_obj = JS_GetFunctionObject(do_nothing_func)); assert!(!do_nothing_obj.is_null()); @@ -141,7 +150,10 @@ impl Promise { } #[allow(unsafe_code)] - pub fn resolve_native<T>(&self, val: &T) where T: ToJSValConvertible { + pub fn resolve_native<T>(&self, val: &T) + where + T: ToJSValConvertible, + { let cx = self.global().get_cx(); let _ac = JSAutoCompartment::new(cx, self.reflector().get_jsobject().get()); rooted!(in(cx) let mut v = UndefinedValue()); @@ -159,7 +171,10 @@ impl Promise { } #[allow(unsafe_code)] - pub fn reject_native<T>(&self, val: &T) where T: ToJSValConvertible { + pub fn reject_native<T>(&self, val: &T) + where + T: ToJSValConvertible, + { let cx = self.global().get_cx(); let _ac = JSAutoCompartment::new(cx, self.reflector().get_jsobject().get()); rooted!(in(cx) let mut v = UndefinedValue()); @@ -192,7 +207,7 @@ impl Promise { let state = unsafe { GetPromiseState(self.promise_obj()) }; match state { PromiseState::Rejected | PromiseState::Fulfilled => true, - _ => false + _ => false, } } @@ -219,17 +234,23 @@ impl Promise { NativeHandlerTask::Reject)); unsafe { - let ok = AddPromiseReactions(cx, - self.promise_obj(), - resolve_func.handle(), - reject_func.handle()); + let ok = AddPromiseReactions( + cx, + self.promise_obj(), + resolve_func.handle(), + reject_func.handle(), + ); assert!(ok); } } } #[allow(unsafe_code)] -unsafe extern fn do_nothing_promise_executor(_cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool { +unsafe extern "C" fn do_nothing_promise_executor( + _cx: *mut JSContext, + argc: u32, + vp: *mut JSVal, +) -> bool { let args = CallArgs::from_vp(vp, argc); *args.rval() = UndefinedValue(); true @@ -245,7 +266,11 @@ enum NativeHandlerTask { } #[allow(unsafe_code)] -unsafe extern fn native_handler_callback(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool { +unsafe extern "C" fn native_handler_callback( + cx: *mut JSContext, + argc: u32, + vp: *mut JSVal, +) -> bool { let args = CallArgs::from_vp(vp, argc); rooted!(in(cx) let v = *GetFunctionNativeReserved(args.callee(), SLOT_NATIVEHANDLER)); assert!(v.get().is_object()); @@ -255,10 +280,12 @@ unsafe extern fn native_handler_callback(cx: *mut JSContext, argc: u32, vp: *mut rooted!(in(cx) let v = *GetFunctionNativeReserved(args.callee(), SLOT_NATIVEHANDLER_TASK)); match v.to_int32() { - v if v == NativeHandlerTask::Resolve as i32 => - handler.resolved_callback(cx, HandleValue::from_raw(args.get(0))), - v if v == NativeHandlerTask::Reject as i32 => - handler.rejected_callback(cx, HandleValue::from_raw(args.get(0))), + v if v == NativeHandlerTask::Resolve as i32 => { + handler.resolved_callback(cx, HandleValue::from_raw(args.get(0))) + }, + v if v == NativeHandlerTask::Reject as i32 => { + handler.rejected_callback(cx, HandleValue::from_raw(args.get(0))) + }, _ => panic!("unexpected native handler task value"), }; @@ -266,21 +293,19 @@ unsafe extern fn native_handler_callback(cx: *mut JSContext, argc: u32, vp: *mut } #[allow(unsafe_code)] -fn create_native_handler_function(cx: *mut JSContext, - holder: HandleObject, - task: NativeHandlerTask) -> *mut JSObject { +fn create_native_handler_function( + cx: *mut JSContext, + holder: HandleObject, + task: NativeHandlerTask, +) -> *mut JSObject { unsafe { let func = NewFunctionWithReserved(cx, Some(native_handler_callback), 1, 0, ptr::null()); assert!(!func.is_null()); rooted!(in(cx) let obj = JS_GetFunctionObject(func)); assert!(!obj.is_null()); - SetFunctionNativeReserved(obj.get(), - SLOT_NATIVEHANDLER, - &ObjectValue(*holder)); - SetFunctionNativeReserved(obj.get(), - SLOT_NATIVEHANDLER_TASK, - &Int32Value(task as i32)); + SetFunctionNativeReserved(obj.get(), SLOT_NATIVEHANDLER, &ObjectValue(*holder)); + SetFunctionNativeReserved(obj.get(), SLOT_NATIVEHANDLER_TASK, &Int32Value(task as i32)); obj.get() } } diff --git a/components/script/dom/promisenativehandler.rs b/components/script/dom/promisenativehandler.rs index 123fbfead26..fa54d454b1a 100644 --- a/components/script/dom/promisenativehandler.rs +++ b/components/script/dom/promisenativehandler.rs @@ -24,15 +24,20 @@ pub struct PromiseNativeHandler { } impl PromiseNativeHandler { - pub fn new(global: &GlobalScope, - resolve: Option<Box<Callback>>, - reject: Option<Box<Callback>>) - -> DomRoot<PromiseNativeHandler> { - reflect_dom_object(Box::new(PromiseNativeHandler { - reflector: Reflector::new(), - resolve: resolve, - reject: reject, - }), global, PromiseNativeHandlerBinding::Wrap) + pub fn new( + global: &GlobalScope, + resolve: Option<Box<Callback>>, + reject: Option<Box<Callback>>, + ) -> DomRoot<PromiseNativeHandler> { + reflect_dom_object( + Box::new(PromiseNativeHandler { + reflector: Reflector::new(), + resolve: resolve, + reject: reject, + }), + global, + PromiseNativeHandlerBinding::Wrap, + ) } fn callback(callback: &Option<Box<Callback>>, cx: *mut JSContext, v: HandleValue) { diff --git a/components/script/dom/radionodelist.rs b/components/script/dom/radionodelist.rs index 4a4a19cd646..956b0bf3313 100644 --- a/components/script/dom/radionodelist.rs +++ b/components/script/dom/radionodelist.rs @@ -25,20 +25,27 @@ impl RadioNodeList { #[allow(unrooted_must_root)] fn new_inherited(list_type: NodeListType) -> RadioNodeList { RadioNodeList { - node_list: NodeList::new_inherited(list_type) + node_list: NodeList::new_inherited(list_type), } } #[allow(unrooted_must_root)] pub fn new(window: &Window, list_type: NodeListType) -> DomRoot<RadioNodeList> { - reflect_dom_object(Box::new(RadioNodeList::new_inherited(list_type)), - window, - RadioNodeListBinding::Wrap) + reflect_dom_object( + Box::new(RadioNodeList::new_inherited(list_type)), + window, + RadioNodeListBinding::Wrap, + ) } pub fn new_simple_list<T>(window: &Window, iter: T) -> DomRoot<RadioNodeList> - where T: Iterator<Item=DomRoot<Node>> { - RadioNodeList::new(window, NodeListType::Simple(iter.map(|r| Dom::from_ref(&*r)).collect())) + where + T: Iterator<Item = DomRoot<Node>>, + { + RadioNodeList::new( + window, + NodeListType::Simple(iter.map(|r| Dom::from_ref(&*r)).collect()), + ) } // FIXME: This shouldn't need to be implemented here since NodeList (the parent of @@ -81,15 +88,15 @@ impl RadioNodeListMethods for RadioNodeList { input.SetChecked(true); return; } - } + }, InputType::Radio => { // Step 2 if input.Value() == value { input.SetChecked(true); return; } - } - _ => {} + }, + _ => {}, } } } diff --git a/components/script/dom/range.rs b/components/script/dom/range.rs index f43c9e1922c..9123a2c67e3 100644 --- a/components/script/dom/range.rs +++ b/components/script/dom/range.rs @@ -40,8 +40,12 @@ pub struct Range { } impl Range { - fn new_inherited(start_container: &Node, start_offset: u32, - end_container: &Node, end_offset: u32) -> Range { + fn new_inherited( + start_container: &Node, + start_offset: u32, + end_container: &Node, + end_offset: u32, + ) -> Range { Range { reflector_: Reflector::new(), start: BoundaryPoint::new(start_container, start_offset), @@ -54,16 +58,22 @@ impl Range { Range::new(document, root, 0, root, 0) } - pub fn new(document: &Document, - start_container: &Node, start_offset: u32, - end_container: &Node, end_offset: u32) - -> DomRoot<Range> { + pub fn new( + document: &Document, + start_container: &Node, + start_offset: u32, + end_container: &Node, + end_offset: u32, + ) -> DomRoot<Range> { let range = reflect_dom_object( Box::new(Range::new_inherited( - start_container, start_offset, end_container, end_offset + start_container, + start_offset, + end_container, + end_offset, )), document.window(), - RangeBinding::Wrap + RangeBinding::Wrap, ); start_container.ranges().push(WeakRef::new(&range)); if start_container != end_container { @@ -80,58 +90,74 @@ impl Range { // https://dom.spec.whatwg.org/#contained fn contains(&self, node: &Node) -> bool { - match (bp_position(node, 0, &self.StartContainer(), self.StartOffset()), - bp_position(node, node.len(), &self.EndContainer(), self.EndOffset())) { + match ( + bp_position(node, 0, &self.StartContainer(), self.StartOffset()), + bp_position(node, node.len(), &self.EndContainer(), self.EndOffset()), + ) { (Some(Ordering::Greater), Some(Ordering::Less)) => true, - _ => false + _ => false, } } // https://dom.spec.whatwg.org/#partially-contained fn partially_contains(&self, node: &Node) -> bool { - self.StartContainer().inclusive_ancestors().any(|n| &*n == node) != - self.EndContainer().inclusive_ancestors().any(|n| &*n == node) + self.StartContainer() + .inclusive_ancestors() + .any(|n| &*n == node) != + self.EndContainer() + .inclusive_ancestors() + .any(|n| &*n == node) } // https://dom.spec.whatwg.org/#concept-range-clone - fn contained_children(&self) -> Fallible<(Option<DomRoot<Node>>, - Option<DomRoot<Node>>, - Vec<DomRoot<Node>>)> { + fn contained_children( + &self, + ) -> Fallible<( + Option<DomRoot<Node>>, + Option<DomRoot<Node>>, + Vec<DomRoot<Node>>, + )> { let start_node = self.StartContainer(); let end_node = self.EndContainer(); // Steps 5-6. let common_ancestor = self.CommonAncestorContainer(); - let first_contained_child = - if start_node.is_inclusive_ancestor_of(&end_node) { - // Step 7. - None - } else { - // Step 8. - common_ancestor.children() - .find(|node| Range::partially_contains(self, node)) - }; + let first_contained_child = if start_node.is_inclusive_ancestor_of(&end_node) { + // Step 7. + None + } else { + // Step 8. + common_ancestor + .children() + .find(|node| Range::partially_contains(self, node)) + }; - let last_contained_child = - if end_node.is_inclusive_ancestor_of(&start_node) { - // Step 9. - None - } else { - // Step 10. - common_ancestor.rev_children() - .find(|node| Range::partially_contains(self, node)) - }; + let last_contained_child = if end_node.is_inclusive_ancestor_of(&start_node) { + // Step 9. + None + } else { + // Step 10. + common_ancestor + .rev_children() + .find(|node| Range::partially_contains(self, node)) + }; // Step 11. - let contained_children: Vec<DomRoot<Node>> = - common_ancestor.children().filter(|n| self.contains(n)).collect(); + let contained_children: Vec<DomRoot<Node>> = common_ancestor + .children() + .filter(|n| self.contains(n)) + .collect(); // Step 12. if contained_children.iter().any(|n| n.is_doctype()) { return Err(Error::HierarchyRequest); } - Ok((first_contained_child, last_contained_child, contained_children)) + Ok(( + first_contained_child, + last_contained_child, + contained_children, + )) } // https://dom.spec.whatwg.org/#concept-range-bp-set @@ -142,7 +168,8 @@ impl Range { } else if &self.end.node == node { self.StartContainer().ranges().remove(self); } else { - node.ranges().push(self.StartContainer().ranges().remove(self)); + node.ranges() + .push(self.StartContainer().ranges().remove(self)); } } self.start.set(node, offset); @@ -156,7 +183,8 @@ impl Range { } else if &self.start.node == node { self.EndContainer().ranges().remove(self); } else { - node.ranges().push(self.EndContainer().ranges().remove(self)); + node.ranges() + .push(self.EndContainer().ranges().remove(self)); } } self.end.set(node, offset); @@ -179,11 +207,14 @@ impl Range { // Step 3. return Err(Error::IndexSize); } - if let Ordering::Less = bp_position(node, offset, &start_node, self.StartOffset()).unwrap() { + if let Ordering::Less = bp_position(node, offset, &start_node, self.StartOffset()).unwrap() + { // Step 4. return Ok(Ordering::Less); } - if let Ordering::Greater = bp_position(node, offset, &self.EndContainer(), self.EndOffset()).unwrap() { + if let Ordering::Greater = + bp_position(node, offset, &self.EndContainer(), self.EndOffset()).unwrap() + { // Step 5. return Ok(Ordering::Greater); } @@ -332,8 +363,7 @@ impl RangeMethods for Range { } // https://dom.spec.whatwg.org/#dom-range-compareboundarypoints - fn CompareBoundaryPoints(&self, how: u16, other: &Range) - -> Fallible<i16> { + fn CompareBoundaryPoints(&self, how: u16, other: &Range) -> Fallible<i16> { if how > RangeConstants::END_TO_START { // Step 1. return Err(Error::NotSupported); @@ -346,18 +376,10 @@ impl RangeMethods for Range { } // Step 3. let (this_point, other_point) = match how { - RangeConstants::START_TO_START => { - (&self.start, &other.start) - }, - RangeConstants::START_TO_END => { - (&self.end, &other.start) - }, - RangeConstants::END_TO_END => { - (&self.end, &other.end) - }, - RangeConstants::END_TO_START => { - (&self.start, &other.end) - }, + RangeConstants::START_TO_START => (&self.start, &other.start), + RangeConstants::START_TO_END => (&self.end, &other.start), + RangeConstants::END_TO_END => (&self.end, &other.end), + RangeConstants::END_TO_START => (&self.start, &other.end), _ => unreachable!(), }; // step 4. @@ -372,8 +394,13 @@ impl RangeMethods for Range { fn CloneRange(&self) -> DomRoot<Range> { let start_node = self.StartContainer(); let owner_doc = start_node.owner_doc(); - Range::new(&owner_doc, &start_node, self.StartOffset(), - &self.EndContainer(), self.EndOffset()) + Range::new( + &owner_doc, + &start_node, + self.StartOffset(), + &self.EndContainer(), + self.EndOffset(), + ) } // https://dom.spec.whatwg.org/#dom-range-ispointinrange @@ -385,19 +412,17 @@ impl RangeMethods for Range { Err(Error::WrongDocument) => { // Step 2. Ok(false) - } + }, Err(error) => Err(error), } } // https://dom.spec.whatwg.org/#dom-range-comparepoint fn ComparePoint(&self, node: &Node, offset: u32) -> Fallible<i16> { - self.compare_point(node, offset).map(|order| { - match order { - Ordering::Less => -1, - Ordering::Equal => 0, - Ordering::Greater => 1, - } + self.compare_point(node, offset).map(|order| match order { + Ordering::Less => -1, + Ordering::Equal => 0, + Ordering::Greater => 1, }) } @@ -420,10 +445,10 @@ impl RangeMethods for Range { // Step 4. let offset = node.index(); // Step 5. - Ordering::Greater == bp_position(&parent, offset + 1, - &start_node, self.StartOffset()).unwrap() && - Ordering::Less == bp_position(&parent, offset, - &self.EndContainer(), self.EndOffset()).unwrap() + Ordering::Greater == + bp_position(&parent, offset + 1, &start_node, self.StartOffset()).unwrap() && + Ordering::Less == + bp_position(&parent, offset, &self.EndContainer(), self.EndOffset()).unwrap() } // https://dom.spec.whatwg.org/#dom-range-clonecontents @@ -446,7 +471,9 @@ impl RangeMethods for Range { if end_node == start_node { if let Some(cdata) = start_node.downcast::<CharacterData>() { // Steps 4.1-2. - let data = cdata.SubstringData(start_offset, end_offset - start_offset).unwrap(); + let data = cdata + .SubstringData(start_offset, end_offset - start_offset) + .unwrap(); let clone = cdata.clone_with_data(data, &start_node.owner_doc()); // Step 4.3. fragment.upcast::<Node>().AppendChild(&clone)?; @@ -464,7 +491,9 @@ impl RangeMethods for Range { if let Some(cdata) = child.downcast::<CharacterData>() { assert!(child == start_node); // Steps 13.1-2. - let data = cdata.SubstringData(start_offset, start_node.len() - start_offset).unwrap(); + let data = cdata + .SubstringData(start_offset, start_node.len() - start_offset) + .unwrap(); let clone = cdata.clone_with_data(data, &start_node.owner_doc()); // Step 13.3. fragment.upcast::<Node>().AppendChild(&clone)?; @@ -474,11 +503,13 @@ impl RangeMethods for Range { // Step 14.2. fragment.upcast::<Node>().AppendChild(&clone)?; // Step 14.3. - let subrange = Range::new(&clone.owner_doc(), - &start_node, - start_offset, - &child, - child.len()); + let subrange = Range::new( + &clone.owner_doc(), + &start_node, + start_offset, + &child, + child.len(), + ); // Step 14.4. let subfragment = subrange.CloneContents()?; // Step 14.5. @@ -509,11 +540,7 @@ impl RangeMethods for Range { // Step 17.2. fragment.upcast::<Node>().AppendChild(&clone)?; // Step 17.3. - let subrange = Range::new(&clone.owner_doc(), - &child, - 0, - &end_node, - end_offset); + let subrange = Range::new(&clone.owner_doc(), &child, 0, &end_node, end_offset); // Step 17.4. let subfragment = subrange.CloneContents()?; // Step 17.5. @@ -548,13 +575,14 @@ impl RangeMethods for Range { let clone = end_node.CloneNode(true); // Step 4.2. let text = end_data.SubstringData(start_offset, end_offset - start_offset); - clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap()); + clone + .downcast::<CharacterData>() + .unwrap() + .SetData(text.unwrap()); // Step 4.3. fragment.upcast::<Node>().AppendChild(&clone)?; // Step 4.4. - end_data.ReplaceData(start_offset, - end_offset - start_offset, - DOMString::new())?; + end_data.ReplaceData(start_offset, end_offset - start_offset, DOMString::new())?; // Step 4.5. return Ok(fragment); } @@ -569,12 +597,16 @@ impl RangeMethods for Range { (DomRoot::from_ref(&*start_node), start_offset) } else { // Step 14.1-2. - let reference_node = start_node.ancestors() - .take_while(|n| !n.is_inclusive_ancestor_of(&end_node)) - .last() - .unwrap_or(DomRoot::from_ref(&start_node)); + let reference_node = start_node + .ancestors() + .take_while(|n| !n.is_inclusive_ancestor_of(&end_node)) + .last() + .unwrap_or(DomRoot::from_ref(&start_node)); // Step 14.3. - (reference_node.GetParentNode().unwrap(), reference_node.index() + 1) + ( + reference_node.GetParentNode().unwrap(), + reference_node.index() + 1, + ) }; if let Some(child) = first_contained_child { @@ -583,26 +615,32 @@ impl RangeMethods for Range { // Step 15.1. let clone = start_node.CloneNode(true); // Step 15.2. - let text = start_data.SubstringData(start_offset, - start_node.len() - start_offset); - clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap()); + let text = start_data.SubstringData(start_offset, start_node.len() - start_offset); + clone + .downcast::<CharacterData>() + .unwrap() + .SetData(text.unwrap()); // Step 15.3. fragment.upcast::<Node>().AppendChild(&clone)?; // Step 15.4. - start_data.ReplaceData(start_offset, - start_node.len() - start_offset, - DOMString::new())?; + start_data.ReplaceData( + start_offset, + start_node.len() - start_offset, + DOMString::new(), + )?; } else { // Step 16.1. let clone = child.CloneNode(false); // Step 16.2. fragment.upcast::<Node>().AppendChild(&clone)?; // Step 16.3. - let subrange = Range::new(&clone.owner_doc(), - &start_node, - start_offset, - &child, - child.len()); + let subrange = Range::new( + &clone.owner_doc(), + &start_node, + start_offset, + &child, + child.len(), + ); // Step 16.4. let subfragment = subrange.ExtractContents()?; // Step 16.5. @@ -622,7 +660,10 @@ impl RangeMethods for Range { let clone = end_node.CloneNode(true); // Step 18.2. let text = end_data.SubstringData(0, end_offset); - clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap()); + clone + .downcast::<CharacterData>() + .unwrap() + .SetData(text.unwrap()); // Step 18.3. fragment.upcast::<Node>().AppendChild(&clone)?; // Step 18.4. @@ -633,11 +674,7 @@ impl RangeMethods for Range { // Step 19.2. fragment.upcast::<Node>().AppendChild(&clone)?; // Step 19.3. - let subrange = Range::new(&clone.owner_doc(), - &child, - 0, - &end_node, - end_offset); + let subrange = Range::new(&clone.owner_doc(), &child, 0, &end_node, end_offset); // Step 19.4. let subfragment = subrange.ExtractContents()?; // Step 19.5. @@ -672,7 +709,7 @@ impl RangeMethods for Range { // Handled under step 2. NodeTypeId::CharacterData(CharacterDataTypeId::Text) => (), NodeTypeId::CharacterData(_) => return Err(Error::HierarchyRequest), - _ => () + _ => (), } // Step 2. @@ -682,7 +719,7 @@ impl RangeMethods for Range { let parent = match start_node.GetParentNode() { Some(parent) => parent, // Step 1. - None => return Err(Error::HierarchyRequest) + None => return Err(Error::HierarchyRequest), }; // Step 5. (Some(DomRoot::from_ref(&*start_node)), parent) @@ -693,22 +730,19 @@ impl RangeMethods for Range { }; // Step 6. - Node::ensure_pre_insertion_validity(node, - &parent, - reference_node.r())?; + Node::ensure_pre_insertion_validity(node, &parent, reference_node.r())?; // Step 7. let split_text; - let reference_node = - match start_node.downcast::<Text>() { - Some(text) => { - split_text = text.SplitText(start_offset)?; - let new_reference = DomRoot::upcast::<Node>(split_text); - assert!(new_reference.GetParentNode().r() == Some(&parent)); - Some(new_reference) - }, - _ => reference_node - }; + let reference_node = match start_node.downcast::<Text>() { + Some(text) => { + split_text = text.SplitText(start_offset)?; + let new_reference = DomRoot::upcast::<Node>(split_text); + assert!(new_reference.GetParentNode().r() == Some(&parent)); + Some(new_reference) + }, + _ => reference_node, + }; // Step 8. let reference_node = if Some(node) == reference_node.r() { @@ -721,8 +755,7 @@ impl RangeMethods for Range { node.remove_self(); // Step 10. - let new_offset = - reference_node.r().map_or(parent.len(), |node| node.index()); + let new_offset = reference_node.r().map_or(parent.len(), |node| node.index()); // Step 11 let new_offset = new_offset + if node.type_id() == NodeTypeId::DocumentFragment { @@ -758,9 +791,7 @@ impl RangeMethods for Range { // Step 3. if start_node == end_node { if let Some(text) = start_node.downcast::<CharacterData>() { - return text.ReplaceData(start_offset, - end_offset - start_offset, - DOMString::new()); + return text.ReplaceData(start_offset, end_offset - start_offset, DOMString::new()); } } @@ -789,7 +820,7 @@ impl RangeMethods for Range { let mut reference_node = DomRoot::from_ref(start_node); while let Some(parent) = reference_node.GetParentNode() { if parent.is_inclusive_ancestor_of(end_node) { - return (parent, reference_node.index() + 1) + return (parent, reference_node.index() + 1); } reference_node = parent; } @@ -801,9 +832,11 @@ impl RangeMethods for Range { // Step 7. if let Some(text) = start_node.downcast::<CharacterData>() { - text.ReplaceData(start_offset, - start_node.len() - start_offset, - DOMString::new()).unwrap(); + text.ReplaceData( + start_offset, + start_node.len() - start_offset, + DOMString::new(), + ).unwrap(); } // Step 8. @@ -828,17 +861,21 @@ impl RangeMethods for Range { let start = self.StartContainer(); let end = self.EndContainer(); - if start.inclusive_ancestors().any(|n| !n.is_inclusive_ancestor_of(&end) && !n.is::<Text>()) || - end.inclusive_ancestors().any(|n| !n.is_inclusive_ancestor_of(&start) && !n.is::<Text>()) { - return Err(Error::InvalidState); + if start + .inclusive_ancestors() + .any(|n| !n.is_inclusive_ancestor_of(&end) && !n.is::<Text>()) || + end.inclusive_ancestors() + .any(|n| !n.is_inclusive_ancestor_of(&start) && !n.is::<Text>()) + { + return Err(Error::InvalidState); } // Step 2. match new_parent.type_id() { - NodeTypeId::Document(_) | - NodeTypeId::DocumentType | - NodeTypeId::DocumentFragment => return Err(Error::InvalidNodeType), - _ => () + NodeTypeId::Document(_) | NodeTypeId::DocumentType | NodeTypeId::DocumentFragment => { + return Err(Error::InvalidNodeType) + }, + _ => (), } // Step 3. @@ -870,19 +907,24 @@ impl RangeMethods for Range { // Step 2. if start_node == end_node { - return char_data.SubstringData(self.StartOffset(), - self.EndOffset() - self.StartOffset()).unwrap(); + return char_data + .SubstringData(self.StartOffset(), self.EndOffset() - self.StartOffset()) + .unwrap(); } // Step 3. - s.push_str(&*char_data.SubstringData(self.StartOffset(), - char_data.Length() - self.StartOffset()).unwrap()); + s.push_str( + &*char_data + .SubstringData(self.StartOffset(), char_data.Length() - self.StartOffset()) + .unwrap(), + ); } // Step 4. let ancestor = self.CommonAncestorContainer(); - let mut iter = start_node.following_nodes(&ancestor) - .filter_map(DomRoot::downcast::<Text>); + let mut iter = start_node + .following_nodes(&ancestor) + .filter_map(DomRoot::downcast::<Text>); while let Some(child) = iter.next() { if self.contains(child.upcast()) { @@ -963,23 +1005,24 @@ impl BoundaryPoint { #[allow(unrooted_must_root)] impl PartialOrd for BoundaryPoint { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { - bp_position(&self.node.get(), self.offset.get(), - &other.node.get(), other.offset.get()) + bp_position( + &self.node.get(), + self.offset.get(), + &other.node.get(), + other.offset.get(), + ) } } #[allow(unrooted_must_root)] impl PartialEq for BoundaryPoint { fn eq(&self, other: &Self) -> bool { - self.node.get() == other.node.get() && - self.offset.get() == other.offset.get() + self.node.get() == other.node.get() && self.offset.get() == other.offset.get() } } // https://dom.spec.whatwg.org/#concept-range-bp-position -fn bp_position(a_node: &Node, a_offset: u32, - b_node: &Node, b_offset: u32) - -> Option<Ordering> { +fn bp_position(a_node: &Node, a_offset: u32, b_node: &Node, b_offset: u32) -> Option<Ordering> { if a_node as *const Node == b_node as *const Node { // Step 1. return Some(a_offset.cmp(&b_offset)); @@ -998,9 +1041,9 @@ fn bp_position(a_node: &Node, a_offset: u32, } else if position & NodeConstants::DOCUMENT_POSITION_CONTAINS != 0 { // Step 3-1, 3-2. let mut b_ancestors = b_node.inclusive_ancestors(); - let child = b_ancestors.find(|child| { - &*child.GetParentNode().unwrap() == a_node - }).unwrap(); + let child = b_ancestors + .find(|child| &*child.GetParentNode().unwrap() == a_node) + .unwrap(); // Step 3-3. if child.index() < a_offset { Some(Ordering::Greater) @@ -1022,7 +1065,9 @@ pub struct WeakRangeVec { impl WeakRangeVec { /// Create a new vector of weak references. pub fn new() -> Self { - WeakRangeVec { cell: UnsafeCell::new(WeakRefVec::new()) } + WeakRangeVec { + cell: UnsafeCell::new(WeakRefVec::new()), + } } /// Whether that vector of ranges is empty. @@ -1100,9 +1145,7 @@ impl WeakRangeVec { /// Used for steps 7.3-4. when normalizing a node. /// <https://dom.spec.whatwg.org/#dom-node-normalize> - pub fn move_to_text_child_at(&self, - node: &Node, offset: u32, - child: &Node, new_offset: u32) { + pub fn move_to_text_child_at(&self, node: &Node, offset: u32, child: &Node, new_offset: u32) { unsafe { let child_ranges = &mut *child.ranges().cell.get(); @@ -1116,8 +1159,8 @@ impl WeakRangeVec { let move_end = node_is_end && range.EndOffset() == offset; let remove_from_node = move_start && move_end || - move_start && !node_is_end || - move_end && !node_is_start; + move_start && !node_is_end || + move_end && !node_is_start; let already_in_child = &range.start.node == child || &range.end.node == child; let push_to_child = !already_in_child && (move_start || move_end); @@ -1143,9 +1186,13 @@ impl WeakRangeVec { /// Used for steps 8-11. when replacing character data. /// <https://dom.spec.whatwg.org/#concept-cd-replace> - pub fn replace_code_units(&self, - node: &Node, offset: u32, - removed_code_units: u32, added_code_units: u32) { + pub fn replace_code_units( + &self, + node: &Node, + offset: u32, + removed_code_units: u32, + added_code_units: u32, + ) { self.map_offset_above(node, offset, |range_offset| { if range_offset <= offset + removed_code_units { offset @@ -1157,9 +1204,7 @@ impl WeakRangeVec { /// Used for steps 7.2-3. when splitting a text node. /// <https://dom.spec.whatwg.org/#concept-text-split> - pub fn move_to_following_text_sibling_above(&self, - node: &Node, offset: u32, - sibling: &Node) { + pub fn move_to_following_text_sibling_above(&self, node: &Node, offset: u32, sibling: &Node) { unsafe { let sibling_ranges = &mut *sibling.ranges().cell.get(); @@ -1175,11 +1220,10 @@ impl WeakRangeVec { let move_end = node_is_end && end_offset > offset; let remove_from_node = move_start && move_end || - move_start && !node_is_end || - move_end && !node_is_start; + move_start && !node_is_end || + move_end && !node_is_start; - let already_in_sibling = - &range.start.node == sibling || &range.end.node == sibling; + let already_in_sibling = &range.start.node == sibling || &range.end.node == sibling; let push_to_sibling = !already_in_sibling && (move_start || move_end); if remove_from_node { @@ -1242,9 +1286,7 @@ impl WeakRangeVec { fn remove(&self, range: &Range) -> WeakRef<Range> { unsafe { let ranges = &mut *self.cell.get(); - let position = ranges.iter().position(|ref_| { - ref_ == range - }).unwrap(); + let position = ranges.iter().position(|ref_| ref_ == range).unwrap(); ranges.swap_remove(position) } } diff --git a/components/script/dom/request.rs b/components/script/dom/request.rs index 60935093647..0415aba9203 100644 --- a/components/script/dom/request.rs +++ b/components/script/dom/request.rs @@ -51,12 +51,10 @@ pub struct Request { } impl Request { - fn new_inherited(global: &GlobalScope, - url: ServoUrl) -> Request { + fn new_inherited(global: &GlobalScope, url: ServoUrl) -> Request { Request { reflector_: Reflector::new(), - request: DomRefCell::new( - net_request_from_global(global, url)), + request: DomRefCell::new(net_request_from_global(global, url)), body_used: Cell::new(false), headers: Default::default(), mime_type: DomRefCell::new("".to_string().into_bytes()), @@ -64,17 +62,20 @@ impl Request { } } - pub fn new(global: &GlobalScope, - url: ServoUrl) -> DomRoot<Request> { - reflect_dom_object(Box::new(Request::new_inherited(global, url)), - global, RequestBinding::Wrap) + pub fn new(global: &GlobalScope, url: ServoUrl) -> DomRoot<Request> { + reflect_dom_object( + Box::new(Request::new_inherited(global, url)), + global, + RequestBinding::Wrap, + ) } // https://fetch.spec.whatwg.org/#dom-request - pub fn Constructor(global: &GlobalScope, - input: RequestInfo, - init: RootedTraceableBox<RequestInit>) - -> Fallible<DomRoot<Request>> { + pub fn Constructor( + global: &GlobalScope, + input: RequestInfo, + init: RootedTraceableBox<RequestInit>, + ) -> Fallible<DomRoot<Request>> { // Step 1 let temporary_request: NetTraitsRequest; @@ -94,12 +95,12 @@ impl Request { let parsed_url = base_url.join(&usv_string); // Step 5.2 if parsed_url.is_err() { - return Err(Error::Type("Url could not be parsed".to_string())) + return Err(Error::Type("Url could not be parsed".to_string())); } // Step 5.3 let url = parsed_url.unwrap(); if includes_credentials(&url) { - return Err(Error::Type("Url includes credentials".to_string())) + return Err(Error::Type("Url includes credentials".to_string())); } // Step 5.4 temporary_request = net_request_from_global(global, url); @@ -107,16 +108,16 @@ impl Request { fallback_mode = Some(NetTraitsRequestMode::CorsMode); // Step 5.6 fallback_credentials = Some(NetTraitsRequestCredentials::CredentialsSameOrigin); - } + }, // Step 6 RequestInfo::Request(ref input_request) => { // Step 6.1 if request_is_disturbed(input_request) || request_is_locked(input_request) { - return Err(Error::Type("Input is disturbed or locked".to_string())) + return Err(Error::Type("Input is disturbed or locked".to_string())); } // Step 6.2 temporary_request = input_request.request.borrow().clone(); - } + }, } // Step 7 @@ -131,7 +132,7 @@ impl Request { // Step 10 if !init.window.handle().is_null_or_undefined() { - return Err(Error::Type("Window is present and is not null".to_string())) + return Err(Error::Type("Window is present and is not null".to_string())); } // Step 11 @@ -167,16 +168,17 @@ impl Request { init.redirect.is_some() || init.referrer.is_some() || init.referrerPolicy.is_some() || - !init.window.handle().is_undefined() { - // Step 13.1 - if request.mode == NetTraitsRequestMode::Navigate { - request.mode = NetTraitsRequestMode::SameOrigin; - } - // Step 13.2 - request.referrer = NetTraitsRequestReferrer::Client; - // Step 13.3 - request.referrer_policy = None; + !init.window.handle().is_undefined() + { + // Step 13.1 + if request.mode == NetTraitsRequestMode::Navigate { + request.mode = NetTraitsRequestMode::SameOrigin; } + // Step 13.2 + request.referrer = NetTraitsRequestReferrer::Client; + // Step 13.3 + request.referrer_policy = None; + } // Step 14 if let Some(init_referrer) = init.referrer.as_ref() { @@ -190,20 +192,20 @@ impl Request { let parsed_referrer = base_url.join(referrer); // Step 14.4 if parsed_referrer.is_err() { - return Err(Error::Type( - "Failed to parse referrer url".to_string())); + return Err(Error::Type("Failed to parse referrer url".to_string())); } // Step 14.5 if let Ok(parsed_referrer) = parsed_referrer { if (parsed_referrer.cannot_be_a_base() && parsed_referrer.scheme() == "about" && parsed_referrer.path() == "client") || - parsed_referrer.origin() != origin { - request.referrer = NetTraitsRequestReferrer::Client; - } else { - // Step 14.6 - request.referrer = NetTraitsRequestReferrer::ReferrerUrl(parsed_referrer); - } + parsed_referrer.origin() != origin + { + request.referrer = NetTraitsRequestReferrer::Client; + } else { + // Step 14.6 + request.referrer = NetTraitsRequestReferrer::ReferrerUrl(parsed_referrer); + } } } } @@ -215,7 +217,11 @@ impl Request { } // Step 16 - let mode = init.mode.as_ref().map(|m| m.clone().into()).or(fallback_mode); + let mode = init + .mode + .as_ref() + .map(|m| m.clone().into()) + .or(fallback_mode); // Step 17 if let Some(NetTraitsRequestMode::Navigate) = mode { @@ -228,7 +234,11 @@ impl Request { } // Step 19 - let credentials = init.credentials.as_ref().map(|m| m.clone().into()).or(fallback_credentials); + let credentials = init + .credentials + .as_ref() + .map(|m| m.clone().into()) + .or(fallback_credentials); // Step 20 if let Some(c) = credentials { @@ -245,7 +255,8 @@ impl Request { if request.cache_mode == NetTraitsRequestCache::OnlyIfCached { if request.mode != NetTraitsRequestMode::SameOrigin { return Err(Error::Type( - "Cache is 'only-if-cached' and mode is not 'same-origin'".to_string())); + "Cache is 'only-if-cached' and mode is not 'same-origin'".to_string(), + )); } } @@ -291,14 +302,15 @@ impl Request { match possible_header { &HeadersInit::Headers(ref init_headers) => { headers_copy = DomRoot::from_ref(&*init_headers); - } + }, &HeadersInit::ByteStringSequenceSequence(ref init_sequence) => { - headers_copy.fill(Some( - HeadersInit::ByteStringSequenceSequence(init_sequence.clone())))?; + headers_copy.fill(Some(HeadersInit::ByteStringSequenceSequence( + init_sequence.clone(), + )))?; }, &HeadersInit::StringByteStringRecord(ref init_map) => { - headers_copy.fill(Some( - HeadersInit::StringByteStringRecord(init_map.clone())))?; + headers_copy + .fill(Some(HeadersInit::StringByteStringRecord(init_map.clone())))?; }, } } @@ -318,7 +330,9 @@ impl Request { // Step 30.1 if !is_cors_safelisted_method(&borrowed_request.method) { return Err(Error::Type( - "The mode is 'no-cors' but the method is not a cors-safelisted method".to_string())); + "The mode is 'no-cors' but the method is not a cors-safelisted method" + .to_string(), + )); } // Step 30.2 r.Headers().set_guard(Guard::RequestNoCors); @@ -332,10 +346,13 @@ impl Request { // but an input with headers is given, set request's // headers as the input's Headers. if let RequestInfo::Request(ref input_request) = input { - r.Headers().fill(Some(HeadersInit::Headers(input_request.Headers())))?; + r.Headers() + .fill(Some(HeadersInit::Headers(input_request.Headers())))?; } }, - Some(HeadersInit::Headers(_)) => r.Headers().fill(Some(HeadersInit::Headers(headers_copy)))?, + Some(HeadersInit::Headers(_)) => { + r.Headers().fill(Some(HeadersInit::Headers(headers_copy)))? + }, _ => {}, } @@ -356,10 +373,16 @@ impl Request { let req = r.request.borrow(); let req_method = &req.method; match *req_method { - HttpMethod::Get => return Err(Error::Type( - "Init's body is non-null, and request method is GET".to_string())), - HttpMethod::Head => return Err(Error::Type( - "Init's body is non-null, and request method is HEAD".to_string())), + HttpMethod::Get => { + return Err(Error::Type( + "Init's body is non-null, and request method is GET".to_string(), + )) + }, + HttpMethod::Head => { + return Err(Error::Type( + "Init's body is non-null, and request method is HEAD".to_string(), + )) + }, _ => {}, } } @@ -374,9 +397,15 @@ impl Request { // Step 34.3 if let Some(contents) = content_type { - if !r.Headers().Has(ByteString::new(b"Content-Type".to_vec())).unwrap() { - r.Headers().Append(ByteString::new(b"Content-Type".to_vec()), - ByteString::new(contents.as_bytes().to_vec()))?; + if !r + .Headers() + .Has(ByteString::new(b"Content-Type".to_vec())) + .unwrap() + { + r.Headers().Append( + ByteString::new(b"Content-Type".to_vec()), + ByteString::new(contents.as_bytes().to_vec()), + )?; } } } @@ -404,10 +433,8 @@ impl Request { } impl Request { - fn from_net_request(global: &GlobalScope, - net_request: NetTraitsRequest) -> DomRoot<Request> { - let r = Request::new(global, - net_request.current_url()); + fn from_net_request(global: &GlobalScope, net_request: NetTraitsRequest) -> DomRoot<Request> { + let r = Request::new(global, net_request.current_url()); *r.request.borrow_mut() = net_request; r } @@ -427,7 +454,9 @@ impl Request { *r_clone.request.borrow_mut() = req.clone(); r_clone.body_used.set(body_used); *r_clone.mime_type.borrow_mut() = mime_type; - r_clone.Headers().fill(Some(HeadersInit::Headers(r.Headers())))?; + r_clone + .Headers() + .fill(Some(HeadersInit::Headers(r.Headers())))?; r_clone.Headers().set_guard(headers_guard); Ok(r_clone) } @@ -437,13 +466,10 @@ impl Request { } } -fn net_request_from_global(global: &GlobalScope, - url: ServoUrl) -> NetTraitsRequest { +fn net_request_from_global(global: &GlobalScope, url: ServoUrl) -> NetTraitsRequest { let origin = Origin::Origin(global.get_url().origin()); let pipeline_id = global.pipeline_id(); - NetTraitsRequest::new(url, - Some(origin), - Some(pipeline_id)) + NetTraitsRequest::new(url, Some(origin), Some(pipeline_id)) } // https://fetch.spec.whatwg.org/#concept-method-normalize @@ -477,9 +503,7 @@ fn is_forbidden_method(m: &ByteString) -> bool { // 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 + m == &HttpMethod::Get || m == &HttpMethod::Head || m == &HttpMethod::Post } // https://url.spec.whatwg.org/#include-credentials @@ -531,13 +555,17 @@ impl RequestMethods for Request { NetTraitsRequestReferrer::ReferrerUrl(ref u) => { let u_c = u.clone(); u_c.into_string() - } + }, }) } // https://fetch.spec.whatwg.org/#dom-request-referrerpolicy fn ReferrerPolicy(&self) -> ReferrerPolicy { - self.request.borrow().referrer_policy.map(|m| m.into()).unwrap_or(ReferrerPolicy::_empty) + self.request + .borrow() + .referrer_policy + .map(|m| m.into()) + .unwrap_or(ReferrerPolicy::_empty) } // https://fetch.spec.whatwg.org/#dom-request-mode @@ -727,8 +755,9 @@ impl Into<RequestDestination> for NetTraitsRequestDestination { NetTraitsRequestDestination::Object => RequestDestination::Object, NetTraitsRequestDestination::Report => RequestDestination::Report, NetTraitsRequestDestination::Script => RequestDestination::Script, - NetTraitsRequestDestination::ServiceWorker - => panic!("ServiceWorker request destination should not be exposed to DOM"), + NetTraitsRequestDestination::ServiceWorker => { + panic!("ServiceWorker request destination should not be exposed to DOM") + }, NetTraitsRequestDestination::SharedWorker => RequestDestination::Sharedworker, NetTraitsRequestDestination::Style => RequestDestination::Style, NetTraitsRequestDestination::Track => RequestDestination::Track, @@ -757,8 +786,9 @@ impl Into<RequestMode> for NetTraitsRequestMode { NetTraitsRequestMode::SameOrigin => RequestMode::Same_origin, NetTraitsRequestMode::NoCors => RequestMode::No_cors, NetTraitsRequestMode::CorsMode => RequestMode::Cors, - NetTraitsRequestMode::WebSocket { .. } => - unreachable!("Websocket request mode should never be exposed to Dom"), + NetTraitsRequestMode::WebSocket { .. } => { + unreachable!("Websocket request mode should never be exposed to Dom") + }, } } } @@ -770,14 +800,16 @@ impl Into<MsgReferrerPolicy> for ReferrerPolicy { match self { ReferrerPolicy::_empty => MsgReferrerPolicy::NoReferrer, ReferrerPolicy::No_referrer => MsgReferrerPolicy::NoReferrer, - ReferrerPolicy::No_referrer_when_downgrade => - MsgReferrerPolicy::NoReferrerWhenDowngrade, + ReferrerPolicy::No_referrer_when_downgrade => { + MsgReferrerPolicy::NoReferrerWhenDowngrade + }, ReferrerPolicy::Origin => MsgReferrerPolicy::Origin, ReferrerPolicy::Origin_when_cross_origin => MsgReferrerPolicy::OriginWhenCrossOrigin, ReferrerPolicy::Unsafe_url => MsgReferrerPolicy::UnsafeUrl, ReferrerPolicy::Strict_origin => MsgReferrerPolicy::StrictOrigin, - ReferrerPolicy::Strict_origin_when_cross_origin => - MsgReferrerPolicy::StrictOriginWhenCrossOrigin, + ReferrerPolicy::Strict_origin_when_cross_origin => { + MsgReferrerPolicy::StrictOriginWhenCrossOrigin + }, } } } @@ -786,15 +818,17 @@ impl Into<ReferrerPolicy> for MsgReferrerPolicy { fn into(self) -> ReferrerPolicy { match self { MsgReferrerPolicy::NoReferrer => ReferrerPolicy::No_referrer, - MsgReferrerPolicy::NoReferrerWhenDowngrade => - ReferrerPolicy::No_referrer_when_downgrade, + MsgReferrerPolicy::NoReferrerWhenDowngrade => { + ReferrerPolicy::No_referrer_when_downgrade + }, MsgReferrerPolicy::Origin => ReferrerPolicy::Origin, MsgReferrerPolicy::SameOrigin => ReferrerPolicy::Origin, MsgReferrerPolicy::OriginWhenCrossOrigin => ReferrerPolicy::Origin_when_cross_origin, MsgReferrerPolicy::UnsafeUrl => ReferrerPolicy::Unsafe_url, MsgReferrerPolicy::StrictOrigin => ReferrerPolicy::Strict_origin, - MsgReferrerPolicy::StrictOriginWhenCrossOrigin => - ReferrerPolicy::Strict_origin_when_cross_origin, + MsgReferrerPolicy::StrictOriginWhenCrossOrigin => { + ReferrerPolicy::Strict_origin_when_cross_origin + }, } } } @@ -821,13 +855,14 @@ impl Into<RequestRedirect> for NetTraitsRequestRedirect { impl Clone for HeadersInit { fn clone(&self) -> HeadersInit { - match self { - &HeadersInit::Headers(ref h) => - HeadersInit::Headers(h.clone()), - &HeadersInit::ByteStringSequenceSequence(ref b) => - HeadersInit::ByteStringSequenceSequence(b.clone()), - &HeadersInit::StringByteStringRecord(ref m) => - HeadersInit::StringByteStringRecord(m.clone()), + match self { + &HeadersInit::Headers(ref h) => HeadersInit::Headers(h.clone()), + &HeadersInit::ByteStringSequenceSequence(ref b) => { + HeadersInit::ByteStringSequenceSequence(b.clone()) + }, + &HeadersInit::StringByteStringRecord(ref m) => { + HeadersInit::StringByteStringRecord(m.clone()) + }, } } } diff --git a/components/script/dom/response.rs b/components/script/dom/response.rs index ff806a5bf8f..613145a370a 100644 --- a/components/script/dom/response.rs +++ b/components/script/dom/response.rs @@ -67,22 +67,32 @@ impl Response { // https://fetch.spec.whatwg.org/#dom-response pub fn new(global: &GlobalScope) -> DomRoot<Response> { - reflect_dom_object(Box::new(Response::new_inherited()), global, ResponseBinding::Wrap) + reflect_dom_object( + Box::new(Response::new_inherited()), + global, + ResponseBinding::Wrap, + ) } - pub fn Constructor(global: &GlobalScope, body: Option<BodyInit>, init: &ResponseBinding::ResponseInit) - -> Fallible<DomRoot<Response>> { + pub fn Constructor( + global: &GlobalScope, + body: Option<BodyInit>, + init: &ResponseBinding::ResponseInit, + ) -> Fallible<DomRoot<Response>> { // Step 1 if init.status < 200 || init.status > 599 { - return Err(Error::Range( - format!("init's status member should be in the range 200 to 599, inclusive, but is {}" - , init.status))); + return Err(Error::Range(format!( + "init's status member should be in the range 200 to 599, inclusive, but is {}", + init.status + ))); } // Step 2 if !is_valid_status_text(&init.statusText) { - return Err(Error::Type("init's statusText member does not match the reason-phrase token production" - .to_string())); + return Err(Error::Type( + "init's statusText member does not match the reason-phrase token production" + .to_string(), + )); } // Step 3 @@ -108,7 +118,8 @@ impl Response { // Step 7.1 if is_null_body_status(init.status) { return Err(Error::Type( - "Body is non-null but init's status member is a null body status".to_string())); + "Body is non-null but init's status member is a null body status".to_string(), + )); }; // Step 7.3 @@ -117,9 +128,15 @@ impl Response { // Step 7.4 if let Some(content_type_contents) = content_type { - if !r.Headers().Has(ByteString::new(b"Content-Type".to_vec())).unwrap() { - r.Headers().Append(ByteString::new(b"Content-Type".to_vec()), - ByteString::new(content_type_contents.as_bytes().to_vec()))?; + if !r + .Headers() + .Has(ByteString::new(b"Content-Type".to_vec())) + .unwrap() + { + r.Headers().Append( + ByteString::new(b"Content-Type".to_vec()), + ByteString::new(content_type_contents.as_bytes().to_vec()), + )?; } }; } @@ -147,7 +164,11 @@ impl Response { } // https://fetch.spec.whatwg.org/#dom-response-redirect - pub fn Redirect(global: &GlobalScope, url: USVString, status: u16) -> Fallible<DomRoot<Response>> { + pub 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); @@ -172,8 +193,10 @@ impl Response { *r.raw_status.borrow_mut() = Some((status, b"".to_vec())); // Step 6 - let url_bytestring = ByteString::from_str(url.as_str()).unwrap_or(ByteString::new(b"".to_vec())); - r.Headers().Set(ByteString::new(b"Location".to_vec()), url_bytestring)?; + let url_bytestring = + ByteString::from_str(url.as_str()).unwrap_or(ByteString::new(b"".to_vec())); + r.Headers() + .Set(ByteString::new(b"Location".to_vec()), url_bytestring)?; // Step 4 continued // Headers Guard is set to Immutable here to prevent error in Step 6 @@ -209,9 +232,7 @@ impl BodyOperations for Response { fn take_body(&self) -> Option<Vec<u8>> { let body = mem::replace(&mut *self.body.borrow_mut(), NetTraitsResponseBody::Empty); match body { - NetTraitsResponseBody::Done(bytes) => { - Some(bytes) - }, + NetTraitsResponseBody::Done(bytes) => Some(bytes), body => { mem::replace(&mut *self.body.borrow_mut(), body); None @@ -248,12 +269,17 @@ fn is_null_body_status(status: u16) -> bool { impl ResponseMethods for Response { // https://fetch.spec.whatwg.org/#dom-response-type fn Type(&self) -> DOMResponseType { - *self.response_type.borrow()//into() + *self.response_type.borrow() //into() } // https://fetch.spec.whatwg.org/#dom-response-url fn Url(&self) -> USVString { - USVString(String::from((*self.url.borrow()).as_ref().map(|u| serialize_without_fragment(u)).unwrap_or(""))) + USVString(String::from( + (*self.url.borrow()) + .as_ref() + .map(|u| serialize_without_fragment(u)) + .unwrap_or(""), + )) } // https://fetch.spec.whatwg.org/#dom-response-redirected @@ -276,7 +302,7 @@ impl ResponseMethods for Response { Some(s) => { let status_num = s.to_u16(); return status_num >= 200 && status_num <= 299; - } + }, None => false, } } @@ -291,7 +317,8 @@ impl ResponseMethods for Response { // https://fetch.spec.whatwg.org/#dom-response-headers fn Headers(&self) -> DomRoot<Headers> { - self.headers_reflector.or_init(|| Headers::for_response(&self.global())) + self.headers_reflector + .or_init(|| Headers::for_response(&self.global())) } // https://fetch.spec.whatwg.org/#dom-response-clone @@ -304,7 +331,9 @@ impl ResponseMethods for Response { // Step 2 let new_response = Response::new(&self.global()); new_response.Headers().set_guard(self.Headers().get_guard()); - new_response.Headers().fill(Some(HeadersInit::Headers(self.Headers())))?; + new_response + .Headers() + .fill(Some(HeadersInit::Headers(self.Headers())))?; // https://fetch.spec.whatwg.org/#concept-response-clone // Instead of storing a net_traits::Response internally, we diff --git a/components/script/dom/screen.rs b/components/script/dom/screen.rs index 193b7705a42..d5a67de4ab9 100644 --- a/components/script/dom/screen.rs +++ b/components/script/dom/screen.rs @@ -33,24 +33,34 @@ impl Screen { } pub fn new(window: &Window) -> DomRoot<Screen> { - reflect_dom_object(Box::new(Screen::new_inherited(window)), - window, - ScreenBinding::Wrap) + reflect_dom_object( + Box::new(Screen::new_inherited(window)), + window, + ScreenBinding::Wrap, + ) } fn screen_size(&self) -> TypedSize2D<u32, CSSPixel> { - let (send, recv) = ipc::channel::<DeviceUintSize>(self.global().time_profiler_chan().clone()).unwrap(); - self.window.upcast::<GlobalScope>() - .script_to_constellation_chan().send(ScriptMsg::GetScreenSize(send)).unwrap(); + let (send, recv) = + ipc::channel::<DeviceUintSize>(self.global().time_profiler_chan().clone()).unwrap(); + self.window + .upcast::<GlobalScope>() + .script_to_constellation_chan() + .send(ScriptMsg::GetScreenSize(send)) + .unwrap(); let dpr = self.window.device_pixel_ratio(); let screen = recv.recv().unwrap_or(TypedSize2D::zero()); (screen.to_f32() / dpr).to_u32() } fn screen_avail_size(&self) -> TypedSize2D<u32, CSSPixel> { - let (send, recv) = ipc::channel::<DeviceUintSize>(self.global().time_profiler_chan().clone()).unwrap(); - self.window.upcast::<GlobalScope>() - .script_to_constellation_chan().send(ScriptMsg::GetScreenAvailSize(send)).unwrap(); + let (send, recv) = + ipc::channel::<DeviceUintSize>(self.global().time_profiler_chan().clone()).unwrap(); + self.window + .upcast::<GlobalScope>() + .script_to_constellation_chan() + .send(ScriptMsg::GetScreenAvailSize(send)) + .unwrap(); let dpr = self.window.device_pixel_ratio(); let screen = recv.recv().unwrap_or(TypedSize2D::zero()); (screen.to_f32() / dpr).to_u32() diff --git a/components/script/dom/serviceworker.rs b/components/script/dom/serviceworker.rs index e04bad6ad50..dcc20407c29 100644 --- a/components/script/dom/serviceworker.rs +++ b/components/script/dom/serviceworker.rs @@ -30,32 +30,34 @@ pub struct ServiceWorker { script_url: DomRefCell<String>, scope_url: ServoUrl, state: Cell<ServiceWorkerState>, - skip_waiting: Cell<bool> + skip_waiting: Cell<bool>, } impl ServiceWorker { - fn new_inherited(script_url: &str, - skip_waiting: bool, - scope_url: ServoUrl) -> ServiceWorker { + fn new_inherited(script_url: &str, skip_waiting: bool, scope_url: ServoUrl) -> ServiceWorker { ServiceWorker { eventtarget: EventTarget::new_inherited(), script_url: DomRefCell::new(String::from(script_url)), state: Cell::new(ServiceWorkerState::Installing), scope_url: scope_url, - skip_waiting: Cell::new(skip_waiting) + skip_waiting: Cell::new(skip_waiting), } } - pub fn install_serviceworker(global: &GlobalScope, - script_url: ServoUrl, - scope_url: ServoUrl, - skip_waiting: bool) -> DomRoot<ServiceWorker> { + pub fn install_serviceworker( + global: &GlobalScope, + script_url: ServoUrl, + scope_url: ServoUrl, + skip_waiting: bool, + ) -> DomRoot<ServiceWorker> { reflect_dom_object( Box::new(ServiceWorker::new_inherited( - script_url.as_str(), skip_waiting, scope_url + script_url.as_str(), + skip_waiting, + scope_url, )), global, - Wrap + Wrap, ) } @@ -66,7 +68,8 @@ impl ServiceWorker { pub fn set_transition_state(&self, state: ServiceWorkerState) { self.state.set(state); - self.upcast::<EventTarget>().fire_event(atom!("statechange")); + self.upcast::<EventTarget>() + .fire_event(atom!("statechange")); } pub fn get_script_url(&self) -> ServoUrl { @@ -95,10 +98,13 @@ impl ServiceWorkerMethods for ServiceWorker { // Step 7 let data = StructuredCloneData::write(cx, message)?; let msg_vec = DOMMessage(data.move_to_arraybuffer()); - let _ = - self.global() - .script_to_constellation_chan() - .send(ScriptMsg::ForwardDOMMessage(msg_vec, self.scope_url.clone())); + let _ = self + .global() + .script_to_constellation_chan() + .send(ScriptMsg::ForwardDOMMessage( + msg_vec, + self.scope_url.clone(), + )); Ok(()) } diff --git a/components/script/dom/serviceworkercontainer.rs b/components/script/dom/serviceworkercontainer.rs index d6886d541eb..2b73927adab 100644 --- a/components/script/dom/serviceworkercontainer.rs +++ b/components/script/dom/serviceworkercontainer.rs @@ -23,7 +23,7 @@ use std::rc::Rc; pub struct ServiceWorkerContainer { eventtarget: EventTarget, controller: MutNullableDom<ServiceWorker>, - client: Dom<Client> + client: Dom<Client>, } impl ServiceWorkerContainer { @@ -52,9 +52,7 @@ impl ServiceWorkerContainerMethods for ServiceWorkerContainer { #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#service-worker-container-register-method and - A // https://w3c.github.io/ServiceWorker/#start-register-algorithm - B - fn Register(&self, - script_url: USVString, - options: &RegistrationOptions) -> Rc<Promise> { + fn Register(&self, script_url: USVString, options: &RegistrationOptions) -> Rc<Promise> { // A: Step 1 let promise = Promise::new(&*self.global()); let USVString(ref script_url) = script_url; @@ -65,7 +63,7 @@ impl ServiceWorkerContainerMethods for ServiceWorkerContainer { Err(_) => { promise.reject_error(Error::Type("Invalid script URL".to_owned())); return promise; - } + }, }; // B: Step 2 match script_url.scheme() { @@ -73,12 +71,15 @@ impl ServiceWorkerContainerMethods for ServiceWorkerContainer { _ => { promise.reject_error(Error::Type("Only secure origins are allowed".to_owned())); return promise; - } + }, } // B: Step 3 if script_url.path().to_ascii_lowercase().contains("%2f") || - script_url.path().to_ascii_lowercase().contains("%5c") { - promise.reject_error(Error::Type("Script URL contains forbidden characters".to_owned())); + script_url.path().to_ascii_lowercase().contains("%5c") + { + promise.reject_error(Error::Type( + "Script URL contains forbidden characters".to_owned(), + )); return promise; } // B: Step 4-5 @@ -90,10 +91,10 @@ impl ServiceWorkerContainerMethods for ServiceWorkerContainer { Err(_) => { promise.reject_error(Error::Type("Invalid scope URL".to_owned())); return promise; - } + }, } }, - None => script_url.join("./").unwrap() + None => script_url.join("./").unwrap(), }; // B: Step 6 match scope.scheme() { @@ -101,17 +102,26 @@ impl ServiceWorkerContainerMethods for ServiceWorkerContainer { _ => { promise.reject_error(Error::Type("Only secure origins are allowed".to_owned())); return promise; - } + }, } // B: Step 7 if scope.path().to_ascii_lowercase().contains("%2f") || - scope.path().to_ascii_lowercase().contains("%5c") { - promise.reject_error(Error::Type("Scope URL contains forbidden characters".to_owned())); + scope.path().to_ascii_lowercase().contains("%5c") + { + promise.reject_error(Error::Type( + "Scope URL contains forbidden characters".to_owned(), + )); return promise; } // B: Step 8 - let job = Job::create_job(JobType::Register, scope, script_url, promise.clone(), &*self.client); + let job = Job::create_job( + JobType::Register, + scope, + script_url, + promise.clone(), + &*self.client, + ); ScriptThread::schedule_job(job); promise } diff --git a/components/script/dom/serviceworkerglobalscope.rs b/components/script/dom/serviceworkerglobalscope.rs index 3781ac3be69..9717910e4ff 100644 --- a/components/script/dom/serviceworkerglobalscope.rs +++ b/components/script/dom/serviceworkerglobalscope.rs @@ -55,7 +55,9 @@ impl QueuedTaskConversion for ServiceWorkerScriptMsg { _ => return None, }; match script_msg { - CommonScriptMsg::Task(_category, _boxed, _pipeline_id, task_source) => Some(&task_source), + CommonScriptMsg::Task(_category, _boxed, _pipeline_id, task_source) => { + Some(&task_source) + }, _ => return None, } } @@ -66,8 +68,9 @@ impl QueuedTaskConversion for ServiceWorkerScriptMsg { _ => return None, }; let (category, boxed, pipeline_id, task_source) = match script_msg { - CommonScriptMsg::Task(category, boxed, pipeline_id, task_source) => - (category, boxed, pipeline_id, task_source), + CommonScriptMsg::Task(category, boxed, pipeline_id, task_source) => { + (category, boxed, pipeline_id, task_source) + }, _ => return None, }; Some((None, category, boxed, pipeline_id, task_source)) @@ -94,18 +97,20 @@ impl QueuedTaskConversion for ServiceWorkerScriptMsg { pub enum MixedMessage { FromServiceWorker(ServiceWorkerScriptMsg), FromDevtools(DevtoolScriptControlMsg), - FromTimeoutThread(()) + FromTimeoutThread(()), } #[derive(Clone, JSTraceable)] pub struct ServiceWorkerChan { - pub sender: Sender<ServiceWorkerScriptMsg> + pub sender: Sender<ServiceWorkerScriptMsg>, } impl ScriptChan for ServiceWorkerChan { fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> { self.sender - .send(ServiceWorkerScriptMsg::CommonWorker(WorkerScriptMsg::Common(msg))) + .send(ServiceWorkerScriptMsg::CommonWorker( + WorkerScriptMsg::Common(msg), + )) .map_err(|_| ()) } @@ -167,44 +172,48 @@ impl WorkerEventLoopMethods for ServiceWorkerGlobalScope { } impl ServiceWorkerGlobalScope { - fn new_inherited(init: WorkerGlobalScopeInit, - worker_url: ServoUrl, - from_devtools_receiver: Receiver<DevtoolScriptControlMsg>, - runtime: Runtime, - own_sender: Sender<ServiceWorkerScriptMsg>, - receiver: Receiver<ServiceWorkerScriptMsg>, - timer_event_chan: IpcSender<TimerEvent>, - timer_event_port: Receiver<()>, - swmanager_sender: IpcSender<ServiceWorkerMsg>, - scope_url: ServoUrl) - -> ServiceWorkerGlobalScope { + fn new_inherited( + init: WorkerGlobalScopeInit, + worker_url: ServoUrl, + from_devtools_receiver: Receiver<DevtoolScriptControlMsg>, + runtime: Runtime, + own_sender: Sender<ServiceWorkerScriptMsg>, + receiver: Receiver<ServiceWorkerScriptMsg>, + timer_event_chan: IpcSender<TimerEvent>, + timer_event_port: Receiver<()>, + swmanager_sender: IpcSender<ServiceWorkerMsg>, + scope_url: ServoUrl, + ) -> ServiceWorkerGlobalScope { ServiceWorkerGlobalScope { - workerglobalscope: WorkerGlobalScope::new_inherited(init, - worker_url, - runtime, - from_devtools_receiver, - timer_event_chan, - None), + workerglobalscope: WorkerGlobalScope::new_inherited( + init, + worker_url, + runtime, + from_devtools_receiver, + timer_event_chan, + None, + ), task_queue: TaskQueue::new(receiver, own_sender.clone()), timer_event_port: timer_event_port, own_sender: own_sender, swmanager_sender: swmanager_sender, - scope_url: scope_url + scope_url: scope_url, } } #[allow(unsafe_code)] - pub fn new(init: WorkerGlobalScopeInit, - worker_url: ServoUrl, - from_devtools_receiver: Receiver<DevtoolScriptControlMsg>, - runtime: Runtime, - own_sender: Sender<ServiceWorkerScriptMsg>, - receiver: Receiver<ServiceWorkerScriptMsg>, - timer_event_chan: IpcSender<TimerEvent>, - timer_event_port: Receiver<()>, - swmanager_sender: IpcSender<ServiceWorkerMsg>, - scope_url: ServoUrl) - -> DomRoot<ServiceWorkerGlobalScope> { + pub fn new( + init: WorkerGlobalScopeInit, + worker_url: ServoUrl, + from_devtools_receiver: Receiver<DevtoolScriptControlMsg>, + runtime: Runtime, + own_sender: Sender<ServiceWorkerScriptMsg>, + receiver: Receiver<ServiceWorkerScriptMsg>, + timer_event_chan: IpcSender<TimerEvent>, + timer_event_port: Receiver<()>, + swmanager_sender: IpcSender<ServiceWorkerMsg>, + scope_url: ServoUrl, + ) -> DomRoot<ServiceWorkerGlobalScope> { let cx = runtime.cx(); let scope = Box::new(ServiceWorkerGlobalScope::new_inherited( init, @@ -216,119 +225,161 @@ impl ServiceWorkerGlobalScope { timer_event_chan, timer_event_port, swmanager_sender, - scope_url + scope_url, )); - unsafe { - ServiceWorkerGlobalScopeBinding::Wrap(cx, scope) - } + unsafe { ServiceWorkerGlobalScopeBinding::Wrap(cx, scope) } } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#run-a-worker - pub fn run_serviceworker_scope(scope_things: ScopeThings, - own_sender: Sender<ServiceWorkerScriptMsg>, - receiver: Receiver<ServiceWorkerScriptMsg>, - devtools_receiver: IpcReceiver<DevtoolScriptControlMsg>, - swmanager_sender: IpcSender<ServiceWorkerMsg>, - scope_url: ServoUrl) { - let ScopeThings { script_url, - init, - worker_load_origin, - .. } = scope_things; + pub fn run_serviceworker_scope( + scope_things: ScopeThings, + own_sender: Sender<ServiceWorkerScriptMsg>, + receiver: Receiver<ServiceWorkerScriptMsg>, + devtools_receiver: IpcReceiver<DevtoolScriptControlMsg>, + swmanager_sender: IpcSender<ServiceWorkerMsg>, + scope_url: ServoUrl, + ) { + let ScopeThings { + script_url, + init, + worker_load_origin, + .. + } = scope_things; let serialized_worker_url = script_url.to_string(); - let origin = GlobalScope::current().expect("No current global object").origin().immutable().clone(); - thread::Builder::new().name(format!("ServiceWorker for {}", serialized_worker_url)).spawn(move || { - thread_state::initialize(ThreadState::SCRIPT | ThreadState::IN_WORKER); - let roots = RootCollection::new(); - let _stack_roots = ThreadLocalStackRoots::new(&roots); - - let WorkerScriptLoadOrigin { referrer_url, referrer_policy, pipeline_id } = worker_load_origin; - - let request = RequestInit { - url: script_url.clone(), - destination: Destination::ServiceWorker, - credentials_mode: CredentialsMode::Include, - use_url_credentials: true, - pipeline_id: pipeline_id, - referrer_url: referrer_url, - referrer_policy: referrer_policy, - origin, - .. RequestInit::default() - }; - - let (url, source) = match load_whole_resource(request, - &init.resource_threads.sender()) { - Err(_) => { - println!("error loading script {}", serialized_worker_url); - return; - } - Ok((metadata, bytes)) => { - (metadata.final_url, String::from_utf8(bytes).unwrap()) + let origin = GlobalScope::current() + .expect("No current global object") + .origin() + .immutable() + .clone(); + thread::Builder::new() + .name(format!("ServiceWorker for {}", serialized_worker_url)) + .spawn(move || { + thread_state::initialize(ThreadState::SCRIPT | ThreadState::IN_WORKER); + let roots = RootCollection::new(); + let _stack_roots = ThreadLocalStackRoots::new(&roots); + + let WorkerScriptLoadOrigin { + referrer_url, + referrer_policy, + pipeline_id, + } = worker_load_origin; + + let request = RequestInit { + url: script_url.clone(), + destination: Destination::ServiceWorker, + credentials_mode: CredentialsMode::Include, + use_url_credentials: true, + pipeline_id: pipeline_id, + referrer_url: referrer_url, + referrer_policy: referrer_policy, + origin, + ..RequestInit::default() + }; + + let (url, source) = + match load_whole_resource(request, &init.resource_threads.sender()) { + Err(_) => { + println!("error loading script {}", serialized_worker_url); + return; + }, + Ok((metadata, bytes)) => { + (metadata.final_url, String::from_utf8(bytes).unwrap()) + }, + }; + + let runtime = unsafe { new_rt_and_cx() }; + + let (devtools_mpsc_chan, devtools_mpsc_port) = channel(); + route_ipc_receiver_to_new_servo_sender(devtools_receiver, devtools_mpsc_chan); + // TODO XXXcreativcoder use this timer_ipc_port, when we have a service worker instance here + let (timer_ipc_chan, _timer_ipc_port) = ipc::channel().unwrap(); + let (timer_chan, timer_port) = channel(); + let global = ServiceWorkerGlobalScope::new( + init, + url, + devtools_mpsc_port, + runtime, + own_sender, + receiver, + timer_ipc_chan, + timer_port, + swmanager_sender, + scope_url, + ); + let scope = global.upcast::<WorkerGlobalScope>(); + + unsafe { + // Handle interrupt requests + JS_AddInterruptCallback(scope.get_cx(), Some(interrupt_callback)); } - }; - - let runtime = unsafe { new_rt_and_cx() }; - - let (devtools_mpsc_chan, devtools_mpsc_port) = channel(); - route_ipc_receiver_to_new_servo_sender(devtools_receiver, devtools_mpsc_chan); - // TODO XXXcreativcoder use this timer_ipc_port, when we have a service worker instance here - let (timer_ipc_chan, _timer_ipc_port) = ipc::channel().unwrap(); - let (timer_chan, timer_port) = channel(); - let global = ServiceWorkerGlobalScope::new( - init, url, devtools_mpsc_port, runtime, - own_sender, receiver, - timer_ipc_chan, timer_port, swmanager_sender, scope_url); - let scope = global.upcast::<WorkerGlobalScope>(); - - unsafe { - // Handle interrupt requests - JS_AddInterruptCallback(scope.get_cx(), Some(interrupt_callback)); - } - - scope.execute_script(DOMString::from(source)); - // Service workers are time limited - thread::Builder::new().name("SWTimeoutThread".to_owned()).spawn(move || { - let sw_lifetime_timeout = PREFS.get("dom.serviceworker.timeout_seconds").as_u64().unwrap(); - thread::sleep(Duration::new(sw_lifetime_timeout, 0)); - let _ = timer_chan.send(()); - }).expect("Thread spawning failed"); - - global.dispatch_activate(); - let reporter_name = format!("service-worker-reporter-{}", random::<u64>()); - scope.upcast::<GlobalScope>().mem_profiler_chan().run_with_memory_reporting(|| { - // Step 29, Run the responsible event loop specified by inside settings until it is destroyed. - // The worker processing model remains on this step until the event loop is destroyed, - // which happens after the closing flag is set to true. - while !scope.is_closing() { - run_worker_event_loop(&*global, None); - } - }, reporter_name, scope.script_chan(), CommonScriptMsg::CollectReports); - }).expect("Thread spawning failed"); + + scope.execute_script(DOMString::from(source)); + // Service workers are time limited + thread::Builder::new() + .name("SWTimeoutThread".to_owned()) + .spawn(move || { + let sw_lifetime_timeout = PREFS + .get("dom.serviceworker.timeout_seconds") + .as_u64() + .unwrap(); + thread::sleep(Duration::new(sw_lifetime_timeout, 0)); + let _ = timer_chan.send(()); + }) + .expect("Thread spawning failed"); + + global.dispatch_activate(); + let reporter_name = format!("service-worker-reporter-{}", random::<u64>()); + scope + .upcast::<GlobalScope>() + .mem_profiler_chan() + .run_with_memory_reporting( + || { + // Step 29, Run the responsible event loop specified + // by inside settings until it is destroyed. + // The worker processing model remains on this step + // until the event loop is destroyed, + // which happens after the closing flag is set to true. + while !scope.is_closing() { + run_worker_event_loop(&*global, None); + } + }, + reporter_name, + scope.script_chan(), + CommonScriptMsg::CollectReports, + ); + }) + .expect("Thread spawning failed"); } fn handle_mixed_message(&self, msg: MixedMessage) -> bool { match msg { MixedMessage::FromDevtools(msg) => { match msg { - DevtoolScriptControlMsg::EvaluateJS(_pipe_id, string, sender) => - devtools::handle_evaluate_js(self.upcast(), string, sender), - DevtoolScriptControlMsg::GetCachedMessages(pipe_id, message_types, sender) => - devtools::handle_get_cached_messages(pipe_id, message_types, sender), - DevtoolScriptControlMsg::WantsLiveNotifications(_pipe_id, bool_val) => - devtools::handle_wants_live_notifications(self.upcast(), bool_val), + DevtoolScriptControlMsg::EvaluateJS(_pipe_id, string, sender) => { + devtools::handle_evaluate_js(self.upcast(), string, sender) + }, + DevtoolScriptControlMsg::GetCachedMessages(pipe_id, message_types, sender) => { + devtools::handle_get_cached_messages(pipe_id, message_types, sender) + }, + DevtoolScriptControlMsg::WantsLiveNotifications(_pipe_id, bool_val) => { + devtools::handle_wants_live_notifications(self.upcast(), bool_val) + }, _ => debug!("got an unusable devtools control message inside the worker!"), } true - } + }, MixedMessage::FromServiceWorker(msg) => { self.handle_script_event(msg); true - } + }, MixedMessage::FromTimeoutThread(_) => { - let _ = self.swmanager_sender.send(ServiceWorkerMsg::Timeout(self.scope_url.clone())); + let _ = self + .swmanager_sender + .send(ServiceWorkerMsg::Timeout(self.scope_url.clone())); false - } + }, } } @@ -339,7 +390,8 @@ impl ServiceWorkerGlobalScope { CommonWorker(WorkerScriptMsg::DOMMessage(data)) => { let scope = self.upcast::<WorkerGlobalScope>(); let target = self.upcast(); - let _ac = JSAutoCompartment::new(scope.get_cx(), scope.reflector().get_jsobject().get()); + let _ac = + JSAutoCompartment::new(scope.get_cx(), scope.reflector().get_jsobject().get()); rooted!(in(scope.get_cx()) let mut message = UndefinedValue()); data.read(scope.upcast(), message.handle_mut()); ExtendableMessageEvent::dispatch_jsval(target, scope.upcast(), message.handle()); @@ -360,7 +412,7 @@ impl ServiceWorkerGlobalScope { pub fn script_chan(&self) -> Box<ScriptChan + Send> { Box::new(ServiceWorkerChan { - sender: self.own_sender.clone() + sender: self.own_sender.clone(), }) } @@ -373,9 +425,8 @@ impl ServiceWorkerGlobalScope { #[allow(unsafe_code)] unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool { - let worker = - DomRoot::downcast::<WorkerGlobalScope>(GlobalScope::from_context(cx)) - .expect("global is not a worker scope"); + let worker = DomRoot::downcast::<WorkerGlobalScope>(GlobalScope::from_context(cx)) + .expect("global is not a worker scope"); assert!(worker.is::<ServiceWorkerGlobalScope>()); // A false response causes the script to terminate diff --git a/components/script/dom/serviceworkerregistration.rs b/components/script/dom/serviceworkerregistration.rs index a16c1418971..ecdf4d6ed04 100644 --- a/components/script/dom/serviceworkerregistration.rs +++ b/components/script/dom/serviceworkerregistration.rs @@ -16,7 +16,6 @@ use script_traits::{WorkerScriptLoadOrigin, ScopeThings}; use servo_url::ServoUrl; use std::cell::Cell; - #[dom_struct] pub struct ServiceWorkerRegistration { eventtarget: EventTarget, @@ -24,7 +23,7 @@ pub struct ServiceWorkerRegistration { installing: Option<Dom<ServiceWorker>>, waiting: Option<Dom<ServiceWorker>>, scope: ServoUrl, - uninstalling: Cell<bool> + uninstalling: Cell<bool>, } impl ServiceWorkerRegistration { @@ -35,16 +34,26 @@ impl ServiceWorkerRegistration { installing: None, waiting: None, scope: scope, - uninstalling: Cell::new(false) + uninstalling: Cell::new(false), } } #[allow(unrooted_must_root)] - pub fn new(global: &GlobalScope, - script_url: &ServoUrl, - scope: ServoUrl) -> DomRoot<ServiceWorkerRegistration> { - let active_worker = ServiceWorker::install_serviceworker(global, script_url.clone(), scope.clone(), true); + pub fn new( + global: &GlobalScope, + script_url: &ServoUrl, + scope: ServoUrl, + ) -> DomRoot<ServiceWorkerRegistration> { + let active_worker = + ServiceWorker::install_serviceworker(global, script_url.clone(), scope.clone(), true); active_worker.set_transition_state(ServiceWorkerState::Installed); - reflect_dom_object(Box::new(ServiceWorkerRegistration::new_inherited(&*active_worker, scope)), global, Wrap) + reflect_dom_object( + Box::new(ServiceWorkerRegistration::new_inherited( + &*active_worker, + scope, + )), + global, + Wrap, + ) } pub fn get_installed(&self) -> &ServiceWorker { @@ -63,7 +72,7 @@ impl ServiceWorkerRegistration { let worker_load_origin = WorkerScriptLoadOrigin { referrer_url: None, referrer_policy: None, - pipeline_id: Some(global.pipeline_id()) + pipeline_id: Some(global.pipeline_id()), }; let worker_id = global.get_next_worker_id(); @@ -74,7 +83,7 @@ impl ServiceWorkerRegistration { init: init, worker_load_origin: worker_load_origin, devtools_chan: devtools_chan, - worker_id: worker_id + worker_id: worker_id, } } @@ -100,7 +109,11 @@ pub fn longest_prefix_match(stored_scope: &ServoUrl, potential_match: &ServoUrl) return false; } - stored_scope.path().chars().zip(potential_match.path().chars()).all(|(scope, matched)| scope == matched) + stored_scope + .path() + .chars() + .zip(potential_match.path().chars()) + .all(|(scope, matched)| scope == matched) } impl ServiceWorkerRegistrationMethods for ServiceWorkerRegistration { diff --git a/components/script/dom/servoparser/async_html.rs b/components/script/dom/servoparser/async_html.rs index 5fe911deb0b..051ea86cfb0 100644 --- a/components/script/dom/servoparser/async_html.rs +++ b/components/script/dom/servoparser/async_html.rs @@ -58,49 +58,77 @@ struct Attribute { #[derive(JSTraceable, MallocSizeOf)] enum ParseOperation { - GetTemplateContents { target: ParseNodeId, contents: ParseNodeId }, + GetTemplateContents { + target: ParseNodeId, + contents: ParseNodeId, + }, CreateElement { node: ParseNodeId, name: QualName, attrs: Vec<Attribute>, - current_line: u64 + current_line: u64, }, - CreateComment { text: String, node: ParseNodeId }, - AppendBeforeSibling { sibling: ParseNodeId, node: NodeOrText }, - AppendBasedOnParentNode { element: ParseNodeId, prev_element: ParseNodeId, node: NodeOrText }, - Append { parent: ParseNodeId, node: NodeOrText }, + CreateComment { + text: String, + node: ParseNodeId, + }, + AppendBeforeSibling { + sibling: ParseNodeId, + node: NodeOrText, + }, + AppendBasedOnParentNode { + element: ParseNodeId, + prev_element: ParseNodeId, + node: NodeOrText, + }, + Append { + parent: ParseNodeId, + node: NodeOrText, + }, AppendDoctypeToDocument { name: String, public_id: String, - system_id: String + system_id: String, }, - AddAttrsIfMissing { target: ParseNodeId, attrs: Vec<Attribute> }, - RemoveFromParent { target: ParseNodeId }, - MarkScriptAlreadyStarted { node: ParseNodeId }, - ReparentChildren { parent: ParseNodeId, new_parent: ParseNodeId }, + AddAttrsIfMissing { + target: ParseNodeId, + attrs: Vec<Attribute>, + }, + RemoveFromParent { + target: ParseNodeId, + }, + MarkScriptAlreadyStarted { + node: ParseNodeId, + }, + ReparentChildren { + parent: ParseNodeId, + new_parent: ParseNodeId, + }, AssociateWithForm { target: ParseNodeId, form: ParseNodeId, element: ParseNodeId, - prev_element: Option<ParseNodeId> + prev_element: Option<ParseNodeId>, }, CreatePI { node: ParseNodeId, target: String, - data: String + data: String, }, - Pop { node: ParseNodeId }, + Pop { + node: ParseNodeId, + }, SetQuirksMode { #[ignore_malloc_size_of = "Defined in style"] - mode: ServoQuirksMode + mode: ServoQuirksMode, }, } @@ -109,12 +137,12 @@ enum ToTokenizerMsg { // From HtmlTokenizer TokenizerResultDone { #[ignore_malloc_size_of = "Defined in html5ever"] - updated_input: VecDeque<SendTendril<UTF8>> + updated_input: VecDeque<SendTendril<UTF8>>, }, TokenizerResultScript { script: ParseNode, #[ignore_malloc_size_of = "Defined in html5ever"] - updated_input: VecDeque<SendTendril<UTF8>> + updated_input: VecDeque<SendTendril<UTF8>>, }, End, // Sent to Tokenizer to signify HtmlTokenizer's end method has returned @@ -126,7 +154,7 @@ enum ToTokenizerMsg { enum ToHtmlTokenizerMsg { Feed { #[ignore_malloc_size_of = "Defined in html5ever"] - input: VecDeque<SendTendril<UTF8>> + input: VecDeque<SendTendril<UTF8>>, }, End, SetPlainTextState, @@ -180,10 +208,10 @@ pub struct Tokenizer { impl Tokenizer { pub fn new( - document: &Document, - url: ServoUrl, - fragment_context: Option<super::FragmentContext>) - -> Self { + document: &Document, + url: ServoUrl, + fragment_context: Option<super::FragmentContext>, + ) -> Self { // Messages from the Tokenizer (main thread) to HtmlTokenizer (parser thread) let (to_html_tokenizer_sender, html_tokenizer_receiver) = channel(); // Messages from HtmlTokenizer and Sink (parser thread) to Tokenizer (main thread) @@ -194,7 +222,7 @@ impl Tokenizer { receiver: tokenizer_receiver, html_tokenizer_sender: to_html_tokenizer_sender, nodes: HashMap::new(), - url: url + url: url, }; tokenizer.insert_node(0, Dom::from_ref(document.upcast())); @@ -218,14 +246,18 @@ impl Tokenizer { // Create new thread for HtmlTokenizer. This is where parser actions // will be generated from the input provided. These parser actions are then passed // onto the main thread to be executed. - thread::Builder::new().name(String::from("HTML Parser")).spawn(move || { - run(sink, - fragment_context_is_some, - ctxt_parse_node, - form_parse_node, - to_tokenizer_sender, - html_tokenizer_receiver); - }).expect("HTML Parser thread spawning failed"); + thread::Builder::new() + .name(String::from("HTML Parser")) + .spawn(move || { + run( + sink, + fragment_context_is_some, + ctxt_parse_node, + form_parse_node, + to_tokenizer_sender, + html_tokenizer_receiver, + ); + }).expect("HTML Parser thread spawning failed"); tokenizer } @@ -238,31 +270,47 @@ impl Tokenizer { // Send message to parser thread, asking it to start reading from the input. // Parser operation messages will be sent to main thread as they are evaluated. - self.html_tokenizer_sender.send(ToHtmlTokenizerMsg::Feed { input: send_tendrils }).unwrap(); + self.html_tokenizer_sender + .send(ToHtmlTokenizerMsg::Feed { + input: send_tendrils, + }).unwrap(); loop { - match self.receiver.recv().expect("Unexpected channel panic in main thread.") { + match self + .receiver + .recv() + .expect("Unexpected channel panic in main thread.") + { ToTokenizerMsg::ProcessOperation(parse_op) => self.process_operation(parse_op), ToTokenizerMsg::TokenizerResultDone { updated_input } => { let buffer_queue = create_buffer_queue(updated_input); *input = buffer_queue; return Ok(()); }, - ToTokenizerMsg::TokenizerResultScript { script, updated_input } => { + ToTokenizerMsg::TokenizerResultScript { + script, + updated_input, + } => { let buffer_queue = create_buffer_queue(updated_input); *input = buffer_queue; let script = self.get_node(&script.id); return Err(DomRoot::from_ref(script.downcast().unwrap())); - } + }, ToTokenizerMsg::End => unreachable!(), }; } } pub fn end(&mut self) { - self.html_tokenizer_sender.send(ToHtmlTokenizerMsg::End).unwrap(); + self.html_tokenizer_sender + .send(ToHtmlTokenizerMsg::End) + .unwrap(); loop { - match self.receiver.recv().expect("Unexpected channel panic in main thread.") { + match self + .receiver + .recv() + .expect("Unexpected channel panic in main thread.") + { ToTokenizerMsg::ProcessOperation(parse_op) => self.process_operation(parse_op), ToTokenizerMsg::End => return, _ => unreachable!(), @@ -275,7 +323,9 @@ impl Tokenizer { } pub fn set_plaintext_state(&mut self) { - self.html_tokenizer_sender.send(ToHtmlTokenizerMsg::SetPlainTextState).unwrap(); + self.html_tokenizer_sender + .send(ToHtmlTokenizerMsg::SetPlainTextState) + .unwrap(); } fn insert_node(&mut self, id: ParseNodeId, node: Dom<Node>) { @@ -286,26 +336,27 @@ impl Tokenizer { self.nodes.get(id).expect("Node not found!") } - fn append_before_sibling(&mut self, sibling: ParseNodeId, node: NodeOrText) { let node = match node { - NodeOrText::Node(n) => HtmlNodeOrText::AppendNode(Dom::from_ref(&**self.get_node(&n.id))), - NodeOrText::Text(text) => HtmlNodeOrText::AppendText( - Tendril::from(text) - ) + NodeOrText::Node(n) => { + HtmlNodeOrText::AppendNode(Dom::from_ref(&**self.get_node(&n.id))) + }, + NodeOrText::Text(text) => HtmlNodeOrText::AppendText(Tendril::from(text)), }; let sibling = &**self.get_node(&sibling); - let parent = &*sibling.GetParentNode().expect("append_before_sibling called on node without parent"); + let parent = &*sibling + .GetParentNode() + .expect("append_before_sibling called on node without parent"); super::insert(parent, Some(sibling), node); } fn append(&mut self, parent: ParseNodeId, node: NodeOrText) { let node = match node { - NodeOrText::Node(n) => HtmlNodeOrText::AppendNode(Dom::from_ref(&**self.get_node(&n.id))), - NodeOrText::Text(text) => HtmlNodeOrText::AppendText( - Tendril::from(text) - ) + NodeOrText::Node(n) => { + HtmlNodeOrText::AppendNode(Dom::from_ref(&**self.get_node(&n.id))) + }, + NodeOrText::Text(text) => HtmlNodeOrText::AppendText(Tendril::from(text)), }; let parent = &**self.get_node(&parent); @@ -327,15 +378,23 @@ impl Tokenizer { fn process_operation(&mut self, op: ParseOperation) { let document = DomRoot::from_ref(&**self.get_node(&0)); - let document = document.downcast::<Document>().expect("Document node should be downcasted!"); + let document = document + .downcast::<Document>() + .expect("Document node should be downcasted!"); match op { ParseOperation::GetTemplateContents { target, contents } => { let target = DomRoot::from_ref(&**self.get_node(&target)); - let template = target.downcast::<HTMLTemplateElement>().expect( - "Tried to extract contents from non-template element while parsing"); + let template = target + .downcast::<HTMLTemplateElement>() + .expect("Tried to extract contents from non-template element while parsing"); self.insert_node(contents, Dom::from_ref(template.Content().upcast())); - } - ParseOperation::CreateElement { node, name, attrs, current_line } => { + }, + ParseOperation::CreateElement { + node, + name, + attrs, + current_line, + } => { let attrs = attrs .into_iter() .map(|attr| ElementAttribute::new(attr.name, DOMString::from(attr.value))) @@ -345,60 +404,85 @@ impl Tokenizer { attrs, &*self.document, ElementCreator::ParserCreated(current_line), - ParsingAlgorithm::Normal + ParsingAlgorithm::Normal, ); self.insert_node(node, Dom::from_ref(element.upcast())); - } + }, ParseOperation::CreateComment { text, node } => { let comment = Comment::new(DOMString::from(text), document); self.insert_node(node, Dom::from_ref(&comment.upcast())); - } + }, ParseOperation::AppendBeforeSibling { sibling, node } => { self.append_before_sibling(sibling, node); - } + }, ParseOperation::Append { parent, node } => { self.append(parent, node); - } - ParseOperation::AppendBasedOnParentNode { element, prev_element, node } => { + }, + ParseOperation::AppendBasedOnParentNode { + element, + prev_element, + node, + } => { if self.has_parent_node(element) { self.append_before_sibling(element, node); } else { self.append(prev_element, node); } - } - ParseOperation::AppendDoctypeToDocument { name, public_id, system_id } => { + }, + ParseOperation::AppendDoctypeToDocument { + name, + public_id, + system_id, + } => { let doctype = DocumentType::new( - DOMString::from(String::from(name)), Some(DOMString::from(public_id)), - Some(DOMString::from(system_id)), document); + DOMString::from(String::from(name)), + Some(DOMString::from(public_id)), + Some(DOMString::from(system_id)), + document, + ); - document.upcast::<Node>().AppendChild(doctype.upcast()).expect("Appending failed"); - } + document + .upcast::<Node>() + .AppendChild(doctype.upcast()) + .expect("Appending failed"); + }, ParseOperation::AddAttrsIfMissing { target, attrs } => { - let elem = self.get_node(&target).downcast::<Element>() + let elem = self + .get_node(&target) + .downcast::<Element>() .expect("tried to set attrs on non-Element in HTML parsing"); for attr in attrs { elem.set_attribute_from_parser(attr.name, DOMString::from(attr.value), None); } - } + }, ParseOperation::RemoveFromParent { target } => { if let Some(ref parent) = self.get_node(&target).GetParentNode() { parent.RemoveChild(&**self.get_node(&target)).unwrap(); } - } + }, ParseOperation::MarkScriptAlreadyStarted { node } => { let script = self.get_node(&node).downcast::<HTMLScriptElement>(); script.map(|script| script.set_already_started(true)); - } + }, ParseOperation::ReparentChildren { parent, new_parent } => { let parent = self.get_node(&parent); let new_parent = self.get_node(&new_parent); while let Some(child) = parent.GetFirstChild() { new_parent.AppendChild(&child).unwrap(); } - } - ParseOperation::AssociateWithForm { target, form, element, prev_element } => { + }, + ParseOperation::AssociateWithForm { + target, + form, + element, + prev_element, + } => { let tree_node = prev_element.map_or(element, |prev| { - if self.has_parent_node(element) { element } else { prev } + if self.has_parent_node(element) { + element + } else { + prev + } }); if !self.same_tree(tree_node, form) { @@ -416,47 +500,51 @@ impl Tokenizer { control.set_form_owner_from_parser(&form); } else { // TODO remove this code when keygen is implemented. - assert_eq!(node.NodeName(), "KEYGEN", "Unknown form-associatable element"); + assert_eq!( + node.NodeName(), + "KEYGEN", + "Unknown form-associatable element" + ); } - } + }, ParseOperation::Pop { node } => { vtable_for(self.get_node(&node)).pop(); - } + }, ParseOperation::CreatePI { node, target, data } => { let pi = ProcessingInstruction::new( DOMString::from(target), DOMString::from(data), - document); + document, + ); self.insert_node(node, Dom::from_ref(pi.upcast())); - } + }, ParseOperation::SetQuirksMode { mode } => { document.set_quirks_mode(mode); - } + }, } } } -fn run(sink: Sink, - fragment_context_is_some: bool, - ctxt_parse_node: Option<ParseNode>, - form_parse_node: Option<ParseNode>, - sender: Sender<ToTokenizerMsg>, - receiver: Receiver<ToHtmlTokenizerMsg>) { +fn run( + sink: Sink, + fragment_context_is_some: bool, + ctxt_parse_node: Option<ParseNode>, + form_parse_node: Option<ParseNode>, + sender: Sender<ToTokenizerMsg>, + receiver: Receiver<ToHtmlTokenizerMsg>, +) { let options = TreeBuilderOpts { ignore_missing_rules: true, - .. Default::default() + ..Default::default() }; let mut html_tokenizer = if fragment_context_is_some { - let tb = TreeBuilder::new_for_fragment( - sink, - ctxt_parse_node.unwrap(), - form_parse_node, - options); + let tb = + TreeBuilder::new_for_fragment(sink, ctxt_parse_node.unwrap(), form_parse_node, options); let tok_options = TokenizerOpts { initial_state: Some(tb.tokenizer_state_for_context_elem()), - .. Default::default() + ..Default::default() }; HtmlTokenizer::new(tb, tok_options) @@ -465,7 +553,10 @@ fn run(sink: Sink, }; loop { - match receiver.recv().expect("Unexpected channel panic in html parser thread") { + match receiver + .recv() + .expect("Unexpected channel panic in html parser thread") + { ToHtmlTokenizerMsg::Feed { input } => { let mut input = create_buffer_queue(input); let res = html_tokenizer.feed(&mut input); @@ -479,7 +570,10 @@ fn run(sink: Sink, let res = match res { TokenizerResult::Done => ToTokenizerMsg::TokenizerResultDone { updated_input }, - TokenizerResult::Script(script) => ToTokenizerMsg::TokenizerResultScript { script, updated_input } + TokenizerResult::Script(script) => ToTokenizerMsg::TokenizerResultScript { + script, + updated_input, + }, }; sender.send(res).unwrap(); }, @@ -488,7 +582,7 @@ fn run(sink: Sink, sender.send(ToTokenizerMsg::End).unwrap(); break; }, - ToHtmlTokenizerMsg::SetPlainTextState => html_tokenizer.set_plaintext_state() + ToHtmlTokenizerMsg::SetPlainTextState => html_tokenizer.set_plaintext_state(), }; } } @@ -517,7 +611,7 @@ impl Sink { id: 0, qual_name: None, }, - sender: sender + sender: sender, }; let data = ParseNodeData::default(); sink.insert_parse_node_data(0, data); @@ -536,7 +630,9 @@ impl Sink { } fn send_op(&self, op: ParseOperation) { - self.sender.send(ToTokenizerMsg::ProcessOperation(op)).unwrap(); + self.sender + .send(ToTokenizerMsg::ProcessOperation(op)) + .unwrap(); } fn insert_parse_node_data(&mut self, id: ParseNodeId, data: ParseNodeData) { @@ -544,18 +640,24 @@ impl Sink { } fn get_parse_node_data<'a>(&'a self, id: &'a ParseNodeId) -> &'a ParseNodeData { - self.parse_node_data.get(id).expect("Parse Node data not found!") + self.parse_node_data + .get(id) + .expect("Parse Node data not found!") } fn get_parse_node_data_mut<'a>(&'a mut self, id: &'a ParseNodeId) -> &'a mut ParseNodeData { - self.parse_node_data.get_mut(id).expect("Parse Node data not found!") + self.parse_node_data + .get_mut(id) + .expect("Parse Node data not found!") } } #[allow(unrooted_must_root)] impl TreeSink for Sink { type Output = Self; - fn finish(self) -> Self { self } + fn finish(self) -> Self { + self + } type Handle = ParseNode; @@ -572,7 +674,10 @@ impl TreeSink for Sink { let data = self.get_parse_node_data_mut(&target.id); data.contents = Some(node.clone()); } - self.send_op(ParseOperation::GetTemplateContents { target: target.id, contents: node.id }); + self.send_op(ParseOperation::GetTemplateContents { + target: target.id, + contents: node.id, + }); node } @@ -581,38 +686,52 @@ impl TreeSink for Sink { } fn elem_name<'a>(&self, target: &'a Self::Handle) -> ExpandedName<'a> { - target.qual_name.as_ref().expect("Expected qual name of node!").expanded() + target + .qual_name + .as_ref() + .expect("Expected qual name of node!") + .expanded() } - fn create_element(&mut self, name: QualName, html_attrs: Vec<HtmlAttribute>, _flags: ElementFlags) - -> Self::Handle { + fn create_element( + &mut self, + name: QualName, + html_attrs: Vec<HtmlAttribute>, + _flags: ElementFlags, + ) -> Self::Handle { let mut node = self.new_parse_node(); node.qual_name = Some(name.clone()); { let node_data = self.get_parse_node_data_mut(&node.id); - node_data.is_integration_point = html_attrs.iter() - .any(|attr| { + node_data.is_integration_point = html_attrs.iter().any(|attr| { let attr_value = &String::from(attr.value.clone()); (attr.name.local == local_name!("encoding") && attr.name.ns == ns!()) && - (attr_value.eq_ignore_ascii_case("text/html") || - attr_value.eq_ignore_ascii_case("application/xhtml+xml")) + (attr_value.eq_ignore_ascii_case("text/html") || + attr_value.eq_ignore_ascii_case("application/xhtml+xml")) }); } - let attrs = html_attrs.into_iter() - .map(|attr| Attribute { name: attr.name, value: String::from(attr.value) }).collect(); + let attrs = html_attrs + .into_iter() + .map(|attr| Attribute { + name: attr.name, + value: String::from(attr.value), + }).collect(); self.send_op(ParseOperation::CreateElement { node: node.id, name, attrs, - current_line: self.current_line + current_line: self.current_line, }); node } fn create_comment(&mut self, text: StrTendril) -> Self::Handle { let node = self.new_parse_node(); - self.send_op(ParseOperation::CreateComment { text: String::from(text), node: node.id }); + self.send_op(ParseOperation::CreateComment { + text: String::from(text), + node: node.id, + }); node } @@ -621,7 +740,7 @@ impl TreeSink for Sink { self.send_op(ParseOperation::CreatePI { node: node.id, target: String::from(target), - data: String::from(data) + data: String::from(data), }); node } @@ -641,14 +760,19 @@ impl TreeSink for Sink { }); } - fn append_before_sibling(&mut self, - sibling: &Self::Handle, - new_node: HtmlNodeOrText<Self::Handle>) { + fn append_before_sibling( + &mut self, + sibling: &Self::Handle, + new_node: HtmlNodeOrText<Self::Handle>, + ) { let new_node = match new_node { HtmlNodeOrText::AppendNode(node) => NodeOrText::Node(node), - HtmlNodeOrText::AppendText(text) => NodeOrText::Text(String::from(text)) + HtmlNodeOrText::AppendText(text) => NodeOrText::Text(String::from(text)), }; - self.send_op(ParseOperation::AppendBeforeSibling { sibling: sibling.id, node: new_node }); + self.send_op(ParseOperation::AppendBeforeSibling { + sibling: sibling.id, + node: new_node, + }); } fn append_based_on_parent_node( @@ -659,12 +783,12 @@ impl TreeSink for Sink { ) { let child = match child { HtmlNodeOrText::AppendNode(node) => NodeOrText::Node(node), - HtmlNodeOrText::AppendText(text) => NodeOrText::Text(String::from(text)) + HtmlNodeOrText::AppendText(text) => NodeOrText::Text(String::from(text)), }; self.send_op(ParseOperation::AppendBasedOnParentNode { element: elem.id, prev_element: prev_elem.id, - node: child + node: child, }); } @@ -684,24 +808,38 @@ impl TreeSink for Sink { fn append(&mut self, parent: &Self::Handle, child: HtmlNodeOrText<Self::Handle>) { let child = match child { HtmlNodeOrText::AppendNode(node) => NodeOrText::Node(node), - HtmlNodeOrText::AppendText(text) => NodeOrText::Text(String::from(text)) + HtmlNodeOrText::AppendText(text) => NodeOrText::Text(String::from(text)), }; - self.send_op(ParseOperation::Append { parent: parent.id, node: child }); + self.send_op(ParseOperation::Append { + parent: parent.id, + node: child, + }); } - fn append_doctype_to_document(&mut self, name: StrTendril, public_id: StrTendril, - system_id: StrTendril) { + fn append_doctype_to_document( + &mut self, + name: StrTendril, + public_id: StrTendril, + system_id: StrTendril, + ) { self.send_op(ParseOperation::AppendDoctypeToDocument { name: String::from(name), public_id: String::from(public_id), - system_id: String::from(system_id) + system_id: String::from(system_id), }); } fn add_attrs_if_missing(&mut self, target: &Self::Handle, html_attrs: Vec<HtmlAttribute>) { - let attrs = html_attrs.into_iter() - .map(|attr| Attribute { name: attr.name, value: String::from(attr.value) }).collect(); - self.send_op(ParseOperation::AddAttrsIfMissing { target: target.id, attrs }); + let attrs = html_attrs + .into_iter() + .map(|attr| Attribute { + name: attr.name, + value: String::from(attr.value), + }).collect(); + self.send_op(ParseOperation::AddAttrsIfMissing { + target: target.id, + attrs, + }); } fn remove_from_parent(&mut self, target: &Self::Handle) { @@ -717,7 +855,10 @@ impl TreeSink for Sink { } fn reparent_children(&mut self, parent: &Self::Handle, new_parent: &Self::Handle) { - self.send_op(ParseOperation::ReparentChildren { parent: parent.id, new_parent: new_parent.id }); + self.send_op(ParseOperation::ReparentChildren { + parent: parent.id, + new_parent: new_parent.id, + }); } /// <https://html.spec.whatwg.org/multipage/#html-integration-point> diff --git a/components/script/dom/servoparser/html.rs b/components/script/dom/servoparser/html.rs index 78ea868cac1..59fcd01fd6a 100644 --- a/components/script/dom/servoparser/html.rs +++ b/components/script/dom/servoparser/html.rs @@ -37,11 +37,11 @@ pub struct Tokenizer { impl Tokenizer { pub fn new( - document: &Document, - url: ServoUrl, - fragment_context: Option<super::FragmentContext>, - parsing_algorithm: ParsingAlgorithm) - -> Self { + document: &Document, + url: ServoUrl, + fragment_context: Option<super::FragmentContext>, + parsing_algorithm: ParsingAlgorithm, + ) -> Self { let sink = Sink { base_url: url, document: Dom::from_ref(document), @@ -52,7 +52,7 @@ impl Tokenizer { let options = TreeBuilderOpts { ignore_missing_rules: true, - .. Default::default() + ..Default::default() }; let inner = if let Some(fc) = fragment_context { @@ -60,11 +60,12 @@ impl Tokenizer { sink, Dom::from_ref(fc.context_elem), fc.form_elem.map(|n| Dom::from_ref(n)), - options); + options, + ); let tok_options = TokenizerOpts { initial_state: Some(tb.tokenizer_state_for_context_elem()), - .. Default::default() + ..Default::default() }; HtmlTokenizer::new(tb, tok_options) @@ -72,9 +73,7 @@ impl Tokenizer { HtmlTokenizer::new(TreeBuilder::new(sink, options), Default::default()) }; - Tokenizer { - inner: inner, - } + Tokenizer { inner: inner } } pub fn feed(&mut self, input: &mut BufferQueue) -> Result<(), DomRoot<HTMLScriptElement>> { @@ -107,7 +106,9 @@ unsafe impl JSTraceable for HtmlTokenizer<TreeBuilder<Dom<Node>, Sink>> { type Handle = Dom<Node>; #[allow(unrooted_must_root)] fn trace_handle(&self, node: &Dom<Node>) { - unsafe { node.trace(self.0); } + unsafe { + node.trace(self.0); + } } } @@ -118,14 +119,15 @@ unsafe impl JSTraceable for HtmlTokenizer<TreeBuilder<Dom<Node>, Sink>> { } fn start_element<S: Serializer>(node: &Element, serializer: &mut S) -> io::Result<()> { - let name = QualName::new(None, node.namespace().clone(), - node.local_name().clone()); - let attrs = node.attrs().iter().map(|attr| { - let qname = QualName::new(None, attr.namespace().clone(), - attr.local_name().clone()); - let value = attr.value().clone(); - (qname, value) - }).collect::<Vec<_>>(); + let name = QualName::new(None, node.namespace().clone(), node.local_name().clone()); + let attrs = node + .attrs() + .iter() + .map(|attr| { + let qname = QualName::new(None, attr.namespace().clone(), attr.local_name().clone()); + let value = attr.value().clone(); + (qname, value) + }).collect::<Vec<_>>(); let attr_refs = attrs.iter().map(|&(ref qname, ref value)| { let ar: AttrRef = (&qname, &**value); ar @@ -135,12 +137,10 @@ fn start_element<S: Serializer>(node: &Element, serializer: &mut S) -> io::Resul } fn end_element<S: Serializer>(node: &Element, serializer: &mut S) -> io::Result<()> { - let name = QualName::new(None, node.namespace().clone(), - node.local_name().clone()); + let name = QualName::new(None, node.namespace().clone(), node.local_name().clone()); serializer.end_elem(name) } - enum SerializationCommand { OpenElement(DomRoot<Element>), CloseElement(DomRoot<Element>), @@ -151,7 +151,7 @@ struct SerializationIterator { stack: Vec<SerializationCommand>, } -fn rev_children_iter(n: &Node) -> impl Iterator<Item=DomRoot<Node>>{ +fn rev_children_iter(n: &Node) -> impl Iterator<Item = DomRoot<Node>> { match n.downcast::<HTMLTemplateElement>() { Some(t) => t.Content().upcast::<Node>().rev_children(), None => n.rev_children(), @@ -160,9 +160,7 @@ fn rev_children_iter(n: &Node) -> impl Iterator<Item=DomRoot<Node>>{ impl SerializationIterator { fn new(node: &Node, skip_first: bool) -> SerializationIterator { - let mut ret = SerializationIterator { - stack: vec![], - }; + let mut ret = SerializationIterator { stack: vec![] }; if skip_first { for c in rev_children_iter(node) { ret.push_node(&*c); @@ -175,8 +173,12 @@ impl SerializationIterator { fn push_node(&mut self, n: &Node) { match n.downcast::<Element>() { - Some(e) => self.stack.push(SerializationCommand::OpenElement(DomRoot::from_ref(e))), - None => self.stack.push(SerializationCommand::SerializeNonelement(DomRoot::from_ref(n))), + Some(e) => self + .stack + .push(SerializationCommand::OpenElement(DomRoot::from_ref(e))), + None => self.stack.push(SerializationCommand::SerializeNonelement( + DomRoot::from_ref(n), + )), } } } @@ -188,7 +190,8 @@ impl Iterator for SerializationIterator { let res = self.stack.pop(); if let Some(SerializationCommand::OpenElement(ref e)) = res { - self.stack.push(SerializationCommand::CloseElement(e.clone())); + self.stack + .push(SerializationCommand::CloseElement(e.clone())); for c in rev_children_iter(&*e.upcast::<Node>()) { self.push_node(&c); } @@ -199,52 +202,52 @@ impl Iterator for SerializationIterator { } impl<'a> Serialize for &'a Node { - fn serialize<S: Serializer>(&self, serializer: &mut S, - traversal_scope: TraversalScope) -> io::Result<()> { + fn serialize<S: Serializer>( + &self, + serializer: &mut S, + traversal_scope: TraversalScope, + ) -> io::Result<()> { let node = *self; - let iter = SerializationIterator::new(node, traversal_scope != IncludeNode); for cmd in iter { match cmd { SerializationCommand::OpenElement(n) => { start_element(&n, serializer)?; - } + }, SerializationCommand::CloseElement(n) => { end_element(&&n, serializer)?; - } - - SerializationCommand::SerializeNonelement(n) => { - match n.type_id() { - NodeTypeId::DocumentType => { - let doctype = n.downcast::<DocumentType>().unwrap(); - serializer.write_doctype(&doctype.name())?; - }, - - NodeTypeId::CharacterData(CharacterDataTypeId::Text) => { - let cdata = n.downcast::<CharacterData>().unwrap(); - serializer.write_text(&cdata.data())?; - }, - - NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => { - let cdata = n.downcast::<CharacterData>().unwrap(); - serializer.write_comment(&cdata.data())?; - }, - - NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => { - let pi = n.downcast::<ProcessingInstruction>().unwrap(); - let data = pi.upcast::<CharacterData>().data(); - serializer.write_processing_instruction(&pi.target(), &data)?; - }, - - NodeTypeId::DocumentFragment => {} - - NodeTypeId::Document(_) => panic!("Can't serialize Document node itself"), - NodeTypeId::Element(_) => panic!("Element shouldn't appear here"), - } - } + }, + + SerializationCommand::SerializeNonelement(n) => match n.type_id() { + NodeTypeId::DocumentType => { + let doctype = n.downcast::<DocumentType>().unwrap(); + serializer.write_doctype(&doctype.name())?; + }, + + NodeTypeId::CharacterData(CharacterDataTypeId::Text) => { + let cdata = n.downcast::<CharacterData>().unwrap(); + serializer.write_text(&cdata.data())?; + }, + + NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => { + let cdata = n.downcast::<CharacterData>().unwrap(); + serializer.write_comment(&cdata.data())?; + }, + + NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => { + let pi = n.downcast::<ProcessingInstruction>().unwrap(); + let data = pi.upcast::<CharacterData>().data(); + serializer.write_processing_instruction(&pi.target(), &data)?; + }, + + NodeTypeId::DocumentFragment => {}, + + NodeTypeId::Document(_) => panic!("Can't serialize Document node itself"), + NodeTypeId::Element(_) => panic!("Element shouldn't appear here"), + }, } } diff --git a/components/script/dom/servoparser/mod.rs b/components/script/dom/servoparser/mod.rs index cc1da9b6c77..e64580f68c1 100644 --- a/components/script/dom/servoparser/mod.rs +++ b/components/script/dom/servoparser/mod.rs @@ -104,7 +104,7 @@ enum LastChunkState { pub struct ElementAttribute { name: QualName, - value: DOMString + value: DOMString, } #[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)] @@ -117,7 +117,7 @@ impl ElementAttribute { pub fn new(name: QualName, value: DOMString) -> ElementAttribute { ElementAttribute { name: name, - value: value + value: value, } } } @@ -128,49 +128,70 @@ impl ServoParser { } pub fn parse_html_document(document: &Document, input: DOMString, url: ServoUrl) { - let parser = if PREFS.get("dom.servoparser.async_html_tokenizer.enabled").as_boolean().unwrap() { - ServoParser::new(document, - Tokenizer::AsyncHtml(self::async_html::Tokenizer::new(document, url, None)), - LastChunkState::NotReceived, - ParserKind::Normal) + let parser = if PREFS + .get("dom.servoparser.async_html_tokenizer.enabled") + .as_boolean() + .unwrap() + { + ServoParser::new( + document, + Tokenizer::AsyncHtml(self::async_html::Tokenizer::new(document, url, None)), + LastChunkState::NotReceived, + ParserKind::Normal, + ) } else { - ServoParser::new(document, - Tokenizer::Html(self::html::Tokenizer::new(document, url, None, ParsingAlgorithm::Normal)), - LastChunkState::NotReceived, - ParserKind::Normal) + ServoParser::new( + document, + Tokenizer::Html(self::html::Tokenizer::new( + document, + url, + None, + ParsingAlgorithm::Normal, + )), + LastChunkState::NotReceived, + ParserKind::Normal, + ) }; parser.parse_string_chunk(String::from(input)); } // https://html.spec.whatwg.org/multipage/#parsing-html-fragments - pub fn parse_html_fragment(context: &Element, input: DOMString) -> impl Iterator<Item=DomRoot<Node>> { + pub fn parse_html_fragment( + context: &Element, + input: DOMString, + ) -> impl Iterator<Item = DomRoot<Node>> { let context_node = context.upcast::<Node>(); let context_document = context_node.owner_doc(); let window = context_document.window(); let url = context_document.url(); // Step 1. - let loader = DocumentLoader::new_with_threads(context_document.loader().resource_threads().clone(), - Some(url.clone())); - let document = Document::new(window, - HasBrowsingContext::No, - Some(url.clone()), - context_document.origin().clone(), - IsHTMLDocument::HTMLDocument, - None, - None, - DocumentActivity::Inactive, - DocumentSource::FromParser, - loader, - None, - None, - Default::default()); + let loader = DocumentLoader::new_with_threads( + context_document.loader().resource_threads().clone(), + Some(url.clone()), + ); + let document = Document::new( + window, + HasBrowsingContext::No, + Some(url.clone()), + context_document.origin().clone(), + IsHTMLDocument::HTMLDocument, + None, + None, + DocumentActivity::Inactive, + DocumentSource::FromParser, + loader, + None, + None, + Default::default(), + ); // Step 2. document.set_quirks_mode(context_document.quirks_mode()); // Step 11. - let form = context_node.inclusive_ancestors() + let form = context_node + .inclusive_ancestors() .find(|element| element.is::<HTMLFormElement>()); let fragment_context = FragmentContext { @@ -178,13 +199,17 @@ impl ServoParser { form_elem: form.r(), }; - let parser = ServoParser::new(&document, - Tokenizer::Html(self::html::Tokenizer::new(&document, - url, - Some(fragment_context), - ParsingAlgorithm::Fragment)), - LastChunkState::Received, - ParserKind::Normal); + let parser = ServoParser::new( + &document, + Tokenizer::Html(self::html::Tokenizer::new( + &document, + url, + Some(fragment_context), + ParsingAlgorithm::Fragment, + )), + LastChunkState::Received, + ParserKind::Normal, + ); parser.parse_string_chunk(String::from(input)); // Step 14. @@ -214,10 +239,12 @@ impl ServoParser { } pub fn parse_xml_document(document: &Document, input: DOMString, url: ServoUrl) { - let parser = ServoParser::new(document, - Tokenizer::Xml(self::xml::Tokenizer::new(document, url)), - LastChunkState::NotReceived, - ParserKind::Normal); + let parser = ServoParser::new( + document, + Tokenizer::Xml(self::xml::Tokenizer::new(document, url)), + LastChunkState::NotReceived, + ParserKind::Normal, + ); parser.parse_string_chunk(String::from(input)); } @@ -243,12 +270,18 @@ impl ServoParser { /// ^ /// insertion point /// ``` - pub fn resume_with_pending_parsing_blocking_script(&self, script: &HTMLScriptElement, result: ScriptResult) { + pub fn resume_with_pending_parsing_blocking_script( + &self, + script: &HTMLScriptElement, + result: ScriptResult, + ) { assert!(self.suspended.get()); self.suspended.set(false); - mem::swap(&mut *self.script_input.borrow_mut(), - &mut *self.network_input.borrow_mut()); + mem::swap( + &mut *self.script_input.borrow_mut(), + &mut *self.network_input.borrow_mut(), + ); while let Some(chunk) = self.script_input.borrow_mut().pop_front() { self.network_input.borrow_mut().push_back(chunk); } @@ -278,7 +311,9 @@ impl ServoParser { // parser is suspended, we just append everything to the // script input and abort these steps. for chunk in text { - self.script_input.borrow_mut().push_back(String::from(chunk).into()); + self.script_input + .borrow_mut() + .push_back(String::from(chunk).into()); } return; } @@ -334,14 +369,16 @@ impl ServoParser { *self.network_input.borrow_mut() = BufferQueue::new(); // Step 2. - self.document.set_ready_state(DocumentReadyState::Interactive); + self.document + .set_ready_state(DocumentReadyState::Interactive); // Step 3. self.tokenizer.borrow_mut().end(); self.document.set_current_parser(None); // Step 4. - self.document.set_ready_state(DocumentReadyState::Interactive); + self.document + .set_ready_state(DocumentReadyState::Interactive); } // https://html.spec.whatwg.org/multipage/#active-parser @@ -350,11 +387,12 @@ impl ServoParser { } #[allow(unrooted_must_root)] - fn new_inherited(document: &Document, - tokenizer: Tokenizer, - last_chunk_state: LastChunkState, - kind: ParserKind) - -> Self { + fn new_inherited( + document: &Document, + tokenizer: Tokenizer, + last_chunk_state: LastChunkState, + kind: ParserKind, + ) -> Self { ServoParser { reflector: Reflector::new(), document: Dom::from_ref(document), @@ -371,14 +409,22 @@ impl ServoParser { } #[allow(unrooted_must_root)] - fn new(document: &Document, - tokenizer: Tokenizer, - last_chunk_state: LastChunkState, - kind: ParserKind) - -> DomRoot<Self> { - reflect_dom_object(Box::new(ServoParser::new_inherited(document, tokenizer, last_chunk_state, kind)), - document.window(), - ServoParserBinding::Wrap) + fn new( + document: &Document, + tokenizer: Tokenizer, + last_chunk_state: LastChunkState, + kind: ParserKind, + ) -> DomRoot<Self> { + reflect_dom_object( + Box::new(ServoParser::new_inherited( + document, + tokenizer, + last_chunk_state, + kind, + )), + document.window(), + ServoParserBinding::Wrap, + ) } fn push_bytes_input_chunk(&self, chunk: Vec<u8>) { @@ -391,11 +437,9 @@ impl ServoParser { match result { Err(()) => { *incomplete_utf8 = Some(incomplete); - return - } - Ok(remaining) => { - chunk = remaining - } + return; + }, + Ok(remaining) => chunk = remaining, } } @@ -413,10 +457,16 @@ impl ServoParser { incremental: TimerMetadataReflowType::FirstReflow, }; let profiler_category = self.tokenizer.borrow().profiler_category(); - profile(profiler_category, - Some(metadata), - self.document.window().upcast::<GlobalScope>().time_profiler_chan().clone(), - || self.do_parse_sync()) + profile( + profiler_category, + Some(metadata), + self.document + .window() + .upcast::<GlobalScope>() + .time_profiler_chan() + .clone(), + || self.do_parse_sync(), + ) } fn do_parse_sync(&self) { @@ -427,7 +477,9 @@ impl ServoParser { if self.last_chunk_received.get() { if let Some(_) = self.incomplete_utf8.borrow_mut().take() { - self.network_input.borrow_mut().push_back(StrTendril::from("\u{FFFD}")) + self.network_input + .borrow_mut() + .push_back(StrTendril::from("\u{FFFD}")) } } self.tokenize(|tokenizer| tokenizer.feed(&mut *self.network_input.borrow_mut())); @@ -460,7 +512,8 @@ impl ServoParser { } fn tokenize<F>(&self, mut feed: F) - where F: FnMut(&mut Tokenizer) -> Result<(), DomRoot<HTMLScriptElement>>, + where + F: FnMut(&mut Tokenizer) -> Result<(), DomRoot<HTMLScriptElement>>, { loop { assert!(!self.suspended.get()); @@ -497,7 +550,8 @@ impl ServoParser { assert!(self.incomplete_utf8.borrow().is_none()); // Step 1. - self.document.set_ready_state(DocumentReadyState::Interactive); + self.document + .set_ready_state(DocumentReadyState::Interactive); // Step 2. self.tokenizer.borrow_mut().end(); @@ -510,13 +564,15 @@ impl ServoParser { } struct FragmentParsingResult<I> - where I: Iterator<Item=DomRoot<Node>> +where + I: Iterator<Item = DomRoot<Node>>, { inner: I, } impl<I> Iterator for FragmentParsingResult<I> - where I: Iterator<Item=DomRoot<Node>> +where + I: Iterator<Item = DomRoot<Node>>, { type Item = DomRoot<Node>; @@ -621,12 +677,10 @@ impl FetchResponseListener for ParserContext { let mut ssl_error = None; let mut network_error = None; let metadata = match meta_result { - Ok(meta) => { - Some(match meta { - FetchMetadata::Unfiltered(m) => m, - FetchMetadata::Filtered { unsafe_, .. } => unsafe_, - }) - }, + Ok(meta) => Some(match meta { + FetchMetadata::Unfiltered(m) => m, + FetchMetadata::Filtered { unsafe_, .. } => unsafe_, + }), Err(NetworkError::SslValidation(url, reason)) => { ssl_error = Some(reason); let mut meta = Metadata::default(url); @@ -643,7 +697,10 @@ impl FetchResponseListener for ParserContext { }, Err(_) => None, }; - let content_type = metadata.clone().and_then(|meta| meta.content_type).map(Serde::into_inner); + let content_type = metadata + .clone() + .and_then(|meta| meta.content_type) + .map(Serde::into_inner); let parser = match ScriptThread::page_headers_available(&self.id, metadata) { Some(parser) => parser, None => return, @@ -795,14 +852,16 @@ impl Sink { } fn has_parent_node(&self, node: &Dom<Node>) -> bool { - node.GetParentNode().is_some() + node.GetParentNode().is_some() } } -#[allow(unrooted_must_root)] // FIXME: really? +#[allow(unrooted_must_root)] // FIXME: really? impl TreeSink for Sink { type Output = Self; - fn finish(self) -> Self { self } + fn finish(self) -> Self { + self + } type Handle = Dom<Node>; @@ -811,7 +870,8 @@ impl TreeSink for Sink { } fn get_template_contents(&mut self, target: &Dom<Node>) -> Dom<Node> { - let template = target.downcast::<HTMLTemplateElement>() + let template = target + .downcast::<HTMLTemplateElement>() .expect("tried to get template contents of non-HTMLTemplateElement in HTML parsing"); Dom::from_ref(template.Content().upcast()) } @@ -821,7 +881,8 @@ impl TreeSink for Sink { } fn elem_name<'a>(&self, target: &'a Dom<Node>) -> ExpandedName<'a> { - let elem = target.downcast::<Element>() + let elem = target + .downcast::<Element>() .expect("tried to get name of non-Element in HTML parsing"); ExpandedName { ns: elem.namespace(), @@ -829,8 +890,12 @@ impl TreeSink for Sink { } } - fn create_element(&mut self, name: QualName, attrs: Vec<Attribute>, _flags: ElementFlags) - -> Dom<Node> { + fn create_element( + &mut self, + name: QualName, + attrs: Vec<Attribute>, + _flags: ElementFlags, + ) -> Dom<Node> { let attrs = attrs .into_iter() .map(|attr| ElementAttribute::new(attr.name, DOMString::from(String::from(attr.value)))) @@ -853,15 +918,26 @@ impl TreeSink for Sink { fn create_pi(&mut self, target: StrTendril, data: StrTendril) -> Dom<Node> { let doc = &*self.document; let pi = ProcessingInstruction::new( - DOMString::from(String::from(target)), DOMString::from(String::from(data)), - doc); + DOMString::from(String::from(target)), + DOMString::from(String::from(data)), + doc, + ); Dom::from_ref(pi.upcast()) } - fn associate_with_form(&mut self, target: &Dom<Node>, form: &Dom<Node>, nodes: (&Dom<Node>, Option<&Dom<Node>>)) { + fn associate_with_form( + &mut self, + target: &Dom<Node>, + form: &Dom<Node>, + nodes: (&Dom<Node>, Option<&Dom<Node>>), + ) { let (element, prev_element) = nodes; let tree_node = prev_element.map_or(element, |prev| { - if self.has_parent_node(element) { element } else { prev } + if self.has_parent_node(element) { + element + } else { + prev + } }); if !self.same_tree(tree_node, form) { return; @@ -878,14 +954,17 @@ impl TreeSink for Sink { control.set_form_owner_from_parser(&form); } else { // TODO remove this code when keygen is implemented. - assert_eq!(node.NodeName(), "KEYGEN", "Unknown form-associatable element"); + assert_eq!( + node.NodeName(), + "KEYGEN", + "Unknown form-associatable element" + ); } } - fn append_before_sibling(&mut self, - sibling: &Dom<Node>, - new_node: NodeOrText<Dom<Node>>) { - let parent = sibling.GetParentNode() + fn append_before_sibling(&mut self, sibling: &Dom<Node>, new_node: NodeOrText<Dom<Node>>) { + let parent = sibling + .GetParentNode() .expect("append_before_sibling called on node without parent"); insert(&parent, Some(&*sibling), new_node); @@ -921,20 +1000,34 @@ impl TreeSink for Sink { } } - fn append_doctype_to_document(&mut self, name: StrTendril, public_id: StrTendril, - system_id: StrTendril) { + fn append_doctype_to_document( + &mut self, + name: StrTendril, + public_id: StrTendril, + system_id: StrTendril, + ) { let doc = &*self.document; let doctype = DocumentType::new( - DOMString::from(String::from(name)), Some(DOMString::from(String::from(public_id))), - Some(DOMString::from(String::from(system_id))), doc); - doc.upcast::<Node>().AppendChild(doctype.upcast()).expect("Appending failed"); + DOMString::from(String::from(name)), + Some(DOMString::from(String::from(public_id))), + Some(DOMString::from(String::from(system_id))), + doc, + ); + doc.upcast::<Node>() + .AppendChild(doctype.upcast()) + .expect("Appending failed"); } fn add_attrs_if_missing(&mut self, target: &Dom<Node>, attrs: Vec<Attribute>) { - let elem = target.downcast::<Element>() + let elem = target + .downcast::<Element>() .expect("tried to set attrs on non-Element in HTML parsing"); for attr in attrs { - elem.set_attribute_from_parser(attr.name, DOMString::from(String::from(attr.value)), None); + elem.set_attribute_from_parser( + attr.name, + DOMString::from(String::from(attr.value)), + None, + ); } } @@ -968,10 +1061,11 @@ impl TreeSink for Sink { /// Specifically, the <annotation-xml> cases. fn is_mathml_annotation_xml_integration_point(&self, handle: &Dom<Node>) -> bool { let elem = handle.downcast::<Element>().unwrap(); - elem.get_attribute(&ns!(), &local_name!("encoding")).map_or(false, |attr| { - attr.value().eq_ignore_ascii_case("text/html") - || attr.value().eq_ignore_ascii_case("application/xhtml+xml") - }) + elem.get_attribute(&ns!(), &local_name!("encoding")) + .map_or(false, |attr| { + attr.value().eq_ignore_ascii_case("text/html") || + attr.value().eq_ignore_ascii_case("application/xhtml+xml") + }) } fn set_current_line(&mut self, line_number: u64) { @@ -993,7 +1087,8 @@ fn create_element_for_token( parsing_algorithm: ParsingAlgorithm, ) -> DomRoot<Element> { // Step 3. - let is = attrs.iter() + let is = attrs + .iter() .find(|attr| attr.name.local.eq_str_ignore_ascii_case("is")) .map(|attr| LocalName::from(&*attr.value)); @@ -1001,7 +1096,8 @@ fn create_element_for_token( let definition = document.lookup_custom_element_definition(&name.ns, &name.local, is.as_ref()); // Step 5. - let will_execute_script = definition.is_some() && parsing_algorithm != ParsingAlgorithm::Fragment; + let will_execute_script = + definition.is_some() && parsing_algorithm != ParsingAlgorithm::Fragment; // Step 6. if will_execute_script { @@ -1009,7 +1105,10 @@ fn create_element_for_token( document.increment_throw_on_dynamic_markup_insertion_counter(); // Step 6.2 if is_execution_stack_empty() { - document.window().upcast::<GlobalScope>().perform_a_microtask_checkpoint(); + document + .window() + .upcast::<GlobalScope>() + .perform_a_microtask_checkpoint(); } // Step 6.3 ScriptThread::push_new_element_queue() diff --git a/components/script/dom/servoparser/xml.rs b/components/script/dom/servoparser/xml.rs index 62ebe351a23..defac0eab44 100644 --- a/components/script/dom/servoparser/xml.rs +++ b/components/script/dom/servoparser/xml.rs @@ -36,9 +36,7 @@ impl Tokenizer { let tb = XmlTreeBuilder::new(sink, Default::default()); let tok = XmlTokenizer::new(tb, Default::default()); - Tokenizer { - inner: tok, - } + Tokenizer { inner: tok } } pub fn feed(&mut self, input: &mut BufferQueue) -> Result<(), DomRoot<HTMLScriptElement>> { @@ -77,7 +75,9 @@ unsafe impl JSTraceable for XmlTokenizer<XmlTreeBuilder<Dom<Node>, Sink>> { type Handle = Dom<Node>; #[allow(unrooted_must_root)] fn trace_handle(&self, node: &Dom<Node>) { - unsafe { node.trace(self.0); } + unsafe { + node.trace(self.0); + } } } diff --git a/components/script/dom/storage.rs b/components/script/dom/storage.rs index b2c3783c010..31d0dd5f84f 100644 --- a/components/script/dom/storage.rs +++ b/components/script/dom/storage.rs @@ -25,19 +25,23 @@ use task_source::TaskSource; #[dom_struct] pub struct Storage { reflector_: Reflector, - storage_type: StorageType + storage_type: StorageType, } impl Storage { fn new_inherited(storage_type: StorageType) -> Storage { Storage { reflector_: Reflector::new(), - storage_type: storage_type + storage_type: storage_type, } } pub fn new(global: &Window, storage_type: StorageType) -> DomRoot<Storage> { - reflect_dom_object(Box::new(Storage::new_inherited(storage_type)), global, StorageBinding::Wrap) + reflect_dom_object( + Box::new(Storage::new_inherited(storage_type)), + global, + StorageBinding::Wrap, + ) } fn get_url(&self) -> ServoUrl { @@ -47,7 +51,6 @@ impl Storage { fn get_storage_thread(&self) -> IpcSender<StorageThreadMsg> { self.global().resource_threads().sender() } - } impl StorageMethods for Storage { @@ -55,7 +58,12 @@ impl StorageMethods for Storage { fn Length(&self) -> u32 { let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); - self.get_storage_thread().send(StorageThreadMsg::Length(sender, self.get_url(), self.storage_type)).unwrap(); + self.get_storage_thread() + .send(StorageThreadMsg::Length( + sender, + self.get_url(), + self.storage_type, + )).unwrap(); receiver.recv().unwrap() as u32 } @@ -64,8 +72,12 @@ impl StorageMethods for Storage { let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); self.get_storage_thread() - .send(StorageThreadMsg::Key(sender, self.get_url(), self.storage_type, index)) - .unwrap(); + .send(StorageThreadMsg::Key( + sender, + self.get_url(), + self.storage_type, + index, + )).unwrap(); receiver.recv().unwrap().map(DOMString::from) } @@ -85,16 +97,22 @@ impl StorageMethods for Storage { let name = String::from(name); let value = String::from(value); - let msg = StorageThreadMsg::SetItem(sender, self.get_url(), self.storage_type, name.clone(), value.clone()); + let msg = StorageThreadMsg::SetItem( + sender, + self.get_url(), + self.storage_type, + name.clone(), + value.clone(), + ); self.get_storage_thread().send(msg).unwrap(); match receiver.recv().unwrap() { Err(_) => Err(Error::QuotaExceeded), Ok((changed, old_value)) => { - if changed { - self.broadcast_change_notification(Some(name), old_value, Some(value)); - } - Ok(()) - } + if changed { + self.broadcast_change_notification(Some(name), old_value, Some(value)); + } + Ok(()) + }, } } @@ -103,7 +121,8 @@ impl StorageMethods for Storage { let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); let name = String::from(name); - let msg = StorageThreadMsg::RemoveItem(sender, self.get_url(), self.storage_type, name.clone()); + let msg = + StorageThreadMsg::RemoveItem(sender, self.get_url(), self.storage_type, name.clone()); self.get_storage_thread().send(msg).unwrap(); if let Some(old_value) = receiver.recv().unwrap() { self.broadcast_change_notification(Some(name), Some(old_value), None); @@ -114,7 +133,12 @@ impl StorageMethods for Storage { fn Clear(&self) { let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); - self.get_storage_thread().send(StorageThreadMsg::Clear(sender, self.get_url(), self.storage_type)).unwrap(); + self.get_storage_thread() + .send(StorageThreadMsg::Clear( + sender, + self.get_url(), + self.storage_type, + )).unwrap(); if receiver.recv().unwrap() { self.broadcast_change_notification(None, None, None); } @@ -124,12 +148,18 @@ impl StorageMethods for Storage { fn SupportedPropertyNames(&self) -> Vec<DOMString> { let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); - self.get_storage_thread().send(StorageThreadMsg::Keys(sender, self.get_url(), self.storage_type)).unwrap(); - receiver.recv() - .unwrap() - .into_iter() - .map(DOMString::from) - .collect() + self.get_storage_thread() + .send(StorageThreadMsg::Keys( + sender, + self.get_url(), + self.storage_type, + )).unwrap(); + receiver + .recv() + .unwrap() + .into_iter() + .map(DOMString::from) + .collect() } // check-tidy: no specs after this line @@ -146,15 +176,21 @@ impl StorageMethods for Storage { } } - impl Storage { /// <https://html.spec.whatwg.org/multipage/#send-a-storage-notification> - fn broadcast_change_notification(&self, key: Option<String>, old_value: Option<String>, - new_value: Option<String>) { + fn broadcast_change_notification( + &self, + key: Option<String>, + old_value: Option<String>, + new_value: Option<String>, + ) { let storage = self.storage_type; let url = self.get_url(); let msg = ScriptMsg::BroadcastStorageEvent(storage, url, key, old_value, new_value); - self.global().script_to_constellation_chan().send(msg).unwrap(); + self.global() + .script_to_constellation_chan() + .send(msg) + .unwrap(); } /// <https://html.spec.whatwg.org/multipage/#send-a-storage-notification> @@ -167,8 +203,11 @@ impl Storage { ) { let global = self.global(); let this = Trusted::new(self); - global.as_window().dom_manipulation_task_source().queue( - task!(send_storage_notification: move || { + global + .as_window() + .dom_manipulation_task_source() + .queue( + task!(send_storage_notification: move || { let this = this.root(); let global = this.global(); let event = StorageEvent::new( @@ -184,7 +223,7 @@ impl Storage { ); event.upcast::<Event>().fire(global.upcast()); }), - global.upcast(), - ).unwrap(); + global.upcast(), + ).unwrap(); } } diff --git a/components/script/dom/storageevent.rs b/components/script/dom/storageevent.rs index 0070a2c1e68..aee88e95c19 100644 --- a/components/script/dom/storageevent.rs +++ b/components/script/dom/storageevent.rs @@ -23,46 +23,56 @@ pub struct StorageEvent { old_value: Option<DOMString>, new_value: Option<DOMString>, url: DOMString, - storage_area: MutNullableDom<Storage> + storage_area: MutNullableDom<Storage>, } - impl StorageEvent { - pub fn new_inherited(key: Option<DOMString>, - old_value: Option<DOMString>, - new_value: Option<DOMString>, - url: DOMString, - storage_area: Option<&Storage>) -> StorageEvent { + pub fn new_inherited( + key: Option<DOMString>, + old_value: Option<DOMString>, + new_value: Option<DOMString>, + url: DOMString, + storage_area: Option<&Storage>, + ) -> StorageEvent { StorageEvent { event: Event::new_inherited(), key: key, old_value: old_value, new_value: new_value, url: url, - storage_area: MutNullableDom::new(storage_area) + storage_area: MutNullableDom::new(storage_area), } } - pub fn new_uninitialized(window: &Window, - url: DOMString) -> DomRoot<StorageEvent> { - reflect_dom_object(Box::new(StorageEvent::new_inherited(None, None, None, url, None)), - window, - StorageEventBinding::Wrap) + pub fn new_uninitialized(window: &Window, url: DOMString) -> DomRoot<StorageEvent> { + reflect_dom_object( + Box::new(StorageEvent::new_inherited(None, None, None, url, None)), + window, + StorageEventBinding::Wrap, + ) } - pub fn new(global: &Window, - type_: Atom, - bubbles: EventBubbles, - cancelable: EventCancelable, - key: Option<DOMString>, - oldValue: Option<DOMString>, - newValue: Option<DOMString>, - url: DOMString, - storageArea: Option<&Storage>) -> DomRoot<StorageEvent> { + pub fn new( + global: &Window, + type_: Atom, + bubbles: EventBubbles, + cancelable: EventCancelable, + key: Option<DOMString>, + oldValue: Option<DOMString>, + newValue: Option<DOMString>, + url: DOMString, + storageArea: Option<&Storage>, + ) -> DomRoot<StorageEvent> { let ev = reflect_dom_object( - Box::new(StorageEvent::new_inherited(key, oldValue, newValue, url, storageArea)), + Box::new(StorageEvent::new_inherited( + key, + oldValue, + newValue, + url, + storageArea, + )), global, - StorageEventBinding::Wrap + StorageEventBinding::Wrap, ); { let event = ev.upcast::<Event>(); @@ -71,9 +81,11 @@ impl StorageEvent { ev } - pub fn Constructor(global: &Window, - type_: DOMString, - init: &StorageEventBinding::StorageEventInit) -> Fallible<DomRoot<StorageEvent>> { + pub fn Constructor( + global: &Window, + type_: DOMString, + init: &StorageEventBinding::StorageEventInit, + ) -> Fallible<DomRoot<StorageEvent>> { let key = init.key.clone(); let oldValue = init.oldValue.clone(); let newValue = init.newValue.clone(); @@ -81,10 +93,17 @@ impl StorageEvent { let storageArea = init.storageArea.r(); let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::from(init.parent.cancelable); - let event = StorageEvent::new(global, Atom::from(type_), - bubbles, cancelable, - key, oldValue, newValue, - url, storageArea); + let event = StorageEvent::new( + global, + Atom::from(type_), + bubbles, + cancelable, + key, + oldValue, + newValue, + url, + storageArea, + ); Ok(event) } } diff --git a/components/script/dom/stylepropertymapreadonly.rs b/components/script/dom/stylepropertymapreadonly.rs index 5948adfeb8d..c76a053f407 100644 --- a/components/script/dom/stylepropertymapreadonly.rs +++ b/components/script/dom/stylepropertymapreadonly.rs @@ -24,8 +24,9 @@ pub struct StylePropertyMapReadOnly { } impl StylePropertyMapReadOnly { - fn new_inherited<Entries>(entries: Entries) -> StylePropertyMapReadOnly where - Entries: IntoIterator<Item=(Atom, Dom<CSSStyleValue>)> + fn new_inherited<Entries>(entries: Entries) -> StylePropertyMapReadOnly + where + Entries: IntoIterator<Item = (Atom, Dom<CSSStyleValue>)>, { StylePropertyMapReadOnly { reflector: Reflector::new(), @@ -33,8 +34,12 @@ impl StylePropertyMapReadOnly { } } - pub fn from_iter<Entries>(global: &GlobalScope, entries: Entries) -> DomRoot<StylePropertyMapReadOnly> where - Entries: IntoIterator<Item=(Atom, String)>, + pub fn from_iter<Entries>( + global: &GlobalScope, + entries: Entries, + ) -> DomRoot<StylePropertyMapReadOnly> + where + Entries: IntoIterator<Item = (Atom, String)>, { let mut keys = Vec::new(); rooted_vec!(let mut values); @@ -48,7 +53,11 @@ impl StylePropertyMapReadOnly { values.push(Dom::from_ref(&*value)); } let iter = keys.drain(..).zip(values.iter().cloned()); - reflect_dom_object(Box::new(StylePropertyMapReadOnly::new_inherited(iter)), global, Wrap) + reflect_dom_object( + Box::new(StylePropertyMapReadOnly::new_inherited(iter)), + global, + Wrap, + ) } } @@ -56,7 +65,9 @@ impl StylePropertyMapReadOnlyMethods for StylePropertyMapReadOnly { /// <https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymapreadonly-get> fn Get(&self, property: DOMString) -> Option<DomRoot<CSSStyleValue>> { // TODO: avoid constructing an Atom - self.entries.get(&Atom::from(property)).map(|value| DomRoot::from_ref(&**value)) + self.entries + .get(&Atom::from(property)) + .map(|value| DomRoot::from_ref(&**value)) } /// <https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymapreadonly-has> @@ -67,7 +78,9 @@ impl StylePropertyMapReadOnlyMethods for StylePropertyMapReadOnly { /// <https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymapreadonly-getproperties> fn GetProperties(&self) -> Vec<DOMString> { - let mut result: Vec<DOMString> = self.entries.keys() + let mut result: Vec<DOMString> = self + .entries + .keys() .map(|key| DOMString::from(&**key)) .collect(); // https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymap-getproperties diff --git a/components/script/dom/stylesheet.rs b/components/script/dom/stylesheet.rs index d53971cf927..94a26755699 100644 --- a/components/script/dom/stylesheet.rs +++ b/components/script/dom/stylesheet.rs @@ -22,9 +22,11 @@ pub struct StyleSheet { impl StyleSheet { #[allow(unrooted_must_root)] - pub fn new_inherited(type_: DOMString, - href: Option<DOMString>, - title: Option<DOMString>) -> StyleSheet { + pub fn new_inherited( + type_: DOMString, + href: Option<DOMString>, + title: Option<DOMString>, + ) -> StyleSheet { StyleSheet { reflector_: Reflector::new(), type_: type_, @@ -34,16 +36,20 @@ impl StyleSheet { } #[allow(unrooted_must_root)] - pub fn new(window: &Window, type_: DOMString, - href: Option<DOMString>, - title: Option<DOMString>) -> DomRoot<StyleSheet> { - reflect_dom_object(Box::new(StyleSheet::new_inherited(type_, href, title)), - window, - StyleSheetBinding::Wrap) + pub fn new( + window: &Window, + type_: DOMString, + href: Option<DOMString>, + title: Option<DOMString>, + ) -> DomRoot<StyleSheet> { + reflect_dom_object( + Box::new(StyleSheet::new_inherited(type_, href, title)), + window, + StyleSheetBinding::Wrap, + ) } } - impl StyleSheetMethods for StyleSheet { // https://drafts.csswg.org/cssom/#dom-stylesheet-type fn Type_(&self) -> DOMString { @@ -67,6 +73,8 @@ impl StyleSheetMethods for StyleSheet { // https://drafts.csswg.org/cssom/#dom-stylesheet-disabled fn SetDisabled(&self, disabled: bool) { - self.downcast::<CSSStyleSheet>().unwrap().set_disabled(disabled) + self.downcast::<CSSStyleSheet>() + .unwrap() + .set_disabled(disabled) } } diff --git a/components/script/dom/stylesheetlist.rs b/components/script/dom/stylesheetlist.rs index 6ae8f0bd769..e4c6b5f649b 100644 --- a/components/script/dom/stylesheetlist.rs +++ b/components/script/dom/stylesheetlist.rs @@ -22,28 +22,33 @@ impl StyleSheetList { fn new_inherited(doc: Dom<Document>) -> StyleSheetList { StyleSheetList { reflector_: Reflector::new(), - document: doc + document: doc, } } #[allow(unrooted_must_root)] pub fn new(window: &Window, document: Dom<Document>) -> DomRoot<StyleSheetList> { - reflect_dom_object(Box::new(StyleSheetList::new_inherited(document)), - window, StyleSheetListBinding::Wrap) + reflect_dom_object( + Box::new(StyleSheetList::new_inherited(document)), + window, + StyleSheetListBinding::Wrap, + ) } } impl StyleSheetListMethods for StyleSheetList { // https://drafts.csswg.org/cssom/#dom-stylesheetlist-length fn Length(&self) -> u32 { - self.document.stylesheet_count() as u32 + self.document.stylesheet_count() as u32 } // https://drafts.csswg.org/cssom/#dom-stylesheetlist-item fn Item(&self, index: u32) -> Option<DomRoot<StyleSheet>> { // XXXManishearth this doesn't handle the origin clean flag and is a // cors vulnerability - self.document.stylesheet_at(index as usize).map(DomRoot::upcast) + self.document + .stylesheet_at(index as usize) + .map(DomRoot::upcast) } // check-tidy: no specs after this line diff --git a/components/script/dom/svgelement.rs b/components/script/dom/svgelement.rs index 2be5b9613f2..bc554416090 100644 --- a/components/script/dom/svgelement.rs +++ b/components/script/dom/svgelement.rs @@ -16,12 +16,14 @@ pub struct SVGElement { } impl SVGElement { - pub fn new_inherited_with_state(state: ElementState, tag_name: LocalName, - prefix: Option<Prefix>, document: &Document) - -> SVGElement { + pub fn new_inherited_with_state( + state: ElementState, + tag_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> SVGElement { SVGElement { - element: - Element::new_inherited_with_state(state, tag_name, ns!(svg), prefix, document), + element: Element::new_inherited_with_state(state, tag_name, ns!(svg), prefix, document), } } } diff --git a/components/script/dom/svggraphicselement.rs b/components/script/dom/svggraphicselement.rs index 4e4f6fadf65..71b272b8737 100644 --- a/components/script/dom/svggraphicselement.rs +++ b/components/script/dom/svggraphicselement.rs @@ -16,17 +16,27 @@ pub struct SVGGraphicsElement { } impl SVGGraphicsElement { - pub fn new_inherited(tag_name: LocalName, prefix: Option<Prefix>, - document: &Document) -> SVGGraphicsElement { - SVGGraphicsElement::new_inherited_with_state(ElementState::empty(), tag_name, prefix, document) + pub fn new_inherited( + tag_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> SVGGraphicsElement { + SVGGraphicsElement::new_inherited_with_state( + ElementState::empty(), + tag_name, + prefix, + document, + ) } - pub fn new_inherited_with_state(state: ElementState, tag_name: LocalName, - prefix: Option<Prefix>, document: &Document) - -> SVGGraphicsElement { + pub fn new_inherited_with_state( + state: ElementState, + tag_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> SVGGraphicsElement { SVGGraphicsElement { - svgelement: - SVGElement::new_inherited_with_state(state, tag_name, prefix, document), + svgelement: SVGElement::new_inherited_with_state(state, tag_name, prefix, document), } } } diff --git a/components/script/dom/svgsvgelement.rs b/components/script/dom/svgsvgelement.rs index b057a3c4b31..4894edc1202 100644 --- a/components/script/dom/svgsvgelement.rs +++ b/components/script/dom/svgsvgelement.rs @@ -22,26 +22,31 @@ const DEFAULT_HEIGHT: u32 = 150; #[dom_struct] pub struct SVGSVGElement { - svggraphicselement: SVGGraphicsElement + svggraphicselement: SVGGraphicsElement, } impl SVGSVGElement { - fn new_inherited(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> SVGSVGElement { + fn new_inherited( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> SVGSVGElement { SVGSVGElement { - svggraphicselement: - SVGGraphicsElement::new_inherited(local_name, prefix, document) + svggraphicselement: SVGGraphicsElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] - pub fn new(local_name: LocalName, - prefix: Option<Prefix>, - document: &Document) -> DomRoot<SVGSVGElement> { - Node::reflect_node(Box::new(SVGSVGElement::new_inherited(local_name, prefix, document)), - document, - SVGSVGElementBinding::Wrap) + pub fn new( + local_name: LocalName, + prefix: Option<Prefix>, + document: &Document, + ) -> DomRoot<SVGSVGElement> { + Node::reflect_node( + Box::new(SVGSVGElement::new_inherited(local_name, prefix, document)), + document, + SVGSVGElementBinding::Wrap, + ) } } @@ -55,8 +60,12 @@ impl LayoutSVGSVGElementHelpers for LayoutDom<SVGSVGElement> { unsafe { let SVG = &*self.unsafe_get(); - let width_attr = SVG.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("width")); - let height_attr = SVG.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("height")); + let width_attr = SVG + .upcast::<Element>() + .get_attr_for_layout(&ns!(), &local_name!("width")); + let height_attr = SVG + .upcast::<Element>() + .get_attr_for_layout(&ns!(), &local_name!("height")); SVGSVGData { width: width_attr.map_or(DEFAULT_WIDTH, |val| val.as_uint()), height: height_attr.map_or(DEFAULT_HEIGHT, |val| val.as_uint()), @@ -78,7 +87,10 @@ impl VirtualMethods for SVGSVGElement { match name { &local_name!("width") => AttrValue::from_u32(value.into(), DEFAULT_WIDTH), &local_name!("height") => AttrValue::from_u32(value.into(), DEFAULT_HEIGHT), - _ => self.super_type().unwrap().parse_plain_attribute(name, value), + _ => self + .super_type() + .unwrap() + .parse_plain_attribute(name, value), } } } diff --git a/components/script/dom/testbinding.rs b/components/script/dom/testbinding.rs index 965589a2683..e6fbfa692c8 100644 --- a/components/script/dom/testbinding.rs +++ b/components/script/dom/testbinding.rs @@ -63,8 +63,11 @@ impl TestBinding { } pub fn new(global: &GlobalScope) -> DomRoot<TestBinding> { - reflect_dom_object(Box::new(TestBinding::new_inherited()), - global, TestBindingBinding::Wrap) + reflect_dom_object( + Box::new(TestBinding::new_inherited()), + global, + TestBindingBinding::Wrap, + ) } pub fn Constructor(global: &GlobalScope) -> Fallible<DomRoot<TestBinding>> { @@ -83,47 +86,89 @@ impl TestBinding { } impl TestBindingMethods for TestBinding { - fn BooleanAttribute(&self) -> bool { false } + fn BooleanAttribute(&self) -> bool { + false + } fn SetBooleanAttribute(&self, _: bool) {} - fn ByteAttribute(&self) -> i8 { 0 } + fn ByteAttribute(&self) -> i8 { + 0 + } fn SetByteAttribute(&self, _: i8) {} - fn OctetAttribute(&self) -> u8 { 0 } + fn OctetAttribute(&self) -> u8 { + 0 + } fn SetOctetAttribute(&self, _: u8) {} - fn ShortAttribute(&self) -> i16 { 0 } + fn ShortAttribute(&self) -> i16 { + 0 + } fn SetShortAttribute(&self, _: i16) {} - fn UnsignedShortAttribute(&self) -> u16 { 0 } + fn UnsignedShortAttribute(&self) -> u16 { + 0 + } fn SetUnsignedShortAttribute(&self, _: u16) {} - fn LongAttribute(&self) -> i32 { 0 } + fn LongAttribute(&self) -> i32 { + 0 + } fn SetLongAttribute(&self, _: i32) {} - fn UnsignedLongAttribute(&self) -> u32 { 0 } + fn UnsignedLongAttribute(&self) -> u32 { + 0 + } fn SetUnsignedLongAttribute(&self, _: u32) {} - fn LongLongAttribute(&self) -> i64 { 0 } + fn LongLongAttribute(&self) -> i64 { + 0 + } fn SetLongLongAttribute(&self, _: i64) {} - fn UnsignedLongLongAttribute(&self) -> u64 { 0 } + fn UnsignedLongLongAttribute(&self) -> u64 { + 0 + } fn SetUnsignedLongLongAttribute(&self, _: u64) {} - fn UnrestrictedFloatAttribute(&self) -> f32 { 0. } + fn UnrestrictedFloatAttribute(&self) -> f32 { + 0. + } fn SetUnrestrictedFloatAttribute(&self, _: f32) {} - fn FloatAttribute(&self) -> Finite<f32> { Finite::wrap(0.) } + fn FloatAttribute(&self) -> Finite<f32> { + Finite::wrap(0.) + } fn SetFloatAttribute(&self, _: Finite<f32>) {} - fn UnrestrictedDoubleAttribute(&self) -> f64 { 0. } + fn UnrestrictedDoubleAttribute(&self) -> f64 { + 0. + } fn SetUnrestrictedDoubleAttribute(&self, _: f64) {} - fn DoubleAttribute(&self) -> Finite<f64> { Finite::wrap(0.) } + fn DoubleAttribute(&self) -> Finite<f64> { + Finite::wrap(0.) + } fn SetDoubleAttribute(&self, _: Finite<f64>) {} - fn StringAttribute(&self) -> DOMString { DOMString::new() } + fn StringAttribute(&self) -> DOMString { + DOMString::new() + } fn SetStringAttribute(&self, _: DOMString) {} - fn UsvstringAttribute(&self) -> USVString { USVString("".to_owned()) } + fn UsvstringAttribute(&self) -> USVString { + USVString("".to_owned()) + } fn SetUsvstringAttribute(&self, _: USVString) {} - fn ByteStringAttribute(&self) -> ByteString { ByteString::new(vec!()) } + fn ByteStringAttribute(&self) -> ByteString { + ByteString::new(vec![]) + } fn SetByteStringAttribute(&self, _: ByteString) {} - fn EnumAttribute(&self) -> TestEnum { TestEnum::_empty } + fn EnumAttribute(&self) -> TestEnum { + TestEnum::_empty + } fn SetEnumAttribute(&self, _: TestEnum) {} fn InterfaceAttribute(&self) -> DomRoot<Blob> { - Blob::new(&self.global(), BlobImpl::new_from_bytes(vec![]), "".to_owned()) + Blob::new( + &self.global(), + BlobImpl::new_from_bytes(vec![]), + "".to_owned(), + ) } fn SetInterfaceAttribute(&self, _: &Blob) {} - fn UnionAttribute(&self) -> HTMLElementOrLong { HTMLElementOrLong::Long(0) } + fn UnionAttribute(&self) -> HTMLElementOrLong { + HTMLElementOrLong::Long(0) + } fn SetUnionAttribute(&self, _: HTMLElementOrLong) {} - fn Union2Attribute(&self) -> EventOrString { EventOrString::String(DOMString::new()) } + fn Union2Attribute(&self) -> EventOrString { + EventOrString::String(DOMString::new()) + } fn SetUnion2Attribute(&self, _: EventOrString) {} fn Union3Attribute(&self) -> EventOrUSVString { EventOrUSVString::USVString(USVString("".to_owned())) @@ -150,7 +195,7 @@ impl TestBindingMethods for TestBinding { } fn SetUnion8Attribute(&self, _: BlobOrUnsignedLong) {} fn Union9Attribute(&self) -> ByteStringOrLong { - ByteStringOrLong::ByteString(ByteString::new(vec!())) + ByteStringOrLong::ByteString(ByteString::new(vec![])) } fn SetUnion9Attribute(&self, _: ByteStringOrLong) {} #[allow(unsafe_code)] @@ -159,7 +204,9 @@ impl TestBindingMethods for TestBinding { NonNull::new(array.get()).expect("got a null pointer") } #[allow(unsafe_code)] - unsafe fn AnyAttribute(&self, _: *mut JSContext) -> JSVal { NullValue() } + unsafe fn AnyAttribute(&self, _: *mut JSContext) -> JSVal { + NullValue() + } #[allow(unsafe_code)] unsafe fn SetAnyAttribute(&self, _: *mut JSContext, _: HandleValue) {} #[allow(unsafe_code)] @@ -170,48 +217,94 @@ impl TestBindingMethods for TestBinding { #[allow(unsafe_code)] unsafe fn SetObjectAttribute(&self, _: *mut JSContext, _: *mut JSObject) {} - fn GetBooleanAttributeNullable(&self) -> Option<bool> { Some(false) } + fn GetBooleanAttributeNullable(&self) -> Option<bool> { + Some(false) + } fn SetBooleanAttributeNullable(&self, _: Option<bool>) {} - fn GetByteAttributeNullable(&self) -> Option<i8> { Some(0) } + fn GetByteAttributeNullable(&self) -> Option<i8> { + Some(0) + } fn SetByteAttributeNullable(&self, _: Option<i8>) {} - fn GetOctetAttributeNullable(&self) -> Option<u8> { Some(0) } + fn GetOctetAttributeNullable(&self) -> Option<u8> { + Some(0) + } fn SetOctetAttributeNullable(&self, _: Option<u8>) {} - fn GetShortAttributeNullable(&self) -> Option<i16> { Some(0) } + fn GetShortAttributeNullable(&self) -> Option<i16> { + Some(0) + } fn SetShortAttributeNullable(&self, _: Option<i16>) {} - fn GetUnsignedShortAttributeNullable(&self) -> Option<u16> { Some(0) } + fn GetUnsignedShortAttributeNullable(&self) -> Option<u16> { + Some(0) + } fn SetUnsignedShortAttributeNullable(&self, _: Option<u16>) {} - fn GetLongAttributeNullable(&self) -> Option<i32> { Some(0) } + fn GetLongAttributeNullable(&self) -> Option<i32> { + Some(0) + } fn SetLongAttributeNullable(&self, _: Option<i32>) {} - fn GetUnsignedLongAttributeNullable(&self) -> Option<u32> { Some(0) } + fn GetUnsignedLongAttributeNullable(&self) -> Option<u32> { + Some(0) + } fn SetUnsignedLongAttributeNullable(&self, _: Option<u32>) {} - fn GetLongLongAttributeNullable(&self) -> Option<i64> { Some(0) } + fn GetLongLongAttributeNullable(&self) -> Option<i64> { + Some(0) + } fn SetLongLongAttributeNullable(&self, _: Option<i64>) {} - fn GetUnsignedLongLongAttributeNullable(&self) -> Option<u64> { Some(0) } + fn GetUnsignedLongLongAttributeNullable(&self) -> Option<u64> { + Some(0) + } fn SetUnsignedLongLongAttributeNullable(&self, _: Option<u64>) {} - fn GetUnrestrictedFloatAttributeNullable(&self) -> Option<f32> { Some(0.) } + fn GetUnrestrictedFloatAttributeNullable(&self) -> Option<f32> { + Some(0.) + } fn SetUnrestrictedFloatAttributeNullable(&self, _: Option<f32>) {} - fn GetFloatAttributeNullable(&self) -> Option<Finite<f32>> { Some(Finite::wrap(0.)) } + fn GetFloatAttributeNullable(&self) -> Option<Finite<f32>> { + Some(Finite::wrap(0.)) + } fn SetFloatAttributeNullable(&self, _: Option<Finite<f32>>) {} - fn GetUnrestrictedDoubleAttributeNullable(&self) -> Option<f64> { Some(0.) } + fn GetUnrestrictedDoubleAttributeNullable(&self) -> Option<f64> { + Some(0.) + } fn SetUnrestrictedDoubleAttributeNullable(&self, _: Option<f64>) {} - fn GetDoubleAttributeNullable(&self) -> Option<Finite<f64>> { Some(Finite::wrap(0.)) } + fn GetDoubleAttributeNullable(&self) -> Option<Finite<f64>> { + Some(Finite::wrap(0.)) + } fn SetDoubleAttributeNullable(&self, _: Option<Finite<f64>>) {} - fn GetByteStringAttributeNullable(&self) -> Option<ByteString> { Some(ByteString::new(vec!())) } + fn GetByteStringAttributeNullable(&self) -> Option<ByteString> { + Some(ByteString::new(vec![])) + } fn SetByteStringAttributeNullable(&self, _: Option<ByteString>) {} - fn GetStringAttributeNullable(&self) -> Option<DOMString> { Some(DOMString::new()) } + fn GetStringAttributeNullable(&self) -> Option<DOMString> { + Some(DOMString::new()) + } fn SetStringAttributeNullable(&self, _: Option<DOMString>) {} - fn GetUsvstringAttributeNullable(&self) -> Option<USVString> { Some(USVString("".to_owned())) } + fn GetUsvstringAttributeNullable(&self) -> Option<USVString> { + Some(USVString("".to_owned())) + } fn SetUsvstringAttributeNullable(&self, _: Option<USVString>) {} fn SetBinaryRenamedAttribute(&self, _: DOMString) {} - fn ForwardedAttribute(&self) -> DomRoot<TestBinding> { DomRoot::from_ref(self) } - fn BinaryRenamedAttribute(&self) -> DOMString { DOMString::new() } + fn ForwardedAttribute(&self) -> DomRoot<TestBinding> { + DomRoot::from_ref(self) + } + fn BinaryRenamedAttribute(&self) -> DOMString { + DOMString::new() + } fn SetBinaryRenamedAttribute2(&self, _: DOMString) {} - fn BinaryRenamedAttribute2(&self) -> DOMString { DOMString::new() } - fn Attr_to_automatically_rename(&self) -> DOMString { DOMString::new() } + fn BinaryRenamedAttribute2(&self) -> DOMString { + DOMString::new() + } + fn Attr_to_automatically_rename(&self) -> DOMString { + DOMString::new() + } fn SetAttr_to_automatically_rename(&self, _: DOMString) {} - fn GetEnumAttributeNullable(&self) -> Option<TestEnum> { Some(TestEnum::_empty) } + fn GetEnumAttributeNullable(&self) -> Option<TestEnum> { + Some(TestEnum::_empty) + } fn GetInterfaceAttributeNullable(&self) -> Option<DomRoot<Blob>> { - Some(Blob::new(&self.global(), BlobImpl::new_from_bytes(vec![]), "".to_owned())) + Some(Blob::new( + &self.global(), + BlobImpl::new_from_bytes(vec![]), + "".to_owned(), + )) } fn SetInterfaceAttributeNullable(&self, _: Option<&Blob>) {} fn GetInterfaceAttributeWeak(&self) -> Option<DomRoot<URL>> { @@ -221,7 +314,9 @@ impl TestBindingMethods for TestBinding { self.url.set(url); } #[allow(unsafe_code)] - unsafe fn GetObjectAttributeNullable(&self, _: *mut JSContext) -> Option<NonNull<JSObject>> { None } + unsafe fn GetObjectAttributeNullable(&self, _: *mut JSContext) -> Option<NonNull<JSObject>> { + None + } #[allow(unsafe_code)] unsafe fn SetObjectAttributeNullable(&self, _: *mut JSContext, _: *mut JSObject) {} fn GetUnionAttributeNullable(&self) -> Option<HTMLElementOrLong> { @@ -245,55 +340,119 @@ impl TestBindingMethods for TestBinding { } fn SetUnion5AttributeNullable(&self, _: Option<StringOrBoolean>) {} fn GetUnion6AttributeNullable(&self) -> Option<ByteStringOrLong> { - Some(ByteStringOrLong::ByteString(ByteString::new(vec!()))) + Some(ByteStringOrLong::ByteString(ByteString::new(vec![]))) } fn SetUnion6AttributeNullable(&self, _: Option<ByteStringOrLong>) {} fn BinaryRenamedMethod(&self) {} fn ReceiveVoid(&self) {} - fn ReceiveBoolean(&self) -> bool { false } - fn ReceiveByte(&self) -> i8 { 0 } - fn ReceiveOctet(&self) -> u8 { 0 } - fn ReceiveShort(&self) -> i16 { 0 } - fn ReceiveUnsignedShort(&self) -> u16 { 0 } - fn ReceiveLong(&self) -> i32 { 0 } - fn ReceiveUnsignedLong(&self) -> u32 { 0 } - fn ReceiveLongLong(&self) -> i64 { 0 } - fn ReceiveUnsignedLongLong(&self) -> u64 { 0 } - fn ReceiveUnrestrictedFloat(&self) -> f32 { 0. } - fn ReceiveFloat(&self) -> Finite<f32> { Finite::wrap(0.) } - fn ReceiveUnrestrictedDouble(&self) -> f64 { 0. } - fn ReceiveDouble(&self) -> Finite<f64> { Finite::wrap(0.) } - fn ReceiveString(&self) -> DOMString { DOMString::new() } - fn ReceiveUsvstring(&self) -> USVString { USVString("".to_owned()) } - fn ReceiveByteString(&self) -> ByteString { ByteString::new(vec!()) } - fn ReceiveEnum(&self) -> TestEnum { TestEnum::_empty } + fn ReceiveBoolean(&self) -> bool { + false + } + fn ReceiveByte(&self) -> i8 { + 0 + } + fn ReceiveOctet(&self) -> u8 { + 0 + } + fn ReceiveShort(&self) -> i16 { + 0 + } + fn ReceiveUnsignedShort(&self) -> u16 { + 0 + } + fn ReceiveLong(&self) -> i32 { + 0 + } + fn ReceiveUnsignedLong(&self) -> u32 { + 0 + } + fn ReceiveLongLong(&self) -> i64 { + 0 + } + fn ReceiveUnsignedLongLong(&self) -> u64 { + 0 + } + fn ReceiveUnrestrictedFloat(&self) -> f32 { + 0. + } + fn ReceiveFloat(&self) -> Finite<f32> { + Finite::wrap(0.) + } + fn ReceiveUnrestrictedDouble(&self) -> f64 { + 0. + } + fn ReceiveDouble(&self) -> Finite<f64> { + Finite::wrap(0.) + } + fn ReceiveString(&self) -> DOMString { + DOMString::new() + } + fn ReceiveUsvstring(&self) -> USVString { + USVString("".to_owned()) + } + fn ReceiveByteString(&self) -> ByteString { + ByteString::new(vec![]) + } + fn ReceiveEnum(&self) -> TestEnum { + TestEnum::_empty + } fn ReceiveInterface(&self) -> DomRoot<Blob> { - Blob::new(&self.global(), BlobImpl::new_from_bytes(vec![]), "".to_owned()) + Blob::new( + &self.global(), + BlobImpl::new_from_bytes(vec![]), + "".to_owned(), + ) } #[allow(unsafe_code)] - unsafe fn ReceiveAny(&self, _: *mut JSContext) -> JSVal { NullValue() } + unsafe fn ReceiveAny(&self, _: *mut JSContext) -> JSVal { + NullValue() + } #[allow(unsafe_code)] unsafe fn ReceiveObject(&self, cx: *mut JSContext) -> NonNull<JSObject> { self.ObjectAttribute(cx) } - fn ReceiveUnion(&self) -> HTMLElementOrLong { HTMLElementOrLong::Long(0) } - fn ReceiveUnion2(&self) -> EventOrString { EventOrString::String(DOMString::new()) } - fn ReceiveUnion3(&self) -> StringOrLongSequence { StringOrLongSequence::LongSequence(vec![]) } - fn ReceiveUnion4(&self) -> StringOrStringSequence { StringOrStringSequence::StringSequence(vec![]) } - fn ReceiveUnion5(&self) -> BlobOrBlobSequence { BlobOrBlobSequence::BlobSequence(vec![]) } - fn ReceiveUnion6(&self) -> StringOrUnsignedLong { StringOrUnsignedLong::String(DOMString::new()) } - fn ReceiveUnion7(&self) -> StringOrBoolean { StringOrBoolean::Boolean(true) } - fn ReceiveUnion8(&self) -> UnsignedLongOrBoolean { UnsignedLongOrBoolean::UnsignedLong(0u32) } + fn ReceiveUnion(&self) -> HTMLElementOrLong { + HTMLElementOrLong::Long(0) + } + fn ReceiveUnion2(&self) -> EventOrString { + EventOrString::String(DOMString::new()) + } + fn ReceiveUnion3(&self) -> StringOrLongSequence { + StringOrLongSequence::LongSequence(vec![]) + } + fn ReceiveUnion4(&self) -> StringOrStringSequence { + StringOrStringSequence::StringSequence(vec![]) + } + fn ReceiveUnion5(&self) -> BlobOrBlobSequence { + BlobOrBlobSequence::BlobSequence(vec![]) + } + fn ReceiveUnion6(&self) -> StringOrUnsignedLong { + StringOrUnsignedLong::String(DOMString::new()) + } + fn ReceiveUnion7(&self) -> StringOrBoolean { + StringOrBoolean::Boolean(true) + } + fn ReceiveUnion8(&self) -> UnsignedLongOrBoolean { + UnsignedLongOrBoolean::UnsignedLong(0u32) + } fn ReceiveUnion9(&self) -> HTMLElementOrUnsignedLongOrStringOrBoolean { HTMLElementOrUnsignedLongOrStringOrBoolean::Boolean(true) } - fn ReceiveUnion10(&self) -> ByteStringOrLong { ByteStringOrLong::ByteString(ByteString::new(vec!())) } + fn ReceiveUnion10(&self) -> ByteStringOrLong { + ByteStringOrLong::ByteString(ByteString::new(vec![])) + } fn ReceiveUnion11(&self) -> ByteStringSequenceOrLongOrString { - ByteStringSequenceOrLongOrString::ByteStringSequence(vec!(ByteString::new(vec!()))) + ByteStringSequenceOrLongOrString::ByteStringSequence(vec![ByteString::new(vec![])]) + } + fn ReceiveSequence(&self) -> Vec<i32> { + vec![1] } - fn ReceiveSequence(&self) -> Vec<i32> { vec![1] } fn ReceiveInterfaceSequence(&self) -> Vec<DomRoot<Blob>> { - vec![Blob::new(&self.global(), BlobImpl::new_from_bytes(vec![]), "".to_owned())] + vec![Blob::new( + &self.global(), + BlobImpl::new_from_bytes(vec![]), + "".to_owned(), + )] } #[allow(unsafe_code)] unsafe fn ReceiveUnionIdentity( @@ -304,25 +463,63 @@ impl TestBindingMethods for TestBinding { arg } - fn ReceiveNullableBoolean(&self) -> Option<bool> { Some(false) } - fn ReceiveNullableByte(&self) -> Option<i8> { Some(0) } - fn ReceiveNullableOctet(&self) -> Option<u8> { Some(0) } - fn ReceiveNullableShort(&self) -> Option<i16> { Some(0) } - fn ReceiveNullableUnsignedShort(&self) -> Option<u16> { Some(0) } - fn ReceiveNullableLong(&self) -> Option<i32> { Some(0) } - fn ReceiveNullableUnsignedLong(&self) -> Option<u32> { Some(0) } - fn ReceiveNullableLongLong(&self) -> Option<i64> { Some(0) } - fn ReceiveNullableUnsignedLongLong(&self) -> Option<u64> { Some(0) } - fn ReceiveNullableUnrestrictedFloat(&self) -> Option<f32> { Some(0.) } - fn ReceiveNullableFloat(&self) -> Option<Finite<f32>> { Some(Finite::wrap(0.)) } - fn ReceiveNullableUnrestrictedDouble(&self) -> Option<f64> { Some(0.) } - fn ReceiveNullableDouble(&self) -> Option<Finite<f64>> { Some(Finite::wrap(0.)) } - fn ReceiveNullableString(&self) -> Option<DOMString> { Some(DOMString::new()) } - fn ReceiveNullableUsvstring(&self) -> Option<USVString> { Some(USVString("".to_owned())) } - fn ReceiveNullableByteString(&self) -> Option<ByteString> { Some(ByteString::new(vec!())) } - fn ReceiveNullableEnum(&self) -> Option<TestEnum> { Some(TestEnum::_empty) } + fn ReceiveNullableBoolean(&self) -> Option<bool> { + Some(false) + } + fn ReceiveNullableByte(&self) -> Option<i8> { + Some(0) + } + fn ReceiveNullableOctet(&self) -> Option<u8> { + Some(0) + } + fn ReceiveNullableShort(&self) -> Option<i16> { + Some(0) + } + fn ReceiveNullableUnsignedShort(&self) -> Option<u16> { + Some(0) + } + fn ReceiveNullableLong(&self) -> Option<i32> { + Some(0) + } + fn ReceiveNullableUnsignedLong(&self) -> Option<u32> { + Some(0) + } + fn ReceiveNullableLongLong(&self) -> Option<i64> { + Some(0) + } + fn ReceiveNullableUnsignedLongLong(&self) -> Option<u64> { + Some(0) + } + fn ReceiveNullableUnrestrictedFloat(&self) -> Option<f32> { + Some(0.) + } + fn ReceiveNullableFloat(&self) -> Option<Finite<f32>> { + Some(Finite::wrap(0.)) + } + fn ReceiveNullableUnrestrictedDouble(&self) -> Option<f64> { + Some(0.) + } + fn ReceiveNullableDouble(&self) -> Option<Finite<f64>> { + Some(Finite::wrap(0.)) + } + fn ReceiveNullableString(&self) -> Option<DOMString> { + Some(DOMString::new()) + } + fn ReceiveNullableUsvstring(&self) -> Option<USVString> { + Some(USVString("".to_owned())) + } + fn ReceiveNullableByteString(&self) -> Option<ByteString> { + Some(ByteString::new(vec![])) + } + fn ReceiveNullableEnum(&self) -> Option<TestEnum> { + Some(TestEnum::_empty) + } fn ReceiveNullableInterface(&self) -> Option<DomRoot<Blob>> { - Some(Blob::new(&self.global(), BlobImpl::new_from_bytes(vec![]), "".to_owned())) + Some(Blob::new( + &self.global(), + BlobImpl::new_from_bytes(vec![]), + "".to_owned(), + )) } #[allow(unsafe_code)] unsafe fn ReceiveNullableObject(&self, cx: *mut JSContext) -> Option<NonNull<JSObject>> { @@ -344,9 +541,11 @@ impl TestBindingMethods for TestBinding { Some(UnsignedLongOrBoolean::UnsignedLong(0u32)) } fn ReceiveNullableUnion6(&self) -> Option<ByteStringOrLong> { - Some(ByteStringOrLong::ByteString(ByteString::new(vec!()))) + Some(ByteStringOrLong::ByteString(ByteString::new(vec![]))) + } + fn ReceiveNullableSequence(&self) -> Option<Vec<i32>> { + Some(vec![1]) } - fn ReceiveNullableSequence(&self) -> Option<Vec<i32>> { Some(vec![1]) } fn ReceiveTestDictionaryWithSuccessOnKeyword(&self) -> RootedTraceableBox<TestDictionary> { RootedTraceableBox::new(TestDictionary { anyValue: RootedTraceableBox::new(Heap::default()), @@ -465,11 +664,20 @@ impl TestBindingMethods for TestBinding { #[allow(unsafe_code)] unsafe fn PassAnySequence(&self, _: *mut JSContext, _: CustomAutoRooterGuard<Vec<JSVal>>) {} #[allow(unsafe_code)] - unsafe fn AnySequencePassthrough(&self, _: *mut JSContext, seq: CustomAutoRooterGuard<Vec<JSVal>>) -> Vec<JSVal> { + unsafe fn AnySequencePassthrough( + &self, + _: *mut JSContext, + seq: CustomAutoRooterGuard<Vec<JSVal>>, + ) -> Vec<JSVal> { (*seq).clone() } #[allow(unsafe_code)] - unsafe fn PassObjectSequence(&self, _: *mut JSContext, _: CustomAutoRooterGuard<Vec<*mut JSObject>>) {} + unsafe fn PassObjectSequence( + &self, + _: *mut JSContext, + _: CustomAutoRooterGuard<Vec<*mut JSObject>>, + ) { + } fn PassStringSequence(&self, _: Vec<DOMString>) {} fn PassInterfaceSequence(&self, _: Vec<DomRoot<Blob>>) {} @@ -496,7 +704,7 @@ impl TestBindingMethods for TestBinding { fn PassNullableInterface(&self, _: Option<&Blob>) {} #[allow(unsafe_code)] unsafe fn PassNullableObject(&self, _: *mut JSContext, _: *mut JSObject) {} - fn PassNullableTypedArray(&self, _: CustomAutoRooterGuard<Option<typedarray::Int8Array>>) { } + fn PassNullableTypedArray(&self, _: CustomAutoRooterGuard<Option<typedarray::Int8Array>>) {} fn PassNullableUnion(&self, _: Option<HTMLElementOrLong>) {} fn PassNullableUnion2(&self, _: Option<EventOrString>) {} fn PassNullableUnion3(&self, _: Option<StringOrLongSequence>) {} @@ -626,8 +834,10 @@ impl TestBindingMethods for TestBinding { fn PassOptionalNullableStringWithNonNullDefault(&self, _: Option<DOMString>) {} fn PassOptionalNullableUsvstringWithNonNullDefault(&self, _: Option<USVString>) {} // fn PassOptionalNullableEnumWithNonNullDefault(self, _: Option<TestEnum>) {} - fn PassOptionalOverloaded(&self, a: &TestBinding, _: u32, _: u32) -> DomRoot<TestBinding> { DomRoot::from_ref(a) } - fn PassOptionalOverloaded_(&self, _: &Blob, _: u32) { } + fn PassOptionalOverloaded(&self, a: &TestBinding, _: u32, _: u32) -> DomRoot<TestBinding> { + DomRoot::from_ref(a) + } + fn PassOptionalOverloaded_(&self, _: &Blob, _: u32) {} fn PassVariadicBoolean(&self, _: Vec<bool>) {} fn PassVariadicBooleanAndDefault(&self, _: bool, _: Vec<bool>) {} @@ -663,26 +873,42 @@ impl TestBindingMethods for TestBinding { PREFS.get(pref_name.as_ref()).as_boolean().unwrap_or(false) } fn StringMozPreference(&self, pref_name: DOMString) -> DOMString { - PREFS.get(pref_name.as_ref()).as_string().map(|s| DOMString::from(s)).unwrap_or_else(|| DOMString::new()) + PREFS + .get(pref_name.as_ref()) + .as_string() + .map(|s| DOMString::from(s)) + .unwrap_or_else(|| DOMString::new()) + } + fn PrefControlledAttributeDisabled(&self) -> bool { + false + } + fn PrefControlledAttributeEnabled(&self) -> bool { + false } - fn PrefControlledAttributeDisabled(&self) -> bool { false } - fn PrefControlledAttributeEnabled(&self) -> bool { false } fn PrefControlledMethodDisabled(&self) {} fn PrefControlledMethodEnabled(&self) {} - fn FuncControlledAttributeDisabled(&self) -> bool { false } - fn FuncControlledAttributeEnabled(&self) -> bool { false } + fn FuncControlledAttributeDisabled(&self) -> bool { + false + } + fn FuncControlledAttributeEnabled(&self) -> bool { + false + } fn FuncControlledMethodDisabled(&self) {} fn FuncControlledMethodEnabled(&self) {} fn PassMozMap(&self, _: MozMap<i32>) {} - fn PassNullableMozMap(&self, _: Option<MozMap<i32> >) {} + fn PassNullableMozMap(&self, _: Option<MozMap<i32>>) {} fn PassMozMapOfNullableInts(&self, _: MozMap<Option<i32>>) {} fn PassOptionalMozMapOfNullableInts(&self, _: Option<MozMap<Option<i32>>>) {} - fn PassOptionalNullableMozMapOfNullableInts(&self, _: Option<Option<MozMap<Option<i32>> >>) {} + fn PassOptionalNullableMozMapOfNullableInts(&self, _: Option<Option<MozMap<Option<i32>>>>) {} fn PassCastableObjectMozMap(&self, _: MozMap<DomRoot<TestBinding>>) {} fn PassNullableCastableObjectMozMap(&self, _: MozMap<Option<DomRoot<TestBinding>>>) {} fn PassCastableObjectNullableMozMap(&self, _: Option<MozMap<DomRoot<TestBinding>>>) {} - fn PassNullableCastableObjectNullableMozMap(&self, _: Option<MozMap<Option<DomRoot<TestBinding>>>>) {} + fn PassNullableCastableObjectNullableMozMap( + &self, + _: Option<MozMap<Option<DomRoot<TestBinding>>>>, + ) { + } fn PassOptionalMozMap(&self, _: Option<MozMap<i32>>) {} fn PassOptionalNullableMozMap(&self, _: Option<Option<MozMap<i32>>>) {} fn PassOptionalNullableMozMapWithDefaultValue(&self, _: Option<MozMap<i32>>) {} @@ -692,23 +918,47 @@ impl TestBindingMethods for TestBinding { fn PassMozMapOfMozMaps(&self, _: MozMap<MozMap<i32>>) {} fn PassMozMapUnion(&self, _: UnionTypes::LongOrStringByteStringRecord) {} fn PassMozMapUnion2(&self, _: UnionTypes::TestBindingOrStringByteStringRecord) {} - fn PassMozMapUnion3(&self, _: UnionTypes::TestBindingOrByteStringSequenceSequenceOrStringByteStringRecord) {} - fn ReceiveMozMap(&self) -> MozMap<i32> { MozMap::new() } - fn ReceiveNullableMozMap(&self) -> Option<MozMap<i32>> { Some(MozMap::new()) } - fn ReceiveMozMapOfNullableInts(&self) -> MozMap<Option<i32>> { MozMap::new() } - fn ReceiveNullableMozMapOfNullableInts(&self) -> Option<MozMap<Option<i32>>> { Some(MozMap::new()) } - fn ReceiveMozMapOfMozMaps(&self) -> MozMap<MozMap<i32>> { MozMap::new() } - fn ReceiveAnyMozMap(&self) -> MozMap<JSVal> { MozMap::new() } + fn PassMozMapUnion3( + &self, + _: UnionTypes::TestBindingOrByteStringSequenceSequenceOrStringByteStringRecord, + ) { + } + fn ReceiveMozMap(&self) -> MozMap<i32> { + MozMap::new() + } + fn ReceiveNullableMozMap(&self) -> Option<MozMap<i32>> { + Some(MozMap::new()) + } + fn ReceiveMozMapOfNullableInts(&self) -> MozMap<Option<i32>> { + MozMap::new() + } + fn ReceiveNullableMozMapOfNullableInts(&self) -> Option<MozMap<Option<i32>>> { + Some(MozMap::new()) + } + fn ReceiveMozMapOfMozMaps(&self) -> MozMap<MozMap<i32>> { + MozMap::new() + } + fn ReceiveAnyMozMap(&self) -> MozMap<JSVal> { + MozMap::new() + } #[allow(unrooted_must_root)] #[allow(unsafe_code)] - unsafe fn ReturnResolvedPromise(&self, cx: *mut JSContext, v: HandleValue) -> Fallible<Rc<Promise>> { + unsafe fn ReturnResolvedPromise( + &self, + cx: *mut JSContext, + v: HandleValue, + ) -> Fallible<Rc<Promise>> { Promise::new_resolved(&self.global(), cx, v) } #[allow(unrooted_must_root)] #[allow(unsafe_code)] - unsafe fn ReturnRejectedPromise(&self, cx: *mut JSContext, v: HandleValue) -> Fallible<Rc<Promise>> { + unsafe fn ReturnRejectedPromise( + &self, + cx: *mut JSContext, + v: HandleValue, + ) -> Fallible<Rc<Promise>> { Promise::new_rejected(&self.global(), cx, v) } @@ -733,20 +983,24 @@ impl TestBindingMethods for TestBinding { promise: TrustedPromise::new(promise), value: value, }; - let _ = self.global() - .schedule_callback( - OneshotTimerCallback::TestBindingCallback(cb), - MsDuration::new(delay)); + let _ = self.global().schedule_callback( + OneshotTimerCallback::TestBindingCallback(cb), + MsDuration::new(delay), + ); } #[allow(unrooted_must_root)] - fn PromiseNativeHandler(&self, - resolve: Option<Rc<SimpleCallback>>, - reject: Option<Rc<SimpleCallback>>) -> Rc<Promise> { + fn PromiseNativeHandler( + &self, + resolve: Option<Rc<SimpleCallback>>, + reject: Option<Rc<SimpleCallback>>, + ) -> Rc<Promise> { let global = self.global(); - let handler = PromiseNativeHandler::new(&global, - resolve.map(SimpleHandler::new), - reject.map(SimpleHandler::new)); + let handler = PromiseNativeHandler::new( + &global, + resolve.map(SimpleHandler::new), + reject.map(SimpleHandler::new), + ); let p = Promise::new(&global); p.append_native_handler(&handler); return p; @@ -775,17 +1029,18 @@ impl TestBindingMethods for TestBinding { Promise::new(&self.global()) } - fn AcceptPromise(&self, _promise: &Promise) { - } + fn AcceptPromise(&self, _promise: &Promise) {} fn PassSequenceSequence(&self, _seq: Vec<Vec<i32>>) {} - fn ReturnSequenceSequence(&self) -> Vec<Vec<i32>> { vec![] } + fn ReturnSequenceSequence(&self) -> Vec<Vec<i32>> { + vec![] + } fn PassUnionSequenceSequence(&self, seq: LongOrLongSequenceSequence) { match seq { LongOrLongSequenceSequence::Long(_) => (), LongOrLongSequenceSequence::LongSequenceSequence(seq) => { let _seq: Vec<Vec<i32>> = seq; - } + }, } } @@ -802,7 +1057,9 @@ impl TestBindingMethods for TestBinding { self.global().as_window().advance_animation_clock(ms, tick); } - fn Panic(&self) { panic!("explicit panic from script") } + fn Panic(&self) { + panic!("explicit panic from script") + } fn EntryGlobal(&self) -> DomRoot<GlobalScope> { GlobalScope::entry() @@ -813,23 +1070,37 @@ impl TestBindingMethods for TestBinding { } impl TestBinding { - pub fn BooleanAttributeStatic(_: &GlobalScope) -> bool { false } + pub fn BooleanAttributeStatic(_: &GlobalScope) -> bool { + false + } pub fn SetBooleanAttributeStatic(_: &GlobalScope, _: bool) {} pub fn ReceiveVoidStatic(_: &GlobalScope) {} - pub fn PrefControlledStaticAttributeDisabled(_: &GlobalScope) -> bool { false } - pub fn PrefControlledStaticAttributeEnabled(_: &GlobalScope) -> bool { false } + pub fn PrefControlledStaticAttributeDisabled(_: &GlobalScope) -> bool { + false + } + pub fn PrefControlledStaticAttributeEnabled(_: &GlobalScope) -> bool { + false + } pub fn PrefControlledStaticMethodDisabled(_: &GlobalScope) {} pub fn PrefControlledStaticMethodEnabled(_: &GlobalScope) {} - pub fn FuncControlledStaticAttributeDisabled(_: &GlobalScope) -> bool { false } - pub fn FuncControlledStaticAttributeEnabled(_: &GlobalScope) -> bool { false } + pub fn FuncControlledStaticAttributeDisabled(_: &GlobalScope) -> bool { + false + } + pub fn FuncControlledStaticAttributeEnabled(_: &GlobalScope) -> bool { + false + } pub fn FuncControlledStaticMethodDisabled(_: &GlobalScope) {} pub fn FuncControlledStaticMethodEnabled(_: &GlobalScope) {} } #[allow(unsafe_code)] impl TestBinding { - pub unsafe fn condition_satisfied(_: *mut JSContext, _: HandleObject) -> bool { true } - pub unsafe fn condition_unsatisfied(_: *mut JSContext, _: HandleObject) -> bool { false } + pub unsafe fn condition_satisfied(_: *mut JSContext, _: HandleObject) -> bool { + true + } + pub unsafe fn condition_unsatisfied(_: *mut JSContext, _: HandleObject) -> bool { + false + } } #[derive(JSTraceable, MallocSizeOf)] diff --git a/components/script/dom/testbindingiterable.rs b/components/script/dom/testbindingiterable.rs index 06a9dda6b37..60c345ce9f1 100644 --- a/components/script/dom/testbindingiterable.rs +++ b/components/script/dom/testbindingiterable.rs @@ -21,10 +21,14 @@ pub struct TestBindingIterable { impl TestBindingIterable { fn new(global: &GlobalScope) -> DomRoot<TestBindingIterable> { - reflect_dom_object(Box::new(TestBindingIterable { - reflector: Reflector::new(), - vals: DomRefCell::new(vec![]), - }), global, TestBindingIterableBinding::Wrap) + reflect_dom_object( + Box::new(TestBindingIterable { + reflector: Reflector::new(), + vals: DomRefCell::new(vec![]), + }), + global, + TestBindingIterableBinding::Wrap, + ) } pub fn Constructor(global: &GlobalScope) -> Fallible<DomRoot<TestBindingIterable>> { @@ -33,9 +37,15 @@ impl TestBindingIterable { } impl TestBindingIterableMethods for TestBindingIterable { - fn Add(&self, v: DOMString) { self.vals.borrow_mut().push(v); } - fn Length(&self) -> u32 { self.vals.borrow().len() as u32 } - fn GetItem(&self, n: u32) -> DOMString { self.IndexedGetter(n).unwrap_or_default() } + fn Add(&self, v: DOMString) { + self.vals.borrow_mut().push(v); + } + fn Length(&self) -> u32 { + self.vals.borrow().len() as u32 + } + fn GetItem(&self, n: u32) -> DOMString { + self.IndexedGetter(n).unwrap_or_default() + } fn IndexedGetter(&self, n: u32) -> Option<DOMString> { self.vals.borrow().get(n as usize).cloned() } diff --git a/components/script/dom/testbindingpairiterable.rs b/components/script/dom/testbindingpairiterable.rs index 2fa90f48fc6..79e3154c6f3 100644 --- a/components/script/dom/testbindingpairiterable.rs +++ b/components/script/dom/testbindingpairiterable.rs @@ -28,19 +28,35 @@ impl Iterable for TestBindingPairIterable { self.map.borrow().len() as u32 } fn get_value_at_index(&self, index: u32) -> u32 { - self.map.borrow().iter().nth(index as usize).map(|a| &a.1).unwrap().clone() + self.map + .borrow() + .iter() + .nth(index as usize) + .map(|a| &a.1) + .unwrap() + .clone() } fn get_key_at_index(&self, index: u32) -> DOMString { - self.map.borrow().iter().nth(index as usize).map(|a| &a.0).unwrap().clone() + self.map + .borrow() + .iter() + .nth(index as usize) + .map(|a| &a.0) + .unwrap() + .clone() } } impl TestBindingPairIterable { fn new(global: &GlobalScope) -> DomRoot<TestBindingPairIterable> { - reflect_dom_object(Box::new(TestBindingPairIterable { - reflector: Reflector::new(), - map: DomRefCell::new(vec![]), - }), global, TestBindingPairIterableBinding::TestBindingPairIterableWrap) + reflect_dom_object( + Box::new(TestBindingPairIterable { + reflector: Reflector::new(), + map: DomRefCell::new(vec![]), + }), + global, + TestBindingPairIterableBinding::TestBindingPairIterableWrap, + ) } pub fn Constructor(global: &GlobalScope) -> Fallible<DomRoot<TestBindingPairIterable>> { diff --git a/components/script/dom/testbindingproxy.rs b/components/script/dom/testbindingproxy.rs index c43040eacb7..8c0766c250e 100644 --- a/components/script/dom/testbindingproxy.rs +++ b/components/script/dom/testbindingproxy.rs @@ -11,22 +11,35 @@ use dom_struct::dom_struct; #[dom_struct] pub struct TestBindingProxy { - reflector_: Reflector + reflector_: Reflector, } impl TestBindingProxyMethods for TestBindingProxy { - fn Length(&self) -> u32 { 0 } - fn SupportedPropertyNames(&self) -> Vec<DOMString> { vec![] } - fn GetNamedItem(&self, _: DOMString) -> DOMString { DOMString::new() } + fn Length(&self) -> u32 { + 0 + } + fn SupportedPropertyNames(&self) -> Vec<DOMString> { + vec![] + } + fn GetNamedItem(&self, _: DOMString) -> DOMString { + DOMString::new() + } fn SetNamedItem(&self, _: DOMString, _: DOMString) {} - fn GetItem(&self, _: u32) -> DOMString { DOMString::new() } + fn GetItem(&self, _: u32) -> DOMString { + DOMString::new() + } fn SetItem(&self, _: u32, _: DOMString) {} fn RemoveItem(&self, _: DOMString) {} - fn Stringifier(&self) -> DOMString { DOMString::new() } - fn IndexedGetter(&self, _: u32) -> Option<DOMString> { None } + fn Stringifier(&self) -> DOMString { + DOMString::new() + } + fn IndexedGetter(&self, _: u32) -> Option<DOMString> { + None + } fn NamedDeleter(&self, _: DOMString) {} fn IndexedSetter(&self, _: u32, _: DOMString) {} fn NamedSetter(&self, _: DOMString, _: DOMString) {} - fn NamedGetter(&self, _: DOMString) -> Option<DOMString> { None } - + fn NamedGetter(&self, _: DOMString) -> Option<DOMString> { + None + } } diff --git a/components/script/dom/testrunner.rs b/components/script/dom/testrunner.rs index c29b5c477d7..4a7276deb50 100644 --- a/components/script/dom/testrunner.rs +++ b/components/script/dom/testrunner.rs @@ -15,7 +15,7 @@ use ipc_channel::ipc::IpcSender; use profile_traits::ipc; // https://webbluetoothcg.github.io/web-bluetooth/tests#test-runner - #[dom_struct] +#[dom_struct] pub struct TestRunner { reflector_: Reflector, } @@ -28,9 +28,11 @@ impl TestRunner { } pub fn new(global: &GlobalScope) -> DomRoot<TestRunner> { - reflect_dom_object(Box::new(TestRunner::new_inherited()), - global, - TestRunnerBinding::Wrap) + reflect_dom_object( + Box::new(TestRunner::new_inherited()), + global, + TestRunnerBinding::Wrap, + ) } fn get_bluetooth_thread(&self) -> IpcSender<BluetoothRequest> { @@ -42,14 +44,12 @@ impl TestRunnerMethods for TestRunner { // https://webbluetoothcg.github.io/web-bluetooth/tests#setBluetoothMockDataSet fn SetBluetoothMockDataSet(&self, dataSetName: DOMString) -> ErrorResult { let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); - self.get_bluetooth_thread().send(BluetoothRequest::Test(String::from(dataSetName), sender)).unwrap(); + self.get_bluetooth_thread() + .send(BluetoothRequest::Test(String::from(dataSetName), sender)) + .unwrap(); match receiver.recv().unwrap().into() { - Ok(()) => { - Ok(()) - }, - Err(error) => { - Err(Error::from(error)) - }, + Ok(()) => Ok(()), + Err(error) => Err(Error::from(error)), } } } diff --git a/components/script/dom/testworklet.rs b/components/script/dom/testworklet.rs index 61a08a2b18f..61726d90c04 100644 --- a/components/script/dom/testworklet.rs +++ b/components/script/dom/testworklet.rs @@ -38,7 +38,11 @@ impl TestWorklet { fn new(window: &Window) -> DomRoot<TestWorklet> { let worklet = Worklet::new(window, WorkletGlobalScopeType::Test); - reflect_dom_object(Box::new(TestWorklet::new_inherited(&*worklet)), window, Wrap) + reflect_dom_object( + Box::new(TestWorklet::new_inherited(&*worklet)), + window, + Wrap, + ) } pub fn Constructor(window: &Window) -> Fallible<DomRoot<TestWorklet>> { @@ -55,6 +59,7 @@ impl TestWorkletMethods for TestWorklet { fn Lookup(&self, key: DOMString) -> Option<DOMString> { let id = self.worklet.worklet_id(); let pool = ScriptThread::worklet_thread_pool(); - pool.test_worklet_lookup(id, String::from(key)).map(DOMString::from) + pool.test_worklet_lookup(id, String::from(key)) + .map(DOMString::from) } } diff --git a/components/script/dom/testworkletglobalscope.rs b/components/script/dom/testworkletglobalscope.rs index a31159de215..49b8d8bd963 100644 --- a/components/script/dom/testworkletglobalscope.rs +++ b/components/script/dom/testworkletglobalscope.rs @@ -29,16 +29,24 @@ pub struct TestWorkletGlobalScope { impl TestWorkletGlobalScope { #[allow(unsafe_code)] - pub fn new(runtime: &Runtime, - pipeline_id: PipelineId, - base_url: ServoUrl, - executor: WorkletExecutor, - init: &WorkletGlobalScopeInit) - -> DomRoot<TestWorkletGlobalScope> - { - debug!("Creating test worklet global scope for pipeline {}.", pipeline_id); + pub fn new( + runtime: &Runtime, + pipeline_id: PipelineId, + base_url: ServoUrl, + executor: WorkletExecutor, + init: &WorkletGlobalScopeInit, + ) -> DomRoot<TestWorkletGlobalScope> { + debug!( + "Creating test worklet global scope for pipeline {}.", + pipeline_id + ); let global = Box::new(TestWorkletGlobalScope { - worklet_global: WorkletGlobalScope::new_inherited(pipeline_id, base_url, executor, init), + worklet_global: WorkletGlobalScope::new_inherited( + pipeline_id, + base_url, + executor, + init, + ), lookup_table: Default::default(), }); unsafe { TestWorkletGlobalScopeBinding::Wrap(runtime.cx(), global) } @@ -50,7 +58,7 @@ impl TestWorkletGlobalScope { debug!("Looking up key {}.", key); let result = self.lookup_table.borrow().get(&key).cloned(); let _ = sender.send(result); - } + }, } } } @@ -58,7 +66,9 @@ impl TestWorkletGlobalScope { impl TestWorkletGlobalScopeMethods for TestWorkletGlobalScope { fn RegisterKeyValue(&self, key: DOMString, value: DOMString) { debug!("Registering test worklet key/value {}/{}.", key, value); - self.lookup_table.borrow_mut().insert(String::from(key), String::from(value)); + self.lookup_table + .borrow_mut() + .insert(String::from(key), String::from(value)); } } diff --git a/components/script/dom/text.rs b/components/script/dom/text.rs index 3e33c6642bb..0b2d6a5b7c9 100644 --- a/components/script/dom/text.rs +++ b/components/script/dom/text.rs @@ -26,13 +26,16 @@ pub struct Text { impl Text { fn new_inherited(text: DOMString, document: &Document) -> Text { Text { - characterdata: CharacterData::new_inherited(text, document) + characterdata: CharacterData::new_inherited(text, document), } } pub fn new(text: DOMString, document: &Document) -> DomRoot<Text> { - Node::reflect_node(Box::new(Text::new_inherited(text, document)), - document, TextBinding::Wrap) + Node::reflect_node( + Box::new(Text::new_inherited(text, document)), + document, + TextBinding::Wrap, + ) } pub fn Constructor(window: &Window, text: DOMString) -> Fallible<DomRoot<Text>> { @@ -64,9 +67,12 @@ impl TextMethods for Text { let parent = node.GetParentNode(); if let Some(ref parent) = parent { // Step 7.1. - parent.InsertBefore(new_node.upcast(), node.GetNextSibling().r()).unwrap(); + parent + .InsertBefore(new_node.upcast(), node.GetNextSibling().r()) + .unwrap(); // Steps 7.2-3. - node.ranges().move_to_following_text_sibling_above(node, offset, new_node.upcast()); + node.ranges() + .move_to_following_text_sibling_above(node, offset, new_node.upcast()); // Steps 7.4-5. parent.ranges().increment_at(&parent, node.index() + 1); } @@ -78,11 +84,15 @@ impl TextMethods for Text { // https://dom.spec.whatwg.org/#dom-text-wholetext fn WholeText(&self) -> DOMString { - let first = self.upcast::<Node>().inclusively_preceding_siblings() - .take_while(|node| node.is::<Text>()) - .last().unwrap(); - let nodes = first.inclusively_following_siblings() - .take_while(|node| node.is::<Text>()); + let first = self + .upcast::<Node>() + .inclusively_preceding_siblings() + .take_while(|node| node.is::<Text>()) + .last() + .unwrap(); + let nodes = first + .inclusively_following_siblings() + .take_while(|node| node.is::<Text>()); let mut text = String::new(); for ref node in nodes { let cdata = node.downcast::<CharacterData>().unwrap(); diff --git a/components/script/dom/textcontrol.rs b/components/script/dom/textcontrol.rs index fa6c8d0b604..9abe8d03a69 100644 --- a/components/script/dom/textcontrol.rs +++ b/components/script/dom/textcontrol.rs @@ -30,7 +30,10 @@ pub struct TextControlSelection<'a, E: TextControlElement> { } impl<'a, E: TextControlElement> TextControlSelection<'a, E> { - pub fn new(element: &'a E, textinput: &'a DomRefCell<TextInput<ScriptToConstellationChan>>) -> Self { + pub fn new( + element: &'a E, + textinput: &'a DomRefCell<TextInput<ScriptToConstellationChan>>, + ) -> Self { TextControlSelection { element, textinput } } @@ -123,7 +126,7 @@ impl<'a, E: TextControlElement> TextControlSelection<'a, E> { Some(self.start()), Some(self.end()), direction.map(|d| SelectionDirection::from(d)), - None + None, ); Ok(()) } @@ -136,7 +139,12 @@ impl<'a, E: TextControlElement> TextControlSelection<'a, E> { } // Step 2 - self.set_range(Some(start), Some(end), direction.map(|d| SelectionDirection::from(d)), None); + self.set_range( + Some(start), + Some(end), + direction.map(|d| SelectionDirection::from(d)), + None, + ); Ok(()) } @@ -146,7 +154,7 @@ impl<'a, E: TextControlElement> TextControlSelection<'a, E> { replacement: DOMString, start: Option<u32>, end: Option<u32>, - selection_mode: SelectionMode + selection_mode: SelectionMode, ) -> ErrorResult { // Step 1 if !self.element.selection_api_applies() { @@ -244,7 +252,12 @@ impl<'a, E: TextControlElement> TextControlSelection<'a, E> { } // Step 14 - self.set_range(Some(selection_start), Some(selection_end), None, Some(original_selection_state)); + self.set_range( + Some(selection_start), + Some(selection_end), + None, + Some(original_selection_state), + ); Ok(()) } @@ -266,10 +279,11 @@ impl<'a, E: TextControlElement> TextControlSelection<'a, E> { start: Option<u32>, end: Option<u32>, direction: Option<SelectionDirection>, - original_selection_state: Option<SelectionState> + original_selection_state: Option<SelectionState>, ) { let mut textinput = self.textinput.borrow_mut(); - let original_selection_state = original_selection_state.unwrap_or_else(|| textinput.selection_state()); + let original_selection_state = + original_selection_state.unwrap_or_else(|| textinput.selection_state()); // Step 1 let start = start.unwrap_or(0); @@ -288,9 +302,12 @@ impl<'a, E: TextControlElement> TextControlSelection<'a, E> { atom!("select"), EventBubbles::Bubbles, EventCancelable::NotCancelable, - &window); + &window, + ); } - self.element.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage); + self.element + .upcast::<Node>() + .dirty(NodeDamage::OtherNodeDamage); } } diff --git a/components/script/dom/textdecoder.rs b/components/script/dom/textdecoder.rs index b9e0bdd9d55..1db4a32768a 100644 --- a/components/script/dom/textdecoder.rs +++ b/components/script/dom/textdecoder.rs @@ -34,39 +34,54 @@ impl TextDecoder { encoding: encoding, fatal: fatal, ignoreBOM: ignoreBOM, - decoder: RefCell::new( - if ignoreBOM { encoding.new_decoder() } else { encoding.new_decoder_without_bom_handling() } - ), + decoder: RefCell::new(if ignoreBOM { + encoding.new_decoder() + } else { + encoding.new_decoder_without_bom_handling() + }), in_stream: RefCell::new(Vec::new()), do_not_flush: Cell::new(false), } } fn make_range_error() -> Fallible<DomRoot<TextDecoder>> { - Err(Error::Range("The given encoding is not supported.".to_owned())) + Err(Error::Range( + "The given encoding is not supported.".to_owned(), + )) } - pub fn new(global: &GlobalScope, encoding: &'static Encoding, fatal: bool, ignoreBOM: bool) - -> DomRoot<TextDecoder> { - reflect_dom_object(Box::new(TextDecoder::new_inherited(encoding, fatal, ignoreBOM)), - global, - TextDecoderBinding::Wrap) + pub fn new( + global: &GlobalScope, + encoding: &'static Encoding, + fatal: bool, + ignoreBOM: bool, + ) -> DomRoot<TextDecoder> { + reflect_dom_object( + Box::new(TextDecoder::new_inherited(encoding, fatal, ignoreBOM)), + global, + TextDecoderBinding::Wrap, + ) } /// <https://encoding.spec.whatwg.org/#dom-textdecoder> - pub fn Constructor(global: &GlobalScope, - label: DOMString, - options: &TextDecoderBinding::TextDecoderOptions) - -> Fallible<DomRoot<TextDecoder>> { + pub fn Constructor( + global: &GlobalScope, + label: DOMString, + options: &TextDecoderBinding::TextDecoderOptions, + ) -> Fallible<DomRoot<TextDecoder>> { let encoding = match Encoding::for_label_no_replacement(label.as_bytes()) { None => return TextDecoder::make_range_error(), - Some(enc) => enc + Some(enc) => enc, }; - Ok(TextDecoder::new(global, encoding, options.fatal, options.ignoreBOM)) + Ok(TextDecoder::new( + global, + encoding, + options.fatal, + options.ignoreBOM, + )) } } - impl TextDecoderMethods for TextDecoder { // https://encoding.spec.whatwg.org/#dom-textdecoder-encoding fn Encoding(&self) -> DOMString { @@ -87,12 +102,13 @@ impl TextDecoderMethods for TextDecoder { fn Decode( &self, input: Option<ArrayBufferViewOrArrayBuffer>, - options: &TextDecodeOptions + options: &TextDecodeOptions, ) -> Fallible<USVString> { // Step 1. if !self.do_not_flush.get() { if self.ignoreBOM { - self.decoder.replace(self.encoding.new_decoder_without_bom_handling()); + self.decoder + .replace(self.encoding.new_decoder_without_bom_handling()); } else { self.decoder.replace(self.encoding.new_decoder()); } @@ -120,21 +136,27 @@ impl TextDecoderMethods for TextDecoder { let (remaining, s) = if self.fatal { // Step 4. let mut out_stream = String::with_capacity( - decoder.max_utf8_buffer_length_without_replacement(in_stream.len()).unwrap() + decoder + .max_utf8_buffer_length_without_replacement(in_stream.len()) + .unwrap(), ); // Step 5: Implemented by encoding_rs::Decoder. - match decoder.decode_to_string_without_replacement(&in_stream, &mut out_stream, !options.stream) { - (DecoderResult::InputEmpty, read) => { - (in_stream.split_off(read), out_stream) - }, + match decoder.decode_to_string_without_replacement( + &in_stream, + &mut out_stream, + !options.stream, + ) { + (DecoderResult::InputEmpty, read) => (in_stream.split_off(read), out_stream), // Step 5.3.3. _ => return Err(Error::Type("Decoding failed".to_owned())), } } else { // Step 4. - let mut out_stream = String::with_capacity(decoder.max_utf8_buffer_length(in_stream.len()).unwrap()); + let mut out_stream = + String::with_capacity(decoder.max_utf8_buffer_length(in_stream.len()).unwrap()); // Step 5: Implemented by encoding_rs::Decoder. - let (_result, read, _replaced) = decoder.decode_to_string(&in_stream, &mut out_stream, !options.stream); + let (_result, read, _replaced) = + decoder.decode_to_string(&in_stream, &mut out_stream, !options.stream); (in_stream.split_off(read), out_stream) }; (remaining, s) diff --git a/components/script/dom/textencoder.rs b/components/script/dom/textencoder.rs index cc0eae4e5a2..9a9e7925e49 100644 --- a/components/script/dom/textencoder.rs +++ b/components/script/dom/textencoder.rs @@ -28,9 +28,11 @@ impl TextEncoder { } pub fn new(global: &GlobalScope) -> DomRoot<TextEncoder> { - reflect_dom_object(Box::new(TextEncoder::new_inherited()), - global, - TextEncoderBinding::Wrap) + reflect_dom_object( + Box::new(TextEncoder::new_inherited()), + global, + TextEncoderBinding::Wrap, + ) } // https://encoding.spec.whatwg.org/#dom-textencoder @@ -51,7 +53,9 @@ impl TextEncoderMethods for TextEncoder { let encoded = input.0.as_bytes(); rooted!(in(cx) let mut js_object = ptr::null_mut::<JSObject>()); - assert!(Uint8Array::create(cx, CreateWith::Slice(&encoded), js_object.handle_mut()).is_ok()); + assert!( + Uint8Array::create(cx, CreateWith::Slice(&encoded), js_object.handle_mut()).is_ok() + ); NonNull::new_unchecked(js_object.get()) } diff --git a/components/script/dom/touch.rs b/components/script/dom/touch.rs index 2109f8d1ce9..c1b47a4df94 100644 --- a/components/script/dom/touch.rs +++ b/components/script/dom/touch.rs @@ -25,10 +25,16 @@ pub struct Touch { } impl Touch { - fn new_inherited(identifier: i32, target: &EventTarget, - screen_x: Finite<f64>, screen_y: Finite<f64>, - client_x: Finite<f64>, client_y: Finite<f64>, - page_x: Finite<f64>, page_y: Finite<f64>) -> Touch { + fn new_inherited( + identifier: i32, + target: &EventTarget, + screen_x: Finite<f64>, + screen_y: Finite<f64>, + client_x: Finite<f64>, + client_y: Finite<f64>, + page_x: Finite<f64>, + page_y: Finite<f64>, + ) -> Touch { Touch { reflector_: Reflector::new(), identifier: identifier, @@ -42,19 +48,23 @@ impl Touch { } } - pub fn new(window: &Window, identifier: i32, target: &EventTarget, - screen_x: Finite<f64>, screen_y: Finite<f64>, - client_x: Finite<f64>, client_y: Finite<f64>, - page_x: Finite<f64>, page_y: Finite<f64>) -> DomRoot<Touch> { - reflect_dom_object(Box::new( - Touch::new_inherited( - identifier, target, - screen_x, screen_y, - client_x, client_y, - page_x, page_y + pub fn new( + window: &Window, + identifier: i32, + target: &EventTarget, + screen_x: Finite<f64>, + screen_y: Finite<f64>, + client_x: Finite<f64>, + client_y: Finite<f64>, + page_x: Finite<f64>, + page_y: Finite<f64>, + ) -> DomRoot<Touch> { + reflect_dom_object( + Box::new(Touch::new_inherited( + identifier, target, screen_x, screen_y, client_x, client_y, page_x, page_y, )), window, - TouchBinding::Wrap + TouchBinding::Wrap, ) } } diff --git a/components/script/dom/touchevent.rs b/components/script/dom/touchevent.rs index 3f8db82c01a..021cefec52e 100644 --- a/components/script/dom/touchevent.rs +++ b/components/script/dom/touchevent.rs @@ -29,9 +29,11 @@ pub struct TouchEvent { } impl TouchEvent { - fn new_inherited(touches: &TouchList, - changed_touches: &TouchList, - target_touches: &TouchList) -> TouchEvent { + fn new_inherited( + touches: &TouchList, + changed_touches: &TouchList, + target_touches: &TouchList, + ) -> TouchEvent { TouchEvent { uievent: UIEvent::new_inherited(), touches: MutDom::new(touches), @@ -44,33 +46,46 @@ impl TouchEvent { } } - pub fn new_uninitialized(window: &Window, - touches: &TouchList, - changed_touches: &TouchList, - target_touches: &TouchList) -> DomRoot<TouchEvent> { - reflect_dom_object(Box::new(TouchEvent::new_inherited(touches, changed_touches, target_touches)), - window, - TouchEventBinding::Wrap) + pub fn new_uninitialized( + window: &Window, + touches: &TouchList, + changed_touches: &TouchList, + target_touches: &TouchList, + ) -> DomRoot<TouchEvent> { + reflect_dom_object( + Box::new(TouchEvent::new_inherited( + touches, + changed_touches, + target_touches, + )), + window, + TouchEventBinding::Wrap, + ) } - pub fn new(window: &Window, - type_: DOMString, - can_bubble: EventBubbles, - cancelable: EventCancelable, - view: Option<&Window>, - detail: i32, - touches: &TouchList, - changed_touches: &TouchList, - target_touches: &TouchList, - ctrl_key: bool, - alt_key: bool, - shift_key: bool, - meta_key: bool) -> DomRoot<TouchEvent> { + pub fn new( + window: &Window, + type_: DOMString, + can_bubble: EventBubbles, + cancelable: EventCancelable, + view: Option<&Window>, + detail: i32, + touches: &TouchList, + changed_touches: &TouchList, + target_touches: &TouchList, + ctrl_key: bool, + alt_key: bool, + shift_key: bool, + meta_key: bool, + ) -> DomRoot<TouchEvent> { let ev = TouchEvent::new_uninitialized(window, touches, changed_touches, target_touches); - ev.upcast::<UIEvent>().InitUIEvent(type_, - bool::from(can_bubble), - bool::from(cancelable), - view, detail); + ev.upcast::<UIEvent>().InitUIEvent( + type_, + bool::from(can_bubble), + bool::from(cancelable), + view, + detail, + ); ev.ctrl_key.set(ctrl_key); ev.alt_key.set(alt_key); ev.shift_key.set(shift_key); diff --git a/components/script/dom/touchlist.rs b/components/script/dom/touchlist.rs index 832d45baaeb..ae9de896113 100644 --- a/components/script/dom/touchlist.rs +++ b/components/script/dom/touchlist.rs @@ -25,8 +25,11 @@ impl TouchList { } pub fn new(window: &Window, touches: &[&Touch]) -> DomRoot<TouchList> { - reflect_dom_object(Box::new(TouchList::new_inherited(touches)), - window, TouchListBinding::Wrap) + reflect_dom_object( + Box::new(TouchList::new_inherited(touches)), + window, + TouchListBinding::Wrap, + ) } } @@ -38,7 +41,9 @@ impl TouchListMethods for TouchList { /// <https://w3c.github.io/touch-events/#widl-TouchList-item-getter-Touch-unsigned-long-index> fn Item(&self, index: u32) -> Option<DomRoot<Touch>> { - self.touches.get(index as usize).map(|js| DomRoot::from_ref(&**js)) + self.touches + .get(index as usize) + .map(|js| DomRoot::from_ref(&**js)) } /// <https://w3c.github.io/touch-events/#widl-TouchList-item-getter-Touch-unsigned-long-index> diff --git a/components/script/dom/transitionevent.rs b/components/script/dom/transitionevent.rs index 3d3f25f4e7a..9176fe18595 100644 --- a/components/script/dom/transitionevent.rs +++ b/components/script/dom/transitionevent.rs @@ -30,16 +30,20 @@ impl TransitionEvent { event: Event::new_inherited(), property_name: Atom::from(init.propertyName.clone()), elapsed_time: init.elapsedTime.clone(), - pseudo_element: init.pseudoElement.clone() + pseudo_element: init.pseudoElement.clone(), } } - pub fn new(window: &Window, - type_: Atom, - init: &TransitionEventInit) -> DomRoot<TransitionEvent> { - let ev = reflect_dom_object(Box::new(TransitionEvent::new_inherited(init)), - window, - TransitionEventBinding::Wrap); + pub fn new( + window: &Window, + type_: Atom, + init: &TransitionEventInit, + ) -> DomRoot<TransitionEvent> { + let ev = reflect_dom_object( + Box::new(TransitionEvent::new_inherited(init)), + window, + TransitionEventBinding::Wrap, + ); { let event = ev.upcast::<Event>(); event.init_event(type_, init.parent.bubbles, init.parent.cancelable); @@ -47,9 +51,11 @@ impl TransitionEvent { ev } - pub fn Constructor(window: &Window, - type_: DOMString, - init: &TransitionEventInit) -> Fallible<DomRoot<TransitionEvent>> { + pub fn Constructor( + window: &Window, + type_: DOMString, + init: &TransitionEventInit, + ) -> Fallible<DomRoot<TransitionEvent>> { Ok(TransitionEvent::new(window, Atom::from(type_), init)) } } diff --git a/components/script/dom/treewalker.rs b/components/script/dom/treewalker.rs index 6c7db10870f..ce57b9f8453 100644 --- a/components/script/dom/treewalker.rs +++ b/components/script/dom/treewalker.rs @@ -30,9 +30,7 @@ pub struct TreeWalker { } impl TreeWalker { - fn new_inherited(root_node: &Node, - what_to_show: u32, - filter: Filter) -> TreeWalker { + fn new_inherited(root_node: &Node, what_to_show: u32, filter: Filter) -> TreeWalker { TreeWalker { reflector_: Reflector::new(), root_node: Dom::from_ref(root_node), @@ -43,22 +41,28 @@ impl TreeWalker { } } - pub fn new_with_filter(document: &Document, - root_node: &Node, - what_to_show: u32, - filter: Filter) -> DomRoot<TreeWalker> { - reflect_dom_object(Box::new(TreeWalker::new_inherited(root_node, what_to_show, filter)), - document.window(), - TreeWalkerBinding::Wrap) + pub fn new_with_filter( + document: &Document, + root_node: &Node, + what_to_show: u32, + filter: Filter, + ) -> DomRoot<TreeWalker> { + reflect_dom_object( + Box::new(TreeWalker::new_inherited(root_node, what_to_show, filter)), + document.window(), + TreeWalkerBinding::Wrap, + ) } - pub fn new(document: &Document, - root_node: &Node, - what_to_show: u32, - node_filter: Option<Rc<NodeFilter>>) -> DomRoot<TreeWalker> { + pub fn new( + document: &Document, + root_node: &Node, + what_to_show: u32, + node_filter: Option<Rc<NodeFilter>>, + ) -> DomRoot<TreeWalker> { let filter = match node_filter { None => Filter::None, - Some(jsfilter) => Filter::Dom(jsfilter) + Some(jsfilter) => Filter::Dom(jsfilter), }; TreeWalker::new_with_filter(document, root_node, what_to_show, filter) } @@ -80,7 +84,7 @@ impl TreeWalkerMethods for TreeWalker { match self.filter { Filter::None => None, Filter::Dom(ref nf) => Some(nf.clone()), - Filter::Native(_) => panic!("Cannot convert native node filter to DOM NodeFilter") + Filter::Native(_) => panic!("Cannot convert native node filter to DOM NodeFilter"), } } @@ -108,7 +112,7 @@ impl TreeWalkerMethods for TreeWalker { // then set the currentNode attribute to node, return node." if NodeFilterConstants::FILTER_ACCEPT == self.accept_node(&node)? { self.current_node.set(&node); - return Ok(Some(node)) + return Ok(Some(node)); } }, None => break, @@ -121,29 +125,25 @@ impl TreeWalkerMethods for TreeWalker { // https://dom.spec.whatwg.org/#dom-treewalker-firstchild fn FirstChild(&self) -> Fallible<Option<DomRoot<Node>>> { // "The firstChild() method must traverse children of type first." - self.traverse_children(|node| node.GetFirstChild(), - |node| node.GetNextSibling()) + self.traverse_children(|node| node.GetFirstChild(), |node| node.GetNextSibling()) } // https://dom.spec.whatwg.org/#dom-treewalker-lastchild fn LastChild(&self) -> Fallible<Option<DomRoot<Node>>> { // "The lastChild() method must traverse children of type last." - self.traverse_children(|node| node.GetLastChild(), - |node| node.GetPreviousSibling()) + self.traverse_children(|node| node.GetLastChild(), |node| node.GetPreviousSibling()) } // https://dom.spec.whatwg.org/#dom-treewalker-previoussibling fn PreviousSibling(&self) -> Fallible<Option<DomRoot<Node>>> { // "The nextSibling() method must traverse siblings of type next." - self.traverse_siblings(|node| node.GetLastChild(), - |node| node.GetPreviousSibling()) + self.traverse_siblings(|node| node.GetLastChild(), |node| node.GetPreviousSibling()) } // https://dom.spec.whatwg.org/#dom-treewalker-nextsibling fn NextSibling(&self) -> Fallible<Option<DomRoot<Node>>> { // "The previousSibling() method must traverse siblings of type previous." - self.traverse_siblings(|node| node.GetFirstChild(), - |node| node.GetNextSibling()) + self.traverse_siblings(|node| node.GetFirstChild(), |node| node.GetNextSibling()) } // https://dom.spec.whatwg.org/#dom-treewalker-previousnode @@ -168,13 +168,12 @@ impl TreeWalkerMethods for TreeWalker { let result = self.accept_node(&node)?; match result { NodeFilterConstants::FILTER_REJECT => break, - _ if node.GetFirstChild().is_some() => - node = node.GetLastChild().unwrap(), + _ if node.GetFirstChild().is_some() => node = node.GetLastChild().unwrap(), NodeFilterConstants::FILTER_ACCEPT => { self.current_node.set(&node); - return Ok(Some(node)) + return Ok(Some(node)); }, - _ => break + _ => break, } } // "5. Set sibling to the previous sibling of node." @@ -182,21 +181,23 @@ impl TreeWalkerMethods for TreeWalker { } // "3. If node is root or node's parent is null, return null." if self.is_root_node(&node) || node.GetParentNode().is_none() { - return Ok(None) + return Ok(None); } // "4. Set node to its parent." match node.GetParentNode() { None => - // This can happen if the user set the current node to somewhere - // outside of the tree rooted at the original root. - return Ok(None), - Some(n) => node = n + // This can happen if the user set the current node to somewhere + // outside of the tree rooted at the original root. + { + return Ok(None) + }, + Some(n) => node = n, } // "5. Filter node and if the return value is FILTER_ACCEPT, then // set the currentNode attribute to node and return node." if NodeFilterConstants::FILTER_ACCEPT == self.accept_node(&node)? { self.current_node.set(&node); - return Ok(Some(node)) + return Ok(Some(node)); } } // "6. Return null." @@ -227,9 +228,9 @@ impl TreeWalkerMethods for TreeWalker { // set the currentNode attribute to node and return node." if NodeFilterConstants::FILTER_ACCEPT == result { self.current_node.set(&node); - return Ok(Some(node)) + return Ok(Some(node)); } - } + }, } } // "2. If a node is following node and is not following root, @@ -245,9 +246,9 @@ impl TreeWalkerMethods for TreeWalker { // set the currentNode attribute to node and return node." if NodeFilterConstants::FILTER_ACCEPT == result { self.current_node.set(&node); - return Ok(Some(node)) + return Ok(Some(node)); } - } + }, } // "5. Run these substeps again." } @@ -256,12 +257,14 @@ impl TreeWalkerMethods for TreeWalker { impl TreeWalker { // https://dom.spec.whatwg.org/#concept-traverse-children - fn traverse_children<F, G>(&self, - next_child: F, - next_sibling: G) - -> Fallible<Option<DomRoot<Node>>> - where F: Fn(&Node) -> Option<DomRoot<Node>>, - G: Fn(&Node) -> Option<DomRoot<Node>> + fn traverse_children<F, G>( + &self, + next_child: F, + next_sibling: G, + ) -> Fallible<Option<DomRoot<Node>>> + where + F: Fn(&Node) -> Option<DomRoot<Node>>, + G: Fn(&Node) -> Option<DomRoot<Node>>, { // "To **traverse children** of type *type*, run these steps:" // "1. Let node be the value of the currentNode attribute." @@ -283,7 +286,7 @@ impl TreeWalker { // attribute to node and return node." NodeFilterConstants::FILTER_ACCEPT => { self.current_node.set(&node); - return Ok(Some(DomRoot::from_ref(&node))) + return Ok(Some(DomRoot::from_ref(&node))); }, // "3. If result is FILTER_SKIP, run these subsubsteps:" NodeFilterConstants::FILTER_SKIP => { @@ -292,10 +295,10 @@ impl TreeWalker { if let Some(child) = next_child(&node) { // "2. If child is not null, set node to child and goto Main." node = child; - continue 'main + continue 'main; } }, - _ => {} + _ => {}, } // "4. Repeat these subsubsteps:" loop { @@ -306,7 +309,7 @@ impl TreeWalker { // set node to sibling and goto Main." Some(sibling) => { node = sibling; - continue 'main + continue 'main; }, None => { // "3. Let parent be node's parent." @@ -315,32 +318,36 @@ impl TreeWalker { // or parent is currentNode attribute's value, // return null." None => return Ok(None), - Some(ref parent) if self.is_root_node(&parent) - || self.is_current_node(&parent) => - return Ok(None), + Some(ref parent) + if self.is_root_node(&parent) || self.is_current_node(&parent) => + { + return Ok(None) + }, // "5. Otherwise, set node to parent." - Some(parent) => node = parent + Some(parent) => node = parent, } - } + }, } } } } // https://dom.spec.whatwg.org/#concept-traverse-siblings - fn traverse_siblings<F, G>(&self, - next_child: F, - next_sibling: G) - -> Fallible<Option<DomRoot<Node>>> - where F: Fn(&Node) -> Option<DomRoot<Node>>, - G: Fn(&Node) -> Option<DomRoot<Node>> + fn traverse_siblings<F, G>( + &self, + next_child: F, + next_sibling: G, + ) -> Fallible<Option<DomRoot<Node>>> + where + F: Fn(&Node) -> Option<DomRoot<Node>>, + G: Fn(&Node) -> Option<DomRoot<Node>>, { // "To **traverse siblings** of type *type* run these steps:" // "1. Let node be the value of the currentNode attribute." let mut node = self.current_node.get(); // "2. If node is root, return null." if self.is_root_node(&node) { - return Ok(None) + return Ok(None); } // "3. Run these substeps:" loop { @@ -357,7 +364,7 @@ impl TreeWalker { // attribute to node and return node." if NodeFilterConstants::FILTER_ACCEPT == result { self.current_node.set(&node); - return Ok(Some(node)) + return Ok(Some(node)); } // "4. Set sibling to node's first child if type is next, @@ -367,9 +374,10 @@ impl TreeWalker { // then set sibling to node's next sibling if type is next, // and node's previous sibling if type is previous." match (result, &sibling_op) { - (NodeFilterConstants::FILTER_REJECT, _) - | (_, &None) => sibling_op = next_sibling(&node), - _ => {} + (NodeFilterConstants::FILTER_REJECT, _) | (_, &None) => { + sibling_op = next_sibling(&node) + }, + _ => {}, } } // "3. Set node to its parent." @@ -381,17 +389,16 @@ impl TreeWalker { Some(n) => { node = n; if NodeFilterConstants::FILTER_ACCEPT == self.accept_node(&node)? { - return Ok(None) + return Ok(None); } - } + }, } // "6. Run these substeps again." } } // https://dom.spec.whatwg.org/#concept-tree-following - fn first_following_node_not_following_root(&self, node: &Node) - -> Option<DomRoot<Node>> { + fn first_following_node_not_following_root(&self, node: &Node) -> Option<DomRoot<Node>> { // "An object A is following an object B if A and B are in the same tree // and A comes after B in tree order." match node.GetNextSibling() { @@ -408,7 +415,7 @@ impl TreeWalker { candidate.GetNextSibling() } }, - it => it + it => it, } } @@ -422,7 +429,7 @@ impl TreeWalker { let n = node.NodeType() - 1; // Step 3. if (self.what_to_show & (1 << n)) == 0 { - return Ok(NodeFilterConstants::FILTER_SKIP) + return Ok(NodeFilterConstants::FILTER_SKIP); } match self.filter { // Step 4. @@ -457,12 +464,14 @@ impl<'a> Iterator for &'a TreeWalker { match self.NextNode() { Ok(node) => node, Err(_) => - // The Err path happens only when a JavaScript - // NodeFilter throws an exception. This iterator - // is meant for internal use from Rust code, which - // will probably be using a native Rust filter, - // which cannot produce an Err result. + // The Err path happens only when a JavaScript + // NodeFilter throws an exception. This iterator + // is meant for internal use from Rust code, which + // will probably be using a native Rust filter, + // which cannot produce an Err result. + { unreachable!() + }, } } } @@ -470,6 +479,6 @@ impl<'a> Iterator for &'a TreeWalker { #[derive(JSTraceable)] pub enum Filter { None, - Native(fn (node: &Node) -> u16), - Dom(Rc<NodeFilter>) + Native(fn(node: &Node) -> u16), + Dom(Rc<NodeFilter>), } diff --git a/components/script/dom/uievent.rs b/components/script/dom/uievent.rs index 1e6af67f41e..7eef5be3910 100644 --- a/components/script/dom/uievent.rs +++ b/components/script/dom/uievent.rs @@ -22,7 +22,7 @@ use std::default::Default; pub struct UIEvent { event: Event, view: MutNullableDom<Window>, - detail: Cell<i32> + detail: Cell<i32>, } impl UIEvent { @@ -35,31 +35,47 @@ impl UIEvent { } pub fn new_uninitialized(window: &Window) -> DomRoot<UIEvent> { - reflect_dom_object(Box::new(UIEvent::new_inherited()), - window, - UIEventBinding::Wrap) + reflect_dom_object( + Box::new(UIEvent::new_inherited()), + window, + UIEventBinding::Wrap, + ) } - pub fn new(window: &Window, - type_: DOMString, - can_bubble: EventBubbles, - cancelable: EventCancelable, - view: Option<&Window>, - detail: i32) -> DomRoot<UIEvent> { + pub fn new( + window: &Window, + type_: DOMString, + can_bubble: EventBubbles, + cancelable: EventCancelable, + view: Option<&Window>, + detail: i32, + ) -> DomRoot<UIEvent> { let ev = UIEvent::new_uninitialized(window); - ev.InitUIEvent(type_, bool::from(can_bubble), bool::from(cancelable), view, detail); + ev.InitUIEvent( + type_, + bool::from(can_bubble), + bool::from(cancelable), + view, + detail, + ); ev } - pub fn Constructor(window: &Window, - type_: DOMString, - init: &UIEventBinding::UIEventInit) -> Fallible<DomRoot<UIEvent>> { + pub fn Constructor( + window: &Window, + type_: DOMString, + init: &UIEventBinding::UIEventInit, + ) -> Fallible<DomRoot<UIEvent>> { let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::from(init.parent.cancelable); - let event = UIEvent::new(window, - type_, - bubbles, cancelable, - init.view.r(), init.detail); + let event = UIEvent::new( + window, + type_, + bubbles, + cancelable, + init.view.r(), + init.detail, + ); Ok(event) } } @@ -76,12 +92,14 @@ impl UIEventMethods for UIEvent { } // https://w3c.github.io/uievents/#widl-UIEvent-initUIEvent - fn InitUIEvent(&self, - type_: DOMString, - can_bubble: bool, - cancelable: bool, - view: Option<&Window>, - detail: i32) { + fn InitUIEvent( + &self, + type_: DOMString, + can_bubble: bool, + cancelable: bool, + view: Option<&Window>, + detail: i32, + ) { let event = self.upcast::<Event>(); if event.dispatching() { return; diff --git a/components/script/dom/url.rs b/components/script/dom/url.rs index 0fef2e5bb5f..0e0c5e02017 100644 --- a/components/script/dom/url.rs +++ b/components/script/dom/url.rs @@ -43,39 +43,50 @@ impl URL { } pub fn new(global: &GlobalScope, url: ServoUrl) -> DomRoot<URL> { - reflect_dom_object(Box::new(URL::new_inherited(url)), - global, URLBinding::Wrap) + reflect_dom_object(Box::new(URL::new_inherited(url)), global, URLBinding::Wrap) } pub fn query_pairs(&self) -> Vec<(String, String)> { - self.url.borrow().as_url().query_pairs().into_owned().collect() + self.url + .borrow() + .as_url() + .query_pairs() + .into_owned() + .collect() } pub fn set_query_pairs(&self, pairs: &[(String, String)]) { let mut url = self.url.borrow_mut(); - url.as_mut_url().query_pairs_mut().clear().extend_pairs(pairs); + url.as_mut_url() + .query_pairs_mut() + .clear() + .extend_pairs(pairs); } } impl URL { // https://url.spec.whatwg.org/#constructors - pub fn Constructor(global: &GlobalScope, url: USVString, - base: Option<USVString>) - -> Fallible<DomRoot<URL>> { + pub fn Constructor( + global: &GlobalScope, + url: USVString, + base: Option<USVString>, + ) -> Fallible<DomRoot<URL>> { let parsed_base = match base { None => { // Step 1. None }, Some(base) => - // Step 2.1. + // Step 2.1. + { match ServoUrl::parse(&base.0) { Ok(base) => Some(base), Err(error) => { // Step 2.2. return Err(Error::Type(format!("could not parse base: {}", error))); - } + }, } + }, }; // Step 3. let parsed_url = match ServoUrl::parse_with_base(parsed_base.as_ref(), &url.0) { @@ -83,7 +94,7 @@ impl URL { Err(error) => { // Step 4. return Err(Error::Type(format!("could not parse URL: {}", error))); - } + }, }; // Step 5: Skip (see step 8 below). // Steps 6-7. @@ -116,7 +127,7 @@ impl URL { let origin = get_blob_origin(&global.get_url()); if let Ok(url) = ServoUrl::parse(&url) { - if let Ok((id, _)) = parse_blob_url(&url) { + if let Ok((id, _)) = parse_blob_url(&url) { let resource_threads = global.resource_threads(); let (tx, rx) = ipc::channel(global.time_profiler_chan().clone()).unwrap(); let msg = FileManagerThreadMsg::RevokeBlobURL(id, origin, tx); @@ -186,12 +197,10 @@ impl URLMethods for URL { match ServoUrl::parse(&value.0) { Ok(url) => { *self.url.borrow_mut() = url; - self.search_params.set(None); // To be re-initialized in the SearchParams getter. + self.search_params.set(None); // To be re-initialized in the SearchParams getter. Ok(()) }, - Err(error) => { - Err(Error::Type(format!("could not parse URL: {}", error))) - }, + Err(error) => Err(Error::Type(format!("could not parse URL: {}", error))), } } @@ -255,9 +264,8 @@ impl URLMethods for URL { // https://url.spec.whatwg.org/#dom-url-searchparams fn SearchParams(&self) -> DomRoot<URLSearchParams> { - self.search_params.or_init(|| { - URLSearchParams::new(&self.global(), Some(self)) - }) + self.search_params + .or_init(|| URLSearchParams::new(&self.global(), Some(self))) } // https://url.spec.whatwg.org/#dom-url-href diff --git a/components/script/dom/urlsearchparams.rs b/components/script/dom/urlsearchparams.rs index a3a297a5f46..17867c63283 100644 --- a/components/script/dom/urlsearchparams.rs +++ b/components/script/dom/urlsearchparams.rs @@ -37,26 +37,32 @@ impl URLSearchParams { } pub fn new(global: &GlobalScope, url: Option<&URL>) -> DomRoot<URLSearchParams> { - reflect_dom_object(Box::new(URLSearchParams::new_inherited(url)), global, - URLSearchParamsWrap) + reflect_dom_object( + Box::new(URLSearchParams::new_inherited(url)), + global, + URLSearchParamsWrap, + ) } // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams - pub fn Constructor(global: &GlobalScope, init: Option<USVStringOrURLSearchParams>) -> - Fallible<DomRoot<URLSearchParams>> { + pub fn Constructor( + global: &GlobalScope, + init: Option<USVStringOrURLSearchParams>, + ) -> Fallible<DomRoot<URLSearchParams>> { // Step 1. let query = URLSearchParams::new(global, None); match init { Some(USVStringOrURLSearchParams::USVString(init)) => { // Step 2. *query.list.borrow_mut() = form_urlencoded::parse(init.0.as_bytes()) - .into_owned().collect(); + .into_owned() + .collect(); }, Some(USVStringOrURLSearchParams::URLSearchParams(init)) => { // Step 3. *query.list.borrow_mut() = init.list.borrow().clone(); }, - None => {} + None => {}, } // Step 4. Ok(query) @@ -87,20 +93,22 @@ impl URLSearchParamsMethods for URLSearchParams { // https://url.spec.whatwg.org/#dom-urlsearchparams-get fn Get(&self, name: USVString) -> Option<USVString> { let list = self.list.borrow(); - list.iter().find(|&kv| kv.0 == name.0) + list.iter() + .find(|&kv| kv.0 == name.0) .map(|ref kv| USVString(kv.1.clone())) } // https://url.spec.whatwg.org/#dom-urlsearchparams-getall fn GetAll(&self, name: USVString) -> Vec<USVString> { let list = self.list.borrow(); - list.iter().filter_map(|&(ref k, ref v)| { - if k == &name.0 { - Some(USVString(v.clone())) - } else { - None - } - }).collect() + list.iter() + .filter_map(|&(ref k, ref v)| { + if k == &name.0 { + Some(USVString(v.clone())) + } else { + None + } + }).collect() } // https://url.spec.whatwg.org/#dom-urlsearchparams-has @@ -132,8 +140,8 @@ impl URLSearchParamsMethods for URLSearchParams { Some(index) => list[index].1 = value.0, None => list.push((name.0, value.0)), // Step 2. }; - } // Un-borrow self.list - // Step 3. + } // Un-borrow self.list + // Step 3. self.update_steps(); } @@ -143,7 +151,6 @@ impl URLSearchParamsMethods for URLSearchParams { } } - impl URLSearchParams { // https://url.spec.whatwg.org/#concept-urlencoded-serializer pub fn serialize_utf8(&self) -> String { @@ -154,7 +161,6 @@ impl URLSearchParams { } } - impl URLSearchParams { // https://url.spec.whatwg.org/#concept-urlsearchparams-update fn update_steps(&self) { @@ -164,7 +170,6 @@ impl URLSearchParams { } } - impl Iterable for URLSearchParams { type Key = USVString; type Value = USVString; diff --git a/components/script/dom/userscripts.rs b/components/script/dom/userscripts.rs index e2db3e4cfe0..1180b0c8279 100644 --- a/components/script/dom/userscripts.rs +++ b/components/script/dom/userscripts.rs @@ -12,7 +12,6 @@ use std::fs::{File, read_dir}; use std::io::Read; use std::path::PathBuf; - pub fn load_script(head: &HTMLHeadElement) { if let Some(ref path_str) = opts::get().userscripts { let node = head.upcast::<Node>(); @@ -22,9 +21,11 @@ pub fn load_script(head: &HTMLHeadElement) { rooted!(in(cx) let mut rval = UndefinedValue()); let path = PathBuf::from(path_str); - let mut files = read_dir(&path).expect("Bad path passed to --userscripts") - .filter_map(|e| e.ok()) - .map(|e| e.path()).collect::<Vec<_>>(); + let mut files = read_dir(&path) + .expect("Bad path passed to --userscripts") + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .collect::<Vec<_>>(); files.sort(); @@ -33,7 +34,8 @@ pub fn load_script(head: &HTMLHeadElement) { let mut contents = vec![]; f.read_to_end(&mut contents).unwrap(); let script_text = String::from_utf8_lossy(&contents); - win.upcast::<GlobalScope>().evaluate_js_on_global_with_result(&script_text, rval.handle_mut()); + win.upcast::<GlobalScope>() + .evaluate_js_on_global_with_result(&script_text, rval.handle_mut()); } } } diff --git a/components/script/dom/validation.rs b/components/script/dom/validation.rs index 7ba915092a2..3945654ec55 100755 --- a/components/script/dom/validation.rs +++ b/components/script/dom/validation.rs @@ -4,6 +4,10 @@ use dom::validitystate::ValidationFlags; pub trait Validatable { - fn is_instance_validatable(&self) -> bool { true } - fn validate(&self, _validate_flags: ValidationFlags) -> bool { true } + fn is_instance_validatable(&self) -> bool { + true + } + fn validate(&self, _validate_flags: ValidationFlags) -> bool { + true + } } diff --git a/components/script/dom/validitystate.rs b/components/script/dom/validitystate.rs index 58c05356204..c0488c39ce8 100755 --- a/components/script/dom/validitystate.rs +++ b/components/script/dom/validitystate.rs @@ -24,7 +24,7 @@ pub enum ValidityStatus { StepMismatch, BadInput, CustomError, - Valid + Valid, } bitflags!{ @@ -47,23 +47,24 @@ bitflags!{ pub struct ValidityState { reflector_: Reflector, element: Dom<Element>, - state: ValidityStatus + state: ValidityStatus, } - impl ValidityState { fn new_inherited(element: &Element) -> ValidityState { ValidityState { reflector_: Reflector::new(), element: Dom::from_ref(element), - state: ValidityStatus::Valid + state: ValidityStatus::Valid, } } pub fn new(window: &Window, element: &Element) -> DomRoot<ValidityState> { - reflect_dom_object(Box::new(ValidityState::new_inherited(element)), - window, - ValidityStateBinding::Wrap) + reflect_dom_object( + Box::new(ValidityState::new_inherited(element)), + window, + ValidityStateBinding::Wrap, + ) } } diff --git a/components/script/dom/virtualmethods.rs b/components/script/dom/virtualmethods.rs index 03193415cb4..30c80c86fae 100644 --- a/components/script/dom/virtualmethods.rs +++ b/components/script/dom/virtualmethods.rs @@ -75,7 +75,7 @@ pub trait VirtualMethods { fn attribute_affects_presentational_hints(&self, attr: &Attr) -> bool { match self.super_type() { Some(s) => s.attribute_affects_presentational_hints(attr), - None => false + None => false, } } @@ -128,8 +128,12 @@ pub trait VirtualMethods { } /// <https://dom.spec.whatwg.org/#concept-node-clone-ext> - fn cloning_steps(&self, copy: &Node, maybe_doc: Option<&Document>, - clone_children: CloneChildrenFlag) { + fn cloning_steps( + &self, + copy: &Node, + maybe_doc: Option<&Document>, + clone_children: CloneChildrenFlag, + ) { if let Some(ref s) = self.super_type() { s.cloning_steps(copy, maybe_doc, clone_children); } @@ -152,122 +156,116 @@ pub fn vtable_for(node: &Node) -> &VirtualMethods { match node.type_id() { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) => { node.downcast::<HTMLAnchorElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAreaElement)) => { node.downcast::<HTMLAreaElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBaseElement)) => { node.downcast::<HTMLBaseElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBodyElement)) => { node.downcast::<HTMLBodyElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) => { node.downcast::<HTMLButtonElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLCanvasElement)) => { node.downcast::<HTMLCanvasElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLDetailsElement)) => { node.downcast::<HTMLDetailsElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFieldSetElement)) => { node.downcast::<HTMLFieldSetElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFontElement)) => { node.downcast::<HTMLFontElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFormElement)) => { node.downcast::<HTMLFormElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLHeadElement)) => { node.downcast::<HTMLHeadElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLHRElement)) => { node.downcast::<HTMLHRElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLImageElement)) => { node.downcast::<HTMLImageElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLIFrameElement)) => { node.downcast::<HTMLIFrameElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => { node.downcast::<HTMLInputElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLabelElement)) => { node.downcast::<HTMLLabelElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLIElement)) => { node.downcast::<HTMLLIElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLinkElement)) => { node.downcast::<HTMLLinkElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLMediaElement(_))) => { node.downcast::<HTMLMediaElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLMetaElement)) => { node.downcast::<HTMLMetaElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLObjectElement)) => { node.downcast::<HTMLObjectElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptGroupElement)) => { node.downcast::<HTMLOptGroupElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptionElement)) => { node.downcast::<HTMLOptionElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOutputElement)) => { node.downcast::<HTMLOutputElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLScriptElement)) => { node.downcast::<HTMLScriptElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) => { node.downcast::<HTMLSelectElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSourceElement)) => { node.downcast::<HTMLSourceElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLStyleElement)) => { node.downcast::<HTMLStyleElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableElement)) => { node.downcast::<HTMLTableElement>().unwrap() as &VirtualMethods - } - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableCellElement(_))) => { - node.downcast::<HTMLTableCellElement>().unwrap() as &VirtualMethods - } + }, + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLTableCellElement(_), + )) => node.downcast::<HTMLTableCellElement>().unwrap() as &VirtualMethods, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableRowElement)) => { node.downcast::<HTMLTableRowElement>().unwrap() as &VirtualMethods - } - NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableSectionElement)) => { - node.downcast::<HTMLTableSectionElement>().unwrap() as &VirtualMethods - } + }, + NodeTypeId::Element(ElementTypeId::HTMLElement( + HTMLElementTypeId::HTMLTableSectionElement, + )) => node.downcast::<HTMLTableSectionElement>().unwrap() as &VirtualMethods, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTemplateElement)) => { node.downcast::<HTMLTemplateElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => { node.downcast::<HTMLTextAreaElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTitleElement)) => { node.downcast::<HTMLTitleElement>().unwrap() as &VirtualMethods - } + }, NodeTypeId::Element(ElementTypeId::SVGElement(SVGElementTypeId::SVGGraphicsElement( - SVGGraphicsElementTypeId::SVGSVGElement - ))) => { - node.downcast::<SVGSVGElement>().unwrap() as &VirtualMethods - } + SVGGraphicsElementTypeId::SVGSVGElement, + ))) => node.downcast::<SVGSVGElement>().unwrap() as &VirtualMethods, NodeTypeId::Element(ElementTypeId::Element) => { node.downcast::<Element>().unwrap() as &VirtualMethods - } - NodeTypeId::Element(_) => { - node.downcast::<HTMLElement>().unwrap() as &VirtualMethods - } - _ => { - node as &VirtualMethods - } + }, + NodeTypeId::Element(_) => node.downcast::<HTMLElement>().unwrap() as &VirtualMethods, + _ => node as &VirtualMethods, } } diff --git a/components/script/dom/vr.rs b/components/script/dom/vr.rs index 3283015dd14..f41360bbb1a 100644 --- a/components/script/dom/vr.rs +++ b/components/script/dom/vr.rs @@ -29,7 +29,7 @@ use webvr_traits::{WebVRGamepadData, WebVRGamepadEvent, WebVRGamepadState}; pub struct VR { reflector_: Reflector, displays: DomRefCell<Vec<Dom<VRDisplay>>>, - gamepads: DomRefCell<Vec<Dom<Gamepad>>> + gamepads: DomRefCell<Vec<Dom<Gamepad>>>, } impl VR { @@ -61,7 +61,8 @@ impl VRMethods for VR { let promise = Promise::new(&self.global()); if let Some(webvr_thread) = self.webvr_thread() { - let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); + let (sender, receiver) = + ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); webvr_thread.send(WebVRMsg::GetDisplays(sender)).unwrap(); match receiver.recv().unwrap() { Ok(displays) => { @@ -73,7 +74,7 @@ impl VRMethods for VR { Err(e) => { promise.reject_native(&e); return promise; - } + }, } } else { // WebVR spec: The Promise MUST be rejected if WebVR is not enabled/supported. @@ -82,39 +83,42 @@ impl VRMethods for VR { } // convert from Dom to DomRoot - let displays: Vec<DomRoot<VRDisplay>> = self.displays.borrow().iter() - .map(|d| DomRoot::from_ref(&**d)) - .collect(); + let displays: Vec<DomRoot<VRDisplay>> = self + .displays + .borrow() + .iter() + .map(|d| DomRoot::from_ref(&**d)) + .collect(); promise.resolve_native(&displays); promise } } - impl VR { fn webvr_thread(&self) -> Option<IpcSender<WebVRMsg>> { self.global().as_window().webvr_thread() } fn find_display(&self, display_id: u32) -> Option<DomRoot<VRDisplay>> { - self.displays.borrow() - .iter() - .find(|d| d.DisplayId() == display_id) - .map(|d| DomRoot::from_ref(&**d)) + self.displays + .borrow() + .iter() + .find(|d| d.DisplayId() == display_id) + .map(|d| DomRoot::from_ref(&**d)) } fn register(&self) { if let Some(webvr_thread) = self.webvr_thread() { - let msg = WebVRMsg::RegisterContext(self.global().pipeline_id()); - webvr_thread.send(msg).unwrap(); + let msg = WebVRMsg::RegisterContext(self.global().pipeline_id()); + webvr_thread.send(msg).unwrap(); } } fn unregister(&self) { if let Some(webvr_thread) = self.webvr_thread() { - let msg = WebVRMsg::UnregisterContext(self.global().pipeline_id()); - webvr_thread.send(msg).unwrap(); + let msg = WebVRMsg::UnregisterContext(self.global().pipeline_id()); + webvr_thread.send(msg).unwrap(); } } @@ -157,7 +161,7 @@ impl VR { if let Some(display) = self.find_display(id) { display.handle_webvr_event(&event); } - } + }, }; } @@ -175,7 +179,7 @@ impl VR { if let Some(gamepad) = self.find_gamepad(id) { gamepad.update_connected(false); } - } + }, }; } @@ -186,7 +190,7 @@ impl VR { }, WebVREvent::Gamepad(event) => { self.handle_gamepad_event(event); - } + }, }; } @@ -198,17 +202,20 @@ impl VR { fn notify_display_event(&self, display: &VRDisplay, event: &WebVRDisplayEvent) { let event = VRDisplayEvent::new_from_webvr(&self.global(), &display, &event); - event.upcast::<Event>().fire(self.global().upcast::<EventTarget>()); + event + .upcast::<Event>() + .fire(self.global().upcast::<EventTarget>()); } } // Gamepad impl VR { fn find_gamepad(&self, gamepad_id: u32) -> Option<DomRoot<Gamepad>> { - self.gamepads.borrow() - .iter() - .find(|g| g.gamepad_id() == gamepad_id) - .map(|g| DomRoot::from_ref(&**g)) + self.gamepads + .borrow() + .iter() + .find(|g| g.gamepad_id() == gamepad_id) + .map(|g| DomRoot::from_ref(&**g)) } fn sync_gamepad(&self, data: Option<WebVRGamepadData>, state: &WebVRGamepadState) { @@ -217,10 +224,7 @@ impl VR { } else { let index = self.gamepads.borrow().len(); let data = data.unwrap_or_default(); - let root = Gamepad::new_from_vr(&self.global(), - index as i32, - &data, - &state); + let root = Gamepad::new_from_vr(&self.global(), index as i32, &data, &state); self.gamepads.borrow_mut().push(Dom::from_ref(&*root)); if state.connected { root.notify_event(GamepadEventType::Connected); @@ -234,9 +238,17 @@ impl VR { // motion capture or drawing applications. pub fn get_gamepads(&self) -> Vec<DomRoot<Gamepad>> { if let Some(wevbr_sender) = self.webvr_thread() { - let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); - let synced_ids = self.gamepads.borrow().iter().map(|g| g.gamepad_id()).collect(); - wevbr_sender.send(WebVRMsg::GetGamepads(synced_ids, sender)).unwrap(); + let (sender, receiver) = + ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); + let synced_ids = self + .gamepads + .borrow() + .iter() + .map(|g| g.gamepad_id()) + .collect(); + wevbr_sender + .send(WebVRMsg::GetGamepads(synced_ids, sender)) + .unwrap(); match receiver.recv().unwrap() { Ok(gamepads) => { // Sync displays @@ -244,13 +256,15 @@ impl VR { self.sync_gamepad(gamepad.0, &gamepad.1); } }, - Err(_) => {} + Err(_) => {}, } } // We can add other not VR related gamepad providers here - self.gamepads.borrow().iter() - .map(|g| DomRoot::from_ref(&**g)) - .collect() + self.gamepads + .borrow() + .iter() + .map(|g| DomRoot::from_ref(&**g)) + .collect() } } diff --git a/components/script/dom/vrdisplay.rs b/components/script/dom/vrdisplay.rs index d44d9d0fa22..9efd763989e 100644 --- a/components/script/dom/vrdisplay.rs +++ b/components/script/dom/vrdisplay.rs @@ -84,7 +84,7 @@ unsafe_no_jsmanaged_fields!(WebVRLayer); enum VRFrameDataStatus { Waiting, Synced, - Exit + Exit, } unsafe_no_jsmanaged_fields!(VRFrameDataStatus); @@ -93,7 +93,7 @@ impl VRDisplay { fn new_inherited(global: &GlobalScope, display: WebVRDisplayData) -> VRDisplay { let stage = match display.stage_parameters { Some(ref params) => Some(VRStageParameters::new(params.clone(), &global)), - None => None + None => None, }; VRDisplay { @@ -102,9 +102,18 @@ impl VRDisplay { depth_near: Cell::new(0.01), depth_far: Cell::new(10000.0), presenting: Cell::new(false), - left_eye_params: MutDom::new(&*VREyeParameters::new(display.left_eye_parameters.clone(), &global)), - right_eye_params: MutDom::new(&*VREyeParameters::new(display.right_eye_parameters.clone(), &global)), - capabilities: MutDom::new(&*VRDisplayCapabilities::new(display.capabilities.clone(), &global)), + left_eye_params: MutDom::new(&*VREyeParameters::new( + display.left_eye_parameters.clone(), + &global, + )), + right_eye_params: MutDom::new(&*VREyeParameters::new( + display.right_eye_parameters.clone(), + &global, + )), + capabilities: MutDom::new(&*VRDisplayCapabilities::new( + display.capabilities.clone(), + &global, + )), stage_params: MutNullableDom::new(stage.as_ref().map(|v| v.deref())), frame_data: DomRefCell::new(Default::default()), layer: DomRefCell::new(Default::default()), @@ -119,14 +128,16 @@ impl VRDisplay { paused: Cell::new(false), // This flag is set when the Display was presenting when it received a VR Pause event. // When the VR Resume event is received and the flag is set, VR presentation automatically restarts. - stopped_on_pause: Cell::new(false) + stopped_on_pause: Cell::new(false), } } pub fn new(global: &GlobalScope, display: WebVRDisplayData) -> DomRoot<VRDisplay> { - reflect_dom_object(Box::new(VRDisplay::new_inherited(&global, display)), - global, - VRDisplayBinding::Wrap) + reflect_dom_object( + Box::new(VRDisplay::new_inherited(&global, display)), + global, + VRDisplayBinding::Wrap, + ) } } @@ -163,7 +174,7 @@ impl VRDisplayMethods for VRDisplay { fn GetEyeParameters(&self, eye: VREye) -> DomRoot<VREyeParameters> { match eye { VREye::Left => DomRoot::from_ref(&*self.left_eye_params.get()), - VREye::Right => DomRoot::from_ref(&*self.right_eye_params.get()) + VREye::Right => DomRoot::from_ref(&*self.right_eye_params.get()), } } @@ -189,17 +200,20 @@ impl VRDisplayMethods for VRDisplay { if self.frame_data_status.get() == VRFrameDataStatus::Waiting { self.sync_frame_data(); } - frameData.update(& self.frame_data.borrow()); + frameData.update(&self.frame_data.borrow()); return true; } // If not presenting we fetch inmediante VRFrameData let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); - self.webvr_thread().send(WebVRMsg::GetFrameData(self.global().pipeline_id(), - self.DisplayId(), - self.depth_near.get(), - self.depth_far.get(), - sender)).unwrap(); + self.webvr_thread() + .send(WebVRMsg::GetFrameData( + self.global().pipeline_id(), + self.DisplayId(), + self.depth_near.get(), + self.depth_far.get(), + sender, + )).unwrap(); return match receiver.recv().unwrap() { Ok(data) => { frameData.update(&data); @@ -208,7 +222,7 @@ impl VRDisplayMethods for VRDisplay { Err(e) => { error!("WebVR::GetFrameData: {:?}", e); false - } + }, }; } @@ -220,9 +234,12 @@ impl VRDisplayMethods for VRDisplay { // https://w3c.github.io/webvr/#dom-vrdisplay-resetpose fn ResetPose(&self) { let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); - self.webvr_thread().send(WebVRMsg::ResetPose(self.global().pipeline_id(), - self.DisplayId(), - sender)).unwrap(); + self.webvr_thread() + .send(WebVRMsg::ResetPose( + self.global().pipeline_id(), + self.DisplayId(), + sender, + )).unwrap(); if let Ok(data) = receiver.recv().unwrap() { // Some VRDisplay data might change after calling ResetPose() *self.display.borrow_mut() = data; @@ -254,7 +271,9 @@ impl VRDisplayMethods for VRDisplay { if self.presenting.get() { let raf_id = self.next_raf_id.get(); self.next_raf_id.set(raf_id + 1); - self.raf_callback_list.borrow_mut().push((raf_id, Some(callback))); + self.raf_callback_list + .borrow_mut() + .push((raf_id, Some(callback))); raf_id } else { // WebVR spec: When a VRDisplay is not presenting it should @@ -315,7 +334,7 @@ impl VRDisplayMethods for VRDisplay { let msg = msg.to_string(); promise.reject_native(&msg); return promise; - } + }, }; // WebVR spec: Repeat calls while already presenting will update the VRLayers being displayed. @@ -328,10 +347,12 @@ impl VRDisplayMethods for VRDisplay { // Request Present let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); - self.webvr_thread().send(WebVRMsg::RequestPresent(self.global().pipeline_id(), - self.display.borrow().display_id, - sender)) - .unwrap(); + self.webvr_thread() + .send(WebVRMsg::RequestPresent( + self.global().pipeline_id(), + self.display.borrow().display_id, + sender, + )).unwrap(); match receiver.recv().unwrap() { Ok(()) => { *self.layer.borrow_mut() = layer_bounds; @@ -341,7 +362,7 @@ impl VRDisplayMethods for VRDisplay { }, Err(e) => { promise.reject_native(&e); - } + }, } promise @@ -361,10 +382,12 @@ impl VRDisplayMethods for VRDisplay { // Exit present let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap(); - self.webvr_thread().send(WebVRMsg::ExitPresent(self.global().pipeline_id(), - self.display.borrow().display_id, - Some(sender))) - .unwrap(); + self.webvr_thread() + .send(WebVRMsg::ExitPresent( + self.global().pipeline_id(), + self.display.borrow().display_id, + Some(sender), + )).unwrap(); match receiver.recv().unwrap() { Ok(()) => { self.stop_present(); @@ -372,7 +395,7 @@ impl VRDisplayMethods for VRDisplay { }, Err(e) => { promise.reject_native(&e); - } + }, } promise @@ -410,7 +433,10 @@ impl VRDisplayMethods for VRDisplay { impl VRDisplay { fn webvr_thread(&self) -> IpcSender<WebVRMsg> { - self.global().as_window().webvr_thread().expect("Shouldn't arrive here with WebVR disabled") + self.global() + .as_window() + .webvr_thread() + .expect("Shouldn't arrive here with WebVR disabled") } pub fn update_display(&self, display: &WebVRDisplayData) { @@ -461,7 +487,6 @@ impl VRDisplay { self.stop_present(); self.stopped_on_pause.set(true); } - }, WebVRDisplayEvent::Resume(_) => { self.paused.set(false); @@ -475,14 +500,16 @@ impl VRDisplay { if self.presenting.get() { self.stop_present(); } - } + }, }; } fn notify_event(&self, event: &WebVRDisplayEvent) { let root = DomRoot::from_ref(&*self); let event = VRDisplayEvent::new_from_webvr(&self.global(), &root, &event); - event.upcast::<Event>().fire(self.global().upcast::<EventTarget>()); + event + .upcast::<Event>() + .fire(self.global().upcast::<EventTarget>()); } fn init_present(&self) { @@ -504,44 +531,49 @@ impl VRDisplay { // in the Webrender thread are executed in parallel. This allows to get some JavaScript code executed ahead. // while the render thread is syncing the VRFrameData to be used for the current frame. // This thread runs until the user calls ExitPresent, the tab is closed or some unexpected error happened. - thread::Builder::new().name("WebVR_RAF".into()).spawn(move || { - let (raf_sender, raf_receiver) = channel(); - let mut near = near_init; - let mut far = far_init; - - // Initialize compositor - api_sender.send_vr(WebVRCommand::Create(display_id)).unwrap(); - loop { - // Run RAF callbacks on JavaScript thread - let this = address.clone(); - let sender = raf_sender.clone(); - let task = Box::new(task!(handle_vrdisplay_raf: move || { + thread::Builder::new() + .name("WebVR_RAF".into()) + .spawn(move || { + let (raf_sender, raf_receiver) = channel(); + let mut near = near_init; + let mut far = far_init; + + // Initialize compositor + api_sender + .send_vr(WebVRCommand::Create(display_id)) + .unwrap(); + loop { + // Run RAF callbacks on JavaScript thread + let this = address.clone(); + let sender = raf_sender.clone(); + let task = Box::new(task!(handle_vrdisplay_raf: move || { this.root().handle_raf(&sender); })); - // NOTE: WebVR spec doesn't specify what task source we should use. Is - // dom-manipulation a good choice long term? - js_sender.send(CommonScriptMsg::Task( - WebVREvent, - task, - Some(pipeline_id), - TaskSourceName::DOMManipulation, - )).unwrap(); - - // Run Sync Poses in parallell on Render thread - let msg = WebVRCommand::SyncPoses(display_id, near, far, sync_sender.clone()); - api_sender.send_vr(msg).unwrap(); - - // Wait until both SyncPoses & RAF ends - if let Ok(depth) = raf_receiver.recv().unwrap() { - near = depth.0; - far = depth.1; - } else { - // Stop thread - // ExitPresent called or some error happened - return; + // NOTE: WebVR spec doesn't specify what task source we should use. Is + // dom-manipulation a good choice long term? + js_sender + .send(CommonScriptMsg::Task( + WebVREvent, + task, + Some(pipeline_id), + TaskSourceName::DOMManipulation, + )).unwrap(); + + // Run Sync Poses in parallell on Render thread + let msg = WebVRCommand::SyncPoses(display_id, near, far, sync_sender.clone()); + api_sender.send_vr(msg).unwrap(); + + // Wait until both SyncPoses & RAF ends + if let Ok(depth) = raf_receiver.recv().unwrap() { + near = depth.0; + far = depth.1; + } else { + // Stop thread + // ExitPresent called or some error happened + return; + } } - } - }).expect("Thread spawning failed"); + }).expect("Thread spawning failed"); } fn stop_present(&self) { @@ -550,16 +582,20 @@ impl VRDisplay { let api_sender = self.layer_ctx.get().unwrap().webgl_sender(); let display_id = self.display.borrow().display_id; - api_sender.send_vr(WebVRCommand::Release(display_id)).unwrap(); + api_sender + .send_vr(WebVRCommand::Release(display_id)) + .unwrap(); } // Only called when the JSContext is destroyed while presenting. // In this case we don't want to wait for WebVR Thread response. fn force_stop_present(&self) { - self.webvr_thread().send(WebVRMsg::ExitPresent(self.global().pipeline_id(), - self.display.borrow().display_id, - None)) - .unwrap(); + self.webvr_thread() + .send(WebVRMsg::ExitPresent( + self.global().pipeline_id(), + self.display.borrow().display_id, + None, + )).unwrap(); self.stop_present(); } @@ -570,9 +606,7 @@ impl VRDisplay { *self.frame_data.borrow_mut() = WebVRFrameData::from_bytes(&bytes[..]); VRFrameDataStatus::Synced }, - Err(()) => { - VRFrameDataStatus::Exit - } + Err(()) => VRFrameDataStatus::Exit, } } else { VRFrameDataStatus::Exit @@ -607,13 +641,15 @@ impl VRDisplay { match self.frame_data_status.get() { VRFrameDataStatus::Synced => { // Sync succeeded. Notify RAF thread. - end_sender.send(Ok((self.depth_near.get(), self.depth_far.get()))).unwrap(); + end_sender + .send(Ok((self.depth_near.get(), self.depth_far.get()))) + .unwrap(); }, VRFrameDataStatus::Exit | VRFrameDataStatus::Waiting => { // ExitPresent called or some error ocurred. // Notify VRDisplay RAF thread to stop. end_sender.send(Err(())).unwrap(); - } + }, } } } @@ -624,22 +660,30 @@ fn parse_bounds(src: &Option<Vec<Finite<f32>>>, dst: &mut [f32; 4]) -> Result<() match *src { Some(ref values) => { if values.len() == 0 { - return Ok(()) + return Ok(()); } if values.len() != 4 { - return Err("The number of values in the leftBounds/rightBounds arrays must be 0 or 4") + return Err( + "The number of values in the leftBounds/rightBounds arrays must be 0 or 4", + ); } for i in 0..4 { dst[i] = *values[i].deref(); } Ok(()) }, - None => Ok(()) + None => Ok(()), } } -fn validate_layer(layer: &VRLayer) -> Result<(WebVRLayer, DomRoot<WebGLRenderingContext>), &'static str> { - let ctx = layer.source.as_ref().map(|ref s| s.get_base_webgl_context()).unwrap_or(None); +fn validate_layer( + layer: &VRLayer, +) -> Result<(WebVRLayer, DomRoot<WebGLRenderingContext>), &'static str> { + let ctx = layer + .source + .as_ref() + .map(|ref s| s.get_base_webgl_context()) + .unwrap_or(None); if let Some(ctx) = ctx { let mut data = WebVRLayer::default(); parse_bounds(&layer.leftBounds, &mut data.left_bounds)?; @@ -651,8 +695,10 @@ fn validate_layer(layer: &VRLayer) -> Result<(WebVRLayer, DomRoot<WebGLRendering } fn bounds_to_vec(src: &[f32; 4]) -> Vec<Finite<f32>> { - vec![Finite::wrap(src[0]), - Finite::wrap(src[1]), - Finite::wrap(src[2]), - Finite::wrap(src[3])] + vec![ + Finite::wrap(src[0]), + Finite::wrap(src[1]), + Finite::wrap(src[2]), + Finite::wrap(src[3]), + ] } diff --git a/components/script/dom/vrdisplaycapabilities.rs b/components/script/dom/vrdisplaycapabilities.rs index ef1f1d7f275..4b1b2132555 100644 --- a/components/script/dom/vrdisplaycapabilities.rs +++ b/components/script/dom/vrdisplaycapabilities.rs @@ -15,7 +15,7 @@ use webvr_traits::WebVRDisplayCapabilities; pub struct VRDisplayCapabilities { reflector_: Reflector, #[ignore_malloc_size_of = "Defined in rust-webvr"] - capabilities: DomRefCell<WebVRDisplayCapabilities> + capabilities: DomRefCell<WebVRDisplayCapabilities>, } unsafe_no_jsmanaged_fields!(WebVRDisplayCapabilities); @@ -24,14 +24,19 @@ impl VRDisplayCapabilities { fn new_inherited(capabilities: WebVRDisplayCapabilities) -> VRDisplayCapabilities { VRDisplayCapabilities { reflector_: Reflector::new(), - capabilities: DomRefCell::new(capabilities) + capabilities: DomRefCell::new(capabilities), } } - pub fn new(capabilities: WebVRDisplayCapabilities, global: &GlobalScope) -> DomRoot<VRDisplayCapabilities> { - reflect_dom_object(Box::new(VRDisplayCapabilities::new_inherited(capabilities)), - global, - VRDisplayCapabilitiesBinding::Wrap) + pub fn new( + capabilities: WebVRDisplayCapabilities, + global: &GlobalScope, + ) -> DomRoot<VRDisplayCapabilities> { + reflect_dom_object( + Box::new(VRDisplayCapabilities::new_inherited(capabilities)), + global, + VRDisplayCapabilitiesBinding::Wrap, + ) } } @@ -58,6 +63,10 @@ impl VRDisplayCapabilitiesMethods for VRDisplayCapabilities { // https://w3c.github.io/webvr/#dom-vrdisplaycapabilities-maxlayers fn MaxLayers(&self) -> u32 { - if self.CanPresent() { 1 } else { 0 } + if self.CanPresent() { + 1 + } else { + 0 + } } } diff --git a/components/script/dom/vrdisplayevent.rs b/components/script/dom/vrdisplayevent.rs index 41ff8fd0859..b5776080ce8 100644 --- a/components/script/dom/vrdisplayevent.rs +++ b/components/script/dom/vrdisplayevent.rs @@ -23,31 +23,30 @@ use webvr_traits::{WebVRDisplayEvent, WebVRDisplayEventReason}; pub struct VRDisplayEvent { event: Event, display: Dom<VRDisplay>, - reason: Option<VRDisplayEventReason> + reason: Option<VRDisplayEventReason>, } impl VRDisplayEvent { - fn new_inherited(display: &VRDisplay, - reason: Option<VRDisplayEventReason>) - -> VRDisplayEvent { + fn new_inherited(display: &VRDisplay, reason: Option<VRDisplayEventReason>) -> VRDisplayEvent { VRDisplayEvent { event: Event::new_inherited(), display: Dom::from_ref(display), - reason: reason.clone() + reason: reason.clone(), } } - pub fn new(global: &GlobalScope, - type_: Atom, - bubbles: bool, - cancelable: bool, - display: &VRDisplay, - reason: Option<VRDisplayEventReason>) - -> DomRoot<VRDisplayEvent> { + pub fn new( + global: &GlobalScope, + type_: Atom, + bubbles: bool, + cancelable: bool, + display: &VRDisplay, + reason: Option<VRDisplayEventReason>, + ) -> DomRoot<VRDisplayEvent> { let ev = reflect_dom_object( Box::new(VRDisplayEvent::new_inherited(&display, reason)), global, - VRDisplayEventBinding::Wrap + VRDisplayEventBinding::Wrap, ); { let event = ev.upcast::<Event>(); @@ -56,10 +55,11 @@ impl VRDisplayEvent { ev } - pub fn new_from_webvr(global: &GlobalScope, - display: &VRDisplay, - event: &WebVRDisplayEvent) - -> DomRoot<VRDisplayEvent> { + pub fn new_from_webvr( + global: &GlobalScope, + display: &VRDisplay, + event: &WebVRDisplayEvent, + ) -> DomRoot<VRDisplayEvent> { let (name, reason) = match *event { WebVRDisplayEvent::Connect(_) => ("vrdisplayconnect", None), WebVRDisplayEvent::Disconnect(_) => ("vrdisplaydisconnect", None), @@ -71,38 +71,39 @@ impl VRDisplayEvent { WebVRDisplayEvent::Change(_) | WebVRDisplayEvent::Pause(_) | WebVRDisplayEvent::Resume(_) | - WebVRDisplayEvent::Exit(_) => { - panic!("{:?} event not available in WebVR", event) - } + WebVRDisplayEvent::Exit(_) => panic!("{:?} event not available in WebVR", event), }; // map to JS enum values - let reason = reason.map(|r| { - match r { - WebVRDisplayEventReason::Navigation => VRDisplayEventReason::Navigation, - WebVRDisplayEventReason::Mounted => VRDisplayEventReason::Mounted, - WebVRDisplayEventReason::Unmounted => VRDisplayEventReason::Unmounted, - } + let reason = reason.map(|r| match r { + WebVRDisplayEventReason::Navigation => VRDisplayEventReason::Navigation, + WebVRDisplayEventReason::Mounted => VRDisplayEventReason::Mounted, + WebVRDisplayEventReason::Unmounted => VRDisplayEventReason::Unmounted, }); - VRDisplayEvent::new(&global, - Atom::from(DOMString::from(name)), - false, - false, - &display, - reason) + VRDisplayEvent::new( + &global, + Atom::from(DOMString::from(name)), + false, + false, + &display, + reason, + ) } - pub fn Constructor(window: &Window, - type_: DOMString, - init: &VRDisplayEventBinding::VRDisplayEventInit) - -> Fallible<DomRoot<VRDisplayEvent>> { - Ok(VRDisplayEvent::new(&window.global(), - Atom::from(type_), - init.parent.bubbles, - init.parent.cancelable, - &init.display, - init.reason)) + pub fn Constructor( + window: &Window, + type_: DOMString, + init: &VRDisplayEventBinding::VRDisplayEventInit, + ) -> Fallible<DomRoot<VRDisplayEvent>> { + Ok(VRDisplayEvent::new( + &window.global(), + Atom::from(type_), + init.parent.bubbles, + init.parent.cancelable, + &init.display, + init.reason, + )) } } diff --git a/components/script/dom/vreyeparameters.rs b/components/script/dom/vreyeparameters.rs index 333c717f06b..18fc221db03 100644 --- a/components/script/dom/vreyeparameters.rs +++ b/components/script/dom/vreyeparameters.rs @@ -34,7 +34,7 @@ impl VREyeParameters { reflector_: Reflector::new(), parameters: DomRefCell::new(parameters), offset: Heap::default(), - fov: Dom::from_ref(&*fov) + fov: Dom::from_ref(&*fov), } } @@ -45,12 +45,18 @@ impl VREyeParameters { let cx = global.get_cx(); rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); unsafe { - let _ = Float32Array::create(cx, CreateWith::Slice(¶meters.offset), array.handle_mut()); + let _ = Float32Array::create( + cx, + CreateWith::Slice(¶meters.offset), + array.handle_mut(), + ); } - let eye_parameters = reflect_dom_object(Box::new(VREyeParameters::new_inherited(parameters, &fov)), - global, - VREyeParametersBinding::Wrap); + let eye_parameters = reflect_dom_object( + Box::new(VREyeParameters::new_inherited(parameters, &fov)), + global, + VREyeParametersBinding::Wrap, + ); eye_parameters.offset.set(array.get()); eye_parameters diff --git a/components/script/dom/vrfieldofview.rs b/components/script/dom/vrfieldofview.rs index eb798bafc8a..c33d6387011 100644 --- a/components/script/dom/vrfieldofview.rs +++ b/components/script/dom/vrfieldofview.rs @@ -16,7 +16,7 @@ use webvr_traits::WebVRFieldOfView; pub struct VRFieldOfView { reflector_: Reflector, #[ignore_malloc_size_of = "Defined in rust-webvr"] - fov: DomRefCell<WebVRFieldOfView> + fov: DomRefCell<WebVRFieldOfView>, } unsafe_no_jsmanaged_fields!(WebVRFieldOfView); @@ -25,14 +25,16 @@ impl VRFieldOfView { fn new_inherited(fov: WebVRFieldOfView) -> VRFieldOfView { VRFieldOfView { reflector_: Reflector::new(), - fov: DomRefCell::new(fov) + fov: DomRefCell::new(fov), } } pub fn new(global: &GlobalScope, fov: WebVRFieldOfView) -> DomRoot<VRFieldOfView> { - reflect_dom_object(Box::new(VRFieldOfView::new_inherited(fov)), - global, - VRFieldOfViewBinding::Wrap) + reflect_dom_object( + Box::new(VRFieldOfView::new_inherited(fov)), + global, + VRFieldOfViewBinding::Wrap, + ) } } diff --git a/components/script/dom/vrframedata.rs b/components/script/dom/vrframedata.rs index 621f70a55c9..dc251165e51 100644 --- a/components/script/dom/vrframedata.rs +++ b/components/script/dom/vrframedata.rs @@ -28,7 +28,7 @@ pub struct VRFrameData { right_view: Heap<*mut JSObject>, pose: Dom<VRPose>, timestamp: Cell<f64>, - first_timestamp: Cell<f64> + first_timestamp: Cell<f64>, } impl VRFrameData { @@ -41,21 +41,22 @@ impl VRFrameData { right_view: Heap::default(), pose: Dom::from_ref(&*pose), timestamp: Cell::new(0.0), - first_timestamp: Cell::new(0.0) + first_timestamp: Cell::new(0.0), } } #[allow(unsafe_code)] fn new(global: &GlobalScope) -> DomRoot<VRFrameData> { - let matrix = [1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0f32]; + let matrix = [ + 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0f32, + ]; let pose = VRPose::new(&global, &Default::default()); - let root = reflect_dom_object(Box::new(VRFrameData::new_inherited(&pose)), - global, - VRFrameDataBinding::Wrap); + let root = reflect_dom_object( + Box::new(VRFrameData::new_inherited(&pose)), + global, + VRFrameDataBinding::Wrap, + ); let cx = global.get_cx(); create_typed_array(cx, &matrix, &root.left_proj); create_typed_array(cx, &matrix, &root.left_view); @@ -70,7 +71,6 @@ impl VRFrameData { } } - #[allow(unsafe_code)] fn create_typed_array(cx: *mut JSContext, src: &[f32], dst: &Heap<*mut JSObject>) { rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); diff --git a/components/script/dom/vrpose.rs b/components/script/dom/vrpose.rs index 01778471ccb..75faa41d20c 100644 --- a/components/script/dom/vrpose.rs +++ b/components/script/dom/vrpose.rs @@ -26,9 +26,11 @@ pub struct VRPose { } #[allow(unsafe_code)] -unsafe fn update_or_create_typed_array(cx: *mut JSContext, - src: Option<&[f32]>, - dst: &Heap<*mut JSObject>) { +unsafe fn update_or_create_typed_array( + cx: *mut JSContext, + src: Option<&[f32]>, + dst: &Heap<*mut JSObject>, +) { match src { Some(data) => { if dst.get().is_null() { @@ -46,7 +48,7 @@ unsafe fn update_or_create_typed_array(cx: *mut JSContext, if !dst.get().is_null() { dst.set(ptr::null_mut()); } - } + }, } } @@ -57,9 +59,7 @@ fn heap_to_option(heap: &Heap<*mut JSObject>) -> Option<NonNull<JSObject>> { if js_object.is_null() { None } else { - unsafe { - Some(NonNull::new_unchecked(js_object)) - } + unsafe { Some(NonNull::new_unchecked(js_object)) } } } @@ -77,9 +77,11 @@ impl VRPose { } pub fn new(global: &GlobalScope, pose: &webvr::VRPose) -> DomRoot<VRPose> { - let root = reflect_dom_object(Box::new(VRPose::new_inherited()), - global, - VRPoseBinding::Wrap); + let root = reflect_dom_object( + Box::new(VRPose::new_inherited()), + global, + VRPoseBinding::Wrap, + ); root.update(&pose); root } @@ -88,12 +90,36 @@ impl VRPose { pub fn update(&self, pose: &webvr::VRPose) { let cx = self.global().get_cx(); unsafe { - update_or_create_typed_array(cx, pose.position.as_ref().map(|v| &v[..]), &self.position); - update_or_create_typed_array(cx, pose.orientation.as_ref().map(|v| &v[..]), &self.orientation); - update_or_create_typed_array(cx, pose.linear_velocity.as_ref().map(|v| &v[..]), &self.linear_vel); - update_or_create_typed_array(cx, pose.angular_velocity.as_ref().map(|v| &v[..]), &self.angular_vel); - update_or_create_typed_array(cx, pose.linear_acceleration.as_ref().map(|v| &v[..]), &self.linear_acc); - update_or_create_typed_array(cx, pose.angular_acceleration.as_ref().map(|v| &v[..]), &self.angular_acc); + update_or_create_typed_array( + cx, + pose.position.as_ref().map(|v| &v[..]), + &self.position, + ); + update_or_create_typed_array( + cx, + pose.orientation.as_ref().map(|v| &v[..]), + &self.orientation, + ); + update_or_create_typed_array( + cx, + pose.linear_velocity.as_ref().map(|v| &v[..]), + &self.linear_vel, + ); + update_or_create_typed_array( + cx, + pose.angular_velocity.as_ref().map(|v| &v[..]), + &self.angular_vel, + ); + update_or_create_typed_array( + cx, + pose.linear_acceleration.as_ref().map(|v| &v[..]), + &self.linear_acc, + ); + update_or_create_typed_array( + cx, + pose.angular_acceleration.as_ref().map(|v| &v[..]), + &self.angular_acc, + ); } } } diff --git a/components/script/dom/vrstageparameters.rs b/components/script/dom/vrstageparameters.rs index bd4dfa5a3a6..61d31036b91 100644 --- a/components/script/dom/vrstageparameters.rs +++ b/components/script/dom/vrstageparameters.rs @@ -31,22 +31,30 @@ impl VRStageParameters { VRStageParameters { reflector_: Reflector::new(), parameters: DomRefCell::new(parameters), - transform: Heap::default() + transform: Heap::default(), } } #[allow(unsafe_code)] - pub fn new(parameters: WebVRStageParameters, global: &GlobalScope) -> DomRoot<VRStageParameters> { + pub fn new( + parameters: WebVRStageParameters, + global: &GlobalScope, + ) -> DomRoot<VRStageParameters> { let cx = global.get_cx(); rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); unsafe { - let _ = Float32Array::create(cx, CreateWith::Slice(¶meters.sitting_to_standing_transform), - array.handle_mut()); + let _ = Float32Array::create( + cx, + CreateWith::Slice(¶meters.sitting_to_standing_transform), + array.handle_mut(), + ); } - let stage_parameters = reflect_dom_object(Box::new(VRStageParameters::new_inherited(parameters)), - global, - VRStageParametersBinding::Wrap); + let stage_parameters = reflect_dom_object( + Box::new(VRStageParameters::new_inherited(parameters)), + global, + VRStageParametersBinding::Wrap, + ); stage_parameters.transform.set(array.get()); diff --git a/components/script/dom/webgl2renderingcontext.rs b/components/script/dom/webgl2renderingcontext.rs index da50ed556df..a674cd719a6 100644 --- a/components/script/dom/webgl2renderingcontext.rs +++ b/components/script/dom/webgl2renderingcontext.rs @@ -50,7 +50,7 @@ impl WebGL2RenderingContext { window: &Window, canvas: &HTMLCanvasElement, size: Size2D<i32>, - attrs: GLContextAttributes + attrs: GLContextAttributes, ) -> Option<WebGL2RenderingContext> { let base = WebGLRenderingContext::new(window, canvas, WebGLVersion::WebGL2, size, attrs)?; Some(WebGL2RenderingContext { @@ -64,7 +64,7 @@ impl WebGL2RenderingContext { window: &Window, canvas: &HTMLCanvasElement, size: Size2D<i32>, - attrs: GLContextAttributes + attrs: GLContextAttributes, ) -> Option<DomRoot<WebGL2RenderingContext>> { WebGL2RenderingContext::new_inherited(window, canvas, size, attrs).map(|ctx| { reflect_dom_object(Box::new(ctx), window, WebGL2RenderingContextBinding::Wrap) @@ -143,7 +143,11 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { #[allow(unsafe_code)] /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14 - unsafe fn GetExtension(&self, cx: *mut JSContext, name: DOMString) -> Option<NonNull<JSObject>> { + unsafe fn GetExtension( + &self, + cx: *mut JSContext, + name: DOMString, + ) -> Option<NonNull<JSObject>> { self.base.GetExtension(cx, name) } @@ -154,9 +158,10 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { cx: *mut JSContext, target: u32, attachment: u32, - pname: u32 + pname: u32, ) -> JSVal { - self.base.GetFramebufferAttachmentParameter(cx, target, attachment, pname) + self.base + .GetFramebufferAttachmentParameter(cx, target, attachment, pname) } #[allow(unsafe_code)] @@ -165,7 +170,7 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { &self, cx: *mut JSContext, target: u32, - pname: u32 + pname: u32, ) -> JSVal { self.base.GetRenderbufferParameter(cx, target, pname) } @@ -197,7 +202,8 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn BlendFuncSeparate(&self, src_rgb: u32, dest_rgb: u32, src_alpha: u32, dest_alpha: u32) { - self.base.BlendFuncSeparate(src_rgb, dest_rgb, src_alpha, dest_alpha) + self.base + .BlendFuncSeparate(src_rgb, dest_rgb, src_alpha, dest_alpha) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 @@ -241,12 +247,7 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 - fn BufferData( - &self, - target: u32, - data: Option<ArrayBufferViewOrArrayBuffer>, - usage: u32, - ) { + fn BufferData(&self, target: u32, data: Option<ArrayBufferViewOrArrayBuffer>, usage: u32) { self.base.BufferData(target, data, usage) } @@ -261,29 +262,74 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn CompressedTexImage2D(&self, target: u32, level: i32, internal_format: u32, - width: i32, height: i32, border: i32, - pixels: CustomAutoRooterGuard<ArrayBufferView>) { - self.base.CompressedTexImage2D(target, level, internal_format, width, height, border, pixels) + fn CompressedTexImage2D( + &self, + target: u32, + level: i32, + internal_format: u32, + width: i32, + height: i32, + border: i32, + pixels: CustomAutoRooterGuard<ArrayBufferView>, + ) { + self.base.CompressedTexImage2D( + target, + level, + internal_format, + width, + height, + border, + pixels, + ) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn CompressedTexSubImage2D(&self, target: u32, level: i32, xoffset: i32, - yoffset: i32, width: i32, height: i32, format: u32, - pixels: CustomAutoRooterGuard<ArrayBufferView>) { - self.base.CompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, pixels) + fn CompressedTexSubImage2D( + &self, + target: u32, + level: i32, + xoffset: i32, + yoffset: i32, + width: i32, + height: i32, + format: u32, + pixels: CustomAutoRooterGuard<ArrayBufferView>, + ) { + self.base.CompressedTexSubImage2D( + target, level, xoffset, yoffset, width, height, format, pixels, + ) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn CopyTexImage2D(&self, target: u32, level: i32, internal_format: u32, - x: i32, y: i32, width: i32, height: i32, border: i32) { - self.base.CopyTexImage2D(target, level, internal_format, x, y, width, height, border) + fn CopyTexImage2D( + &self, + target: u32, + level: i32, + internal_format: u32, + x: i32, + y: i32, + width: i32, + height: i32, + border: i32, + ) { + self.base + .CopyTexImage2D(target, level, internal_format, x, y, width, height, border) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn CopyTexSubImage2D(&self, target: u32, level: i32, xoffset: i32, yoffset: i32, - x: i32, y: i32, width: i32, height: i32) { - self.base.CopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height) + fn CopyTexSubImage2D( + &self, + target: u32, + level: i32, + xoffset: i32, + yoffset: i32, + x: i32, + y: i32, + width: i32, + height: i32, + ) { + self.base + .CopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11 @@ -431,12 +477,20 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn GetActiveUniform(&self, program: &WebGLProgram, index: u32) -> Option<DomRoot<WebGLActiveInfo>> { + fn GetActiveUniform( + &self, + program: &WebGLProgram, + index: u32, + ) -> Option<DomRoot<WebGLActiveInfo>> { self.base.GetActiveUniform(program, index) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn GetActiveAttrib(&self, program: &WebGLProgram, index: u32) -> Option<DomRoot<WebGLActiveInfo>> { + fn GetActiveAttrib( + &self, + program: &WebGLProgram, + index: u32, + ) -> Option<DomRoot<WebGLActiveInfo>> { self.base.GetActiveAttrib(program, index) } @@ -452,7 +506,12 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { #[allow(unsafe_code)] /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - unsafe fn GetProgramParameter(&self, cx: *mut JSContext, program: &WebGLProgram, param_id: u32) -> JSVal { + unsafe fn GetProgramParameter( + &self, + cx: *mut JSContext, + program: &WebGLProgram, + param_id: u32, + ) -> JSVal { self.base.GetProgramParameter(cx, program, param_id) } @@ -463,16 +522,23 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { #[allow(unsafe_code)] /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - unsafe fn GetShaderParameter(&self, cx: *mut JSContext, shader: &WebGLShader, param_id: u32) -> JSVal { + unsafe fn GetShaderParameter( + &self, + cx: *mut JSContext, + shader: &WebGLShader, + param_id: u32, + ) -> JSVal { self.base.GetShaderParameter(cx, shader, param_id) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - fn GetShaderPrecisionFormat(&self, - shader_type: u32, - precision_type: u32) - -> Option<DomRoot<WebGLShaderPrecisionFormat>> { - self.base.GetShaderPrecisionFormat(shader_type, precision_type) + fn GetShaderPrecisionFormat( + &self, + shader_type: u32, + precision_type: u32, + ) -> Option<DomRoot<WebGLShaderPrecisionFormat>> { + self.base + .GetShaderPrecisionFormat(shader_type, precision_type) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 @@ -552,9 +618,18 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.12 - fn ReadPixels(&self, x: i32, y: i32, width: i32, height: i32, format: u32, pixel_type: u32, - pixels: CustomAutoRooterGuard<Option<ArrayBufferView>>) { - self.base.ReadPixels(x, y, width, height, format, pixel_type, pixels) + fn ReadPixels( + &self, + x: i32, + y: i32, + width: i32, + height: i32, + format: u32, + pixel_type: u32, + pixels: CustomAutoRooterGuard<Option<ArrayBufferView>>, + ) { + self.base + .ReadPixels(x, y, width, height, format, pixel_type, pixels) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 @@ -613,25 +688,17 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform1f(&self, - location: Option<&WebGLUniformLocation>, - val: f32) { + fn Uniform1f(&self, location: Option<&WebGLUniformLocation>, val: f32) { self.base.Uniform1f(location, val) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform1i(&self, - location: Option<&WebGLUniformLocation>, - val: i32) { + fn Uniform1i(&self, location: Option<&WebGLUniformLocation>, val: i32) { self.base.Uniform1i(location, val) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform1iv( - &self, - location: Option<&WebGLUniformLocation>, - v: Int32ArrayOrLongSequence, - ) { + fn Uniform1iv(&self, location: Option<&WebGLUniformLocation>, v: Int32ArrayOrLongSequence) { self.base.Uniform1iv(location, v) } @@ -645,9 +712,7 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform2f(&self, - location: Option<&WebGLUniformLocation>, - x: f32, y: f32) { + fn Uniform2f(&self, location: Option<&WebGLUniformLocation>, x: f32, y: f32) { self.base.Uniform2f(location, x, y) } @@ -661,25 +726,17 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform2i(&self, - location: Option<&WebGLUniformLocation>, - x: i32, y: i32) { + fn Uniform2i(&self, location: Option<&WebGLUniformLocation>, x: i32, y: i32) { self.base.Uniform2i(location, x, y) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform2iv( - &self, - location: Option<&WebGLUniformLocation>, - v: Int32ArrayOrLongSequence, - ) { + fn Uniform2iv(&self, location: Option<&WebGLUniformLocation>, v: Int32ArrayOrLongSequence) { self.base.Uniform2iv(location, v) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform3f(&self, - location: Option<&WebGLUniformLocation>, - x: f32, y: f32, z: f32) { + fn Uniform3f(&self, location: Option<&WebGLUniformLocation>, x: f32, y: f32, z: f32) { self.base.Uniform3f(location, x, y, z) } @@ -693,41 +750,27 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform3i(&self, - location: Option<&WebGLUniformLocation>, - x: i32, y: i32, z: i32) { + fn Uniform3i(&self, location: Option<&WebGLUniformLocation>, x: i32, y: i32, z: i32) { self.base.Uniform3i(location, x, y, z) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform3iv( - &self, - location: Option<&WebGLUniformLocation>, - v: Int32ArrayOrLongSequence, - ) { + fn Uniform3iv(&self, location: Option<&WebGLUniformLocation>, v: Int32ArrayOrLongSequence) { self.base.Uniform3iv(location, v) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform4i(&self, - location: Option<&WebGLUniformLocation>, - x: i32, y: i32, z: i32, w: i32) { + fn Uniform4i(&self, location: Option<&WebGLUniformLocation>, x: i32, y: i32, z: i32, w: i32) { self.base.Uniform4i(location, x, y, z, w) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform4iv( - &self, - location: Option<&WebGLUniformLocation>, - v: Int32ArrayOrLongSequence, - ) { + fn Uniform4iv(&self, location: Option<&WebGLUniformLocation>, v: Int32ArrayOrLongSequence) { self.base.Uniform4iv(location, v) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform4f(&self, - location: Option<&WebGLUniformLocation>, - x: f32, y: f32, z: f32, w: f32) { + fn Uniform4f(&self, location: Option<&WebGLUniformLocation>, x: f32, y: f32, z: f32, w: f32) { self.base.Uniform4f(location, x, y, z, w) } @@ -832,9 +875,17 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn VertexAttribPointer(&self, attrib_id: u32, size: i32, data_type: u32, - normalized: bool, stride: i32, offset: i64) { - self.base.VertexAttribPointer(attrib_id, size, data_type, normalized, stride, offset) + fn VertexAttribPointer( + &self, + attrib_id: u32, + size: i32, + data_type: u32, + normalized: bool, + stride: i32, + offset: i64, + ) { + self.base + .VertexAttribPointer(attrib_id, size, data_type, normalized, stride, offset) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.4 @@ -843,17 +894,29 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn TexImage2D(&self, - target: u32, - level: i32, - internal_format: u32, - width: i32, - height: i32, - border: i32, - format: u32, - data_type: u32, - pixels: CustomAutoRooterGuard<Option<ArrayBufferView>>) -> Fallible<()> { - self.base.TexImage2D(target, level, internal_format, width, height, border, format, data_type, pixels) + fn TexImage2D( + &self, + target: u32, + level: i32, + internal_format: u32, + width: i32, + height: i32, + border: i32, + format: u32, + data_type: u32, + pixels: CustomAutoRooterGuard<Option<ArrayBufferView>>, + ) -> Fallible<()> { + self.base.TexImage2D( + target, + level, + internal_format, + width, + height, + border, + format, + data_type, + pixels, + ) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 @@ -866,34 +929,50 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { data_type: u32, source: ImageDataOrHTMLImageElementOrHTMLCanvasElementOrHTMLVideoElement, ) -> ErrorResult { - self.base.TexImage2D_(target, level, internal_format, format, data_type, source) + self.base + .TexImage2D_(target, level, internal_format, format, data_type, source) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn TexImageDOM(&self, - target: u32, - level: i32, - internal_format: u32, - width: i32, - height: i32, - format: u32, - data_type: u32, - source: &HTMLIFrameElement) -> Fallible<()> { - self.base.TexImageDOM(target, level, internal_format, width, height, format, data_type, source) + fn TexImageDOM( + &self, + target: u32, + level: i32, + internal_format: u32, + width: i32, + height: i32, + format: u32, + data_type: u32, + source: &HTMLIFrameElement, + ) -> Fallible<()> { + self.base.TexImageDOM( + target, + level, + internal_format, + width, + height, + format, + data_type, + source, + ) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn TexSubImage2D(&self, - target: u32, - level: i32, - xoffset: i32, - yoffset: i32, - width: i32, - height: i32, - format: u32, - data_type: u32, - pixels: CustomAutoRooterGuard<Option<ArrayBufferView>>) -> Fallible<()> { - self.base.TexSubImage2D(target, level, xoffset, yoffset, width, height, format, data_type, pixels) + fn TexSubImage2D( + &self, + target: u32, + level: i32, + xoffset: i32, + yoffset: i32, + width: i32, + height: i32, + format: u32, + data_type: u32, + pixels: CustomAutoRooterGuard<Option<ArrayBufferView>>, + ) -> Fallible<()> { + self.base.TexSubImage2D( + target, level, xoffset, yoffset, width, height, format, data_type, pixels, + ) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 @@ -907,7 +986,8 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { data_type: u32, source: ImageDataOrHTMLImageElementOrHTMLCanvasElementOrHTMLVideoElement, ) -> ErrorResult { - self.base.TexSubImage2D_(target, level, xoffset, yoffset, format, data_type, source) + self.base + .TexSubImage2D_(target, level, xoffset, yoffset, format, data_type, source) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 @@ -926,44 +1006,47 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 - fn RenderbufferStorage(&self, target: u32, internal_format: u32, - width: i32, height: i32) { - self.base.RenderbufferStorage(target, internal_format, width, height) + fn RenderbufferStorage(&self, target: u32, internal_format: u32, width: i32, height: i32) { + self.base + .RenderbufferStorage(target, internal_format, width, height) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6 - fn FramebufferRenderbuffer(&self, target: u32, attachment: u32, - renderbuffertarget: u32, - rb: Option<&WebGLRenderbuffer>) { - self.base.FramebufferRenderbuffer(target, attachment, renderbuffertarget, rb) + fn FramebufferRenderbuffer( + &self, + target: u32, + attachment: u32, + renderbuffertarget: u32, + rb: Option<&WebGLRenderbuffer>, + ) { + self.base + .FramebufferRenderbuffer(target, attachment, renderbuffertarget, rb) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6 - fn FramebufferTexture2D(&self, target: u32, attachment: u32, - textarget: u32, texture: Option<&WebGLTexture>, - level: i32) { - self.base.FramebufferTexture2D(target, attachment, textarget, texture, level) + fn FramebufferTexture2D( + &self, + target: u32, + attachment: u32, + textarget: u32, + texture: Option<&WebGLTexture>, + level: i32, + ) { + self.base + .FramebufferTexture2D(target, attachment, textarget, texture, level) } /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - fn GetAttachedShaders( - &self, - program: &WebGLProgram, - ) -> Option<Vec<DomRoot<WebGLShader>>> { + fn GetAttachedShaders(&self, program: &WebGLProgram) -> Option<Vec<DomRoot<WebGLShader>>> { self.base.GetAttachedShaders(program) } /// https://www.khronos.org/registry/webgl/specs/latest/2.0/#3.7.9 - fn DrawArraysInstanced( - &self, - mode: u32, - first: i32, - count: i32, - primcount: i32, - ) { + fn DrawArraysInstanced(&self, mode: u32, first: i32, count: i32, primcount: i32) { handle_potential_webgl_error!( self.base, - self.base.draw_arrays_instanced(mode, first, count, primcount) + self.base + .draw_arrays_instanced(mode, first, count, primcount) ) } @@ -978,7 +1061,8 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { ) { handle_potential_webgl_error!( self.base, - self.base.draw_elements_instanced(mode, count, type_, offset, primcount) + self.base + .draw_elements_instanced(mode, count, type_, offset, primcount) ) } @@ -988,7 +1072,6 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext { } } - impl LayoutCanvasWebGLRenderingContextHelpers for LayoutDom<WebGL2RenderingContext> { #[allow(unsafe_code)] unsafe fn canvas_data_source(&self) -> HTMLCanvasDataSource { diff --git a/components/script/dom/webgl_extensions/ext/angleinstancedarrays.rs b/components/script/dom/webgl_extensions/ext/angleinstancedarrays.rs index 7c93c8c6567..030146b8d3a 100644 --- a/components/script/dom/webgl_extensions/ext/angleinstancedarrays.rs +++ b/components/script/dom/webgl_extensions/ext/angleinstancedarrays.rs @@ -64,16 +64,11 @@ impl WebGLExtension for ANGLEInstancedArrays { impl ANGLEInstancedArraysMethods for ANGLEInstancedArrays { // https://www.khronos.org/registry/webgl/extensions/ANGLE_instanced_arrays/ - fn DrawArraysInstancedANGLE( - &self, - mode: u32, - first: i32, - count: i32, - primcount: i32, - ) { + fn DrawArraysInstancedANGLE(&self, mode: u32, first: i32, count: i32, primcount: i32) { handle_potential_webgl_error!( self.ctx, - self.ctx.draw_arrays_instanced(mode, first, count, primcount) + self.ctx + .draw_arrays_instanced(mode, first, count, primcount) ) } @@ -88,7 +83,8 @@ impl ANGLEInstancedArraysMethods for ANGLEInstancedArrays { ) { handle_potential_webgl_error!( self.ctx, - self.ctx.draw_elements_instanced(mode, count, type_, offset, primcount) + self.ctx + .draw_elements_instanced(mode, count, type_, offset, primcount) ) } diff --git a/components/script/dom/webgl_extensions/ext/extblendminmax.rs b/components/script/dom/webgl_extensions/ext/extblendminmax.rs index 70bf828ccc8..78c4c5bcb78 100644 --- a/components/script/dom/webgl_extensions/ext/extblendminmax.rs +++ b/components/script/dom/webgl_extensions/ext/extblendminmax.rs @@ -17,7 +17,9 @@ pub struct EXTBlendMinmax { impl EXTBlendMinmax { fn new_inherited() -> Self { - Self { reflector_: Reflector::new() } + Self { + reflector_: Reflector::new(), + } } } diff --git a/components/script/dom/webgl_extensions/ext/extshadertexturelod.rs b/components/script/dom/webgl_extensions/ext/extshadertexturelod.rs index f31a40fd29f..9766032c0c5 100644 --- a/components/script/dom/webgl_extensions/ext/extshadertexturelod.rs +++ b/components/script/dom/webgl_extensions/ext/extshadertexturelod.rs @@ -17,7 +17,9 @@ pub struct EXTShaderTextureLod { impl EXTShaderTextureLod { fn new_inherited() -> Self { - Self { reflector_: Reflector::new() } + Self { + reflector_: Reflector::new(), + } } } diff --git a/components/script/dom/webgl_extensions/ext/exttexturefilteranisotropic.rs b/components/script/dom/webgl_extensions/ext/exttexturefilteranisotropic.rs index 203f4da6251..ce8e6f840cc 100644 --- a/components/script/dom/webgl_extensions/ext/exttexturefilteranisotropic.rs +++ b/components/script/dom/webgl_extensions/ext/exttexturefilteranisotropic.rs @@ -44,8 +44,12 @@ impl WebGLExtension for EXTTextureFilterAnisotropic { } fn enable(ext: &WebGLExtensions) { - ext.enable_get_tex_parameter_name(EXTTextureFilterAnisotropicConstants::TEXTURE_MAX_ANISOTROPY_EXT); - ext.enable_get_parameter_name(EXTTextureFilterAnisotropicConstants::MAX_TEXTURE_MAX_ANISOTROPY_EXT); + ext.enable_get_tex_parameter_name( + EXTTextureFilterAnisotropicConstants::TEXTURE_MAX_ANISOTROPY_EXT, + ); + ext.enable_get_parameter_name( + EXTTextureFilterAnisotropicConstants::MAX_TEXTURE_MAX_ANISOTROPY_EXT, + ); } fn name() -> &'static str { diff --git a/components/script/dom/webgl_extensions/ext/oeselementindexuint.rs b/components/script/dom/webgl_extensions/ext/oeselementindexuint.rs index 2868ab0c41d..48e60b316dd 100644 --- a/components/script/dom/webgl_extensions/ext/oeselementindexuint.rs +++ b/components/script/dom/webgl_extensions/ext/oeselementindexuint.rs @@ -17,7 +17,9 @@ pub struct OESElementIndexUint { impl OESElementIndexUint { fn new_inherited() -> Self { - Self { reflector_: Reflector::new() } + Self { + reflector_: Reflector::new(), + } } } diff --git a/components/script/dom/webgl_extensions/ext/oesstandardderivatives.rs b/components/script/dom/webgl_extensions/ext/oesstandardderivatives.rs index 36fb84124a5..966a03505b6 100644 --- a/components/script/dom/webgl_extensions/ext/oesstandardderivatives.rs +++ b/components/script/dom/webgl_extensions/ext/oesstandardderivatives.rs @@ -27,9 +27,11 @@ impl OESStandardDerivatives { impl WebGLExtension for OESStandardDerivatives { type Extension = OESStandardDerivatives; fn new(ctx: &WebGLRenderingContext) -> DomRoot<OESStandardDerivatives> { - reflect_dom_object(Box::new(OESStandardDerivatives::new_inherited()), - &*ctx.global(), - OESStandardDerivativesBinding::Wrap) + reflect_dom_object( + Box::new(OESStandardDerivatives::new_inherited()), + &*ctx.global(), + OESStandardDerivativesBinding::Wrap, + ) } fn spec() -> WebGLExtensionSpec { @@ -42,8 +44,12 @@ impl WebGLExtension for OESStandardDerivatives { } fn enable(ext: &WebGLExtensions) { - ext.enable_hint_target(OESStandardDerivativesConstants::FRAGMENT_SHADER_DERIVATIVE_HINT_OES); - ext.enable_get_parameter_name(OESStandardDerivativesConstants::FRAGMENT_SHADER_DERIVATIVE_HINT_OES); + ext.enable_hint_target( + OESStandardDerivativesConstants::FRAGMENT_SHADER_DERIVATIVE_HINT_OES, + ); + ext.enable_get_parameter_name( + OESStandardDerivativesConstants::FRAGMENT_SHADER_DERIVATIVE_HINT_OES, + ); } fn name() -> &'static str { diff --git a/components/script/dom/webgl_extensions/ext/oestexturefloat.rs b/components/script/dom/webgl_extensions/ext/oestexturefloat.rs index a7eb655947f..13170f19538 100644 --- a/components/script/dom/webgl_extensions/ext/oestexturefloat.rs +++ b/components/script/dom/webgl_extensions/ext/oestexturefloat.rs @@ -26,9 +26,11 @@ impl OESTextureFloat { impl WebGLExtension for OESTextureFloat { type Extension = OESTextureFloat; fn new(ctx: &WebGLRenderingContext) -> DomRoot<OESTextureFloat> { - reflect_dom_object(Box::new(OESTextureFloat::new_inherited()), - &*ctx.global(), - OESTextureFloatBinding::Wrap) + reflect_dom_object( + Box::new(OESTextureFloat::new_inherited()), + &*ctx.global(), + OESTextureFloatBinding::Wrap, + ) } fn spec() -> WebGLExtensionSpec { @@ -36,9 +38,11 @@ impl WebGLExtension for OESTextureFloat { } fn is_supported(ext: &WebGLExtensions) -> bool { - ext.supports_any_gl_extension(&["GL_OES_texture_float", - "GL_ARB_texture_float", - "GL_EXT_color_buffer_float"]) + ext.supports_any_gl_extension(&[ + "GL_OES_texture_float", + "GL_ARB_texture_float", + "GL_EXT_color_buffer_float", + ]) } fn enable(ext: &WebGLExtensions) { @@ -49,10 +53,17 @@ impl WebGLExtension for OESTextureFloat { // Special internal formats must be used to avoid clamped float values ext.add_effective_tex_internal_format(webgl::RGBA, webgl::FLOAT, gl::RGBA32F); ext.add_effective_tex_internal_format(webgl::RGB, webgl::FLOAT, gl::RGB32F); - ext.add_effective_tex_internal_format(webgl::LUMINANCE, webgl::FLOAT, gl::LUMINANCE32F_ARB); + ext.add_effective_tex_internal_format( + webgl::LUMINANCE, + webgl::FLOAT, + gl::LUMINANCE32F_ARB, + ); ext.add_effective_tex_internal_format(webgl::ALPHA, webgl::FLOAT, gl::ALPHA32F_ARB); - ext.add_effective_tex_internal_format(webgl::LUMINANCE_ALPHA, webgl::FLOAT, - gl::LUMINANCE_ALPHA32F_ARB); + ext.add_effective_tex_internal_format( + webgl::LUMINANCE_ALPHA, + webgl::FLOAT, + gl::LUMINANCE_ALPHA32F_ARB, + ); } } diff --git a/components/script/dom/webgl_extensions/ext/oestexturefloatlinear.rs b/components/script/dom/webgl_extensions/ext/oestexturefloatlinear.rs index 7ce5cb3533a..264dd8fe41d 100644 --- a/components/script/dom/webgl_extensions/ext/oestexturefloatlinear.rs +++ b/components/script/dom/webgl_extensions/ext/oestexturefloatlinear.rs @@ -25,9 +25,11 @@ impl OESTextureFloatLinear { impl WebGLExtension for OESTextureFloatLinear { type Extension = OESTextureFloatLinear; fn new(ctx: &WebGLRenderingContext) -> DomRoot<OESTextureFloatLinear> { - reflect_dom_object(Box::new(OESTextureFloatLinear::new_inherited()), - &*ctx.global(), - OESTextureFloatLinearBinding::Wrap) + reflect_dom_object( + Box::new(OESTextureFloatLinear::new_inherited()), + &*ctx.global(), + OESTextureFloatLinearBinding::Wrap, + ) } fn spec() -> WebGLExtensionSpec { @@ -35,8 +37,7 @@ impl WebGLExtension for OESTextureFloatLinear { } fn is_supported(ext: &WebGLExtensions) -> bool { - ext.supports_any_gl_extension(&["GL_OES_texture_float_linear", - "GL_ARB_texture_float"]) + ext.supports_any_gl_extension(&["GL_OES_texture_float_linear", "GL_ARB_texture_float"]) } fn enable(ext: &WebGLExtensions) { diff --git a/components/script/dom/webgl_extensions/ext/oestexturehalffloat.rs b/components/script/dom/webgl_extensions/ext/oestexturehalffloat.rs index df35ee66c5e..67c9521750f 100644 --- a/components/script/dom/webgl_extensions/ext/oestexturehalffloat.rs +++ b/components/script/dom/webgl_extensions/ext/oestexturehalffloat.rs @@ -26,9 +26,11 @@ impl OESTextureHalfFloat { impl WebGLExtension for OESTextureHalfFloat { type Extension = OESTextureHalfFloat; fn new(ctx: &WebGLRenderingContext) -> DomRoot<OESTextureHalfFloat> { - reflect_dom_object(Box::new(OESTextureHalfFloat::new_inherited()), - &*ctx.global(), - OESTextureHalfFloatBinding::Wrap) + reflect_dom_object( + Box::new(OESTextureHalfFloat::new_inherited()), + &*ctx.global(), + OESTextureHalfFloatBinding::Wrap, + ) } fn spec() -> WebGLExtensionSpec { @@ -36,10 +38,12 @@ impl WebGLExtension for OESTextureHalfFloat { } fn is_supported(ext: &WebGLExtensions) -> bool { - ext.supports_any_gl_extension(&["GL_OES_texture_half_float", - "GL_ARB_half_float_pixel", - "GL_NV_half_float", - "GL_EXT_color_buffer_half_float"]) + ext.supports_any_gl_extension(&[ + "GL_OES_texture_half_float", + "GL_ARB_half_float_pixel", + "GL_NV_half_float", + "GL_EXT_color_buffer_half_float", + ]) } fn enable(ext: &WebGLExtensions) { @@ -53,7 +57,11 @@ impl WebGLExtension for OESTextureHalfFloat { ext.add_effective_tex_internal_format(webgl::RGB, hf, gl::RGB16F); ext.add_effective_tex_internal_format(webgl::LUMINANCE, hf, gl::LUMINANCE16F_ARB); ext.add_effective_tex_internal_format(webgl::ALPHA, hf, gl::ALPHA16F_ARB); - ext.add_effective_tex_internal_format(webgl::LUMINANCE_ALPHA, hf, gl::LUMINANCE_ALPHA16F_ARB); + ext.add_effective_tex_internal_format( + webgl::LUMINANCE_ALPHA, + hf, + gl::LUMINANCE_ALPHA16F_ARB, + ); } } diff --git a/components/script/dom/webgl_extensions/ext/oestexturehalffloatlinear.rs b/components/script/dom/webgl_extensions/ext/oestexturehalffloatlinear.rs index dad96a32f93..80a0583f822 100644 --- a/components/script/dom/webgl_extensions/ext/oestexturehalffloatlinear.rs +++ b/components/script/dom/webgl_extensions/ext/oestexturehalffloatlinear.rs @@ -26,9 +26,11 @@ impl OESTextureHalfFloatLinear { impl WebGLExtension for OESTextureHalfFloatLinear { type Extension = OESTextureHalfFloatLinear; fn new(ctx: &WebGLRenderingContext) -> DomRoot<OESTextureHalfFloatLinear> { - reflect_dom_object(Box::new(OESTextureHalfFloatLinear::new_inherited()), - &*ctx.global(), - OESTextureHalfFloatLinearBinding::Wrap) + reflect_dom_object( + Box::new(OESTextureHalfFloatLinear::new_inherited()), + &*ctx.global(), + OESTextureHalfFloatLinearBinding::Wrap, + ) } fn spec() -> WebGLExtensionSpec { @@ -36,9 +38,11 @@ impl WebGLExtension for OESTextureHalfFloatLinear { } fn is_supported(ext: &WebGLExtensions) -> bool { - ext.supports_any_gl_extension(&["GL_OES_texture_float_linear", - "GL_ARB_half_float_pixel", - "GL_NV_half_float"]) + ext.supports_any_gl_extension(&[ + "GL_OES_texture_float_linear", + "GL_ARB_half_float_pixel", + "GL_NV_half_float", + ]) } fn enable(ext: &WebGLExtensions) { diff --git a/components/script/dom/webgl_extensions/ext/oesvertexarrayobject.rs b/components/script/dom/webgl_extensions/ext/oesvertexarrayobject.rs index aae50c1effe..630088ab029 100644 --- a/components/script/dom/webgl_extensions/ext/oesvertexarrayobject.rs +++ b/components/script/dom/webgl_extensions/ext/oesvertexarrayobject.rs @@ -52,9 +52,11 @@ impl OESVertexArrayObjectMethods for OESVertexArrayObject { impl WebGLExtension for OESVertexArrayObject { type Extension = OESVertexArrayObject; fn new(ctx: &WebGLRenderingContext) -> DomRoot<OESVertexArrayObject> { - reflect_dom_object(Box::new(OESVertexArrayObject::new_inherited(ctx)), - &*ctx.global(), - OESVertexArrayObjectBinding::Wrap) + reflect_dom_object( + Box::new(OESVertexArrayObject::new_inherited(ctx)), + &*ctx.global(), + OESVertexArrayObjectBinding::Wrap, + ) } fn spec() -> WebGLExtensionSpec { @@ -62,9 +64,11 @@ impl WebGLExtension for OESVertexArrayObject { } fn is_supported(ext: &WebGLExtensions) -> bool { - ext.supports_any_gl_extension(&["GL_OES_vertex_array_object", - "GL_ARB_vertex_array_object", - "GL_APPLE_vertex_array_object"]) + ext.supports_any_gl_extension(&[ + "GL_OES_vertex_array_object", + "GL_ARB_vertex_array_object", + "GL_APPLE_vertex_array_object", + ]) } fn enable(ext: &WebGLExtensions) { diff --git a/components/script/dom/webgl_extensions/extension.rs b/components/script/dom/webgl_extensions/extension.rs index 1f8c770aaa3..8610fcc6e80 100644 --- a/components/script/dom/webgl_extensions/extension.rs +++ b/components/script/dom/webgl_extensions/extension.rs @@ -10,7 +10,10 @@ use dom::webglrenderingcontext::WebGLRenderingContext; use super::WebGLExtensions; /// Trait implemented by WebGL extensions. -pub trait WebGLExtension: Sized where Self::Extension: DomObject + JSTraceable { +pub trait WebGLExtension: Sized +where + Self::Extension: DomObject + JSTraceable, +{ type Extension; /// Creates the DOM object of the WebGL extension. @@ -33,5 +36,5 @@ pub enum WebGLExtensionSpec { /// Extensions written against both WebGL and WebGL2 specs. All, /// Extensions writen against a specific WebGL version spec. - Specific(WebGLVersion) + Specific(WebGLVersion), } diff --git a/components/script/dom/webgl_extensions/extensions.rs b/components/script/dom/webgl_extensions/extensions.rs index 51d8de44efc..5833cccba71 100644 --- a/components/script/dom/webgl_extensions/extensions.rs +++ b/components/script/dom/webgl_extensions/extensions.rs @@ -26,14 +26,16 @@ use super::wrapper::{WebGLExtensionWrapper, TypedWebGLExtensionWrapper}; // but must trigger a InvalidValue error until the related WebGL Extensions are enabled. // Example: https://www.khronos.org/registry/webgl/extensions/OES_texture_float/ const DEFAULT_DISABLED_TEX_TYPES_WEBGL1: [GLenum; 2] = [ - constants::FLOAT, OESTextureHalfFloatConstants::HALF_FLOAT_OES + constants::FLOAT, + OESTextureHalfFloatConstants::HALF_FLOAT_OES, ]; // Data types that are implemented for textures in WebGLRenderingContext // but not allowed to use with linear filtering until the related WebGL Extensions are enabled. // Example: https://www.khronos.org/registry/webgl/extensions/OES_texture_float_linear/ const DEFAULT_NOT_FILTERABLE_TEX_TYPES: [GLenum; 2] = [ - constants::FLOAT, OESTextureHalfFloatConstants::HALF_FLOAT_OES + constants::FLOAT, + OESTextureHalfFloatConstants::HALF_FLOAT_OES, ]; // Param names that are implemented for glGetParameter in a WebGL 1.0 context @@ -48,16 +50,14 @@ const DEFAULT_DISABLED_GET_PARAMETER_NAMES_WEBGL1: [GLenum; 3] = [ // Param names that are implemented for glGetTexParameter in a WebGL 1.0 context // but must trigger a InvalidEnum error until the related WebGL Extensions are enabled. // Example: https://www.khronos.org/registry/webgl/extensions/OES_standard_derivatives/ -const DEFAULT_DISABLED_GET_TEX_PARAMETER_NAMES_WEBGL1: [GLenum; 1] = [ - EXTTextureFilterAnisotropicConstants::TEXTURE_MAX_ANISOTROPY_EXT, -]; +const DEFAULT_DISABLED_GET_TEX_PARAMETER_NAMES_WEBGL1: [GLenum; 1] = + [EXTTextureFilterAnisotropicConstants::TEXTURE_MAX_ANISOTROPY_EXT]; // Param names that are implemented for glGetVertexAttrib in a WebGL 1.0 context // but must trigger a InvalidEnum error until the related WebGL Extensions are enabled. // Example: https://www.khronos.org/registry/webgl/extensions/ANGLE_instanced_arrays/ -const DEFAULT_DISABLED_GET_VERTEX_ATTRIB_NAMES_WEBGL1: [GLenum; 1] = [ - ANGLEInstancedArraysConstants::VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE, -]; +const DEFAULT_DISABLED_GET_VERTEX_ATTRIB_NAMES_WEBGL1: [GLenum; 1] = + [ANGLEInstancedArraysConstants::VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE]; /// WebGL features that are enabled/disabled by WebGL Extensions. #[derive(JSTraceable, MallocSizeOf)] @@ -90,26 +90,31 @@ impl WebGLExtensionFeatures { element_index_uint_enabled, blend_minmax_enabled, ) = match webgl_version { - WebGLVersion::WebGL1 => { - ( - DEFAULT_DISABLED_TEX_TYPES_WEBGL1.iter().cloned().collect(), - DEFAULT_DISABLED_GET_PARAMETER_NAMES_WEBGL1.iter().cloned().collect(), - DEFAULT_DISABLED_GET_TEX_PARAMETER_NAMES_WEBGL1.iter().cloned().collect(), - DEFAULT_DISABLED_GET_VERTEX_ATTRIB_NAMES_WEBGL1.iter().cloned().collect(), - false, - false, - ) - }, - WebGLVersion::WebGL2 => { - ( - Default::default(), - Default::default(), - Default::default(), - Default::default(), - true, - true, - ) - } + WebGLVersion::WebGL1 => ( + DEFAULT_DISABLED_TEX_TYPES_WEBGL1.iter().cloned().collect(), + DEFAULT_DISABLED_GET_PARAMETER_NAMES_WEBGL1 + .iter() + .cloned() + .collect(), + DEFAULT_DISABLED_GET_TEX_PARAMETER_NAMES_WEBGL1 + .iter() + .cloned() + .collect(), + DEFAULT_DISABLED_GET_VERTEX_ATTRIB_NAMES_WEBGL1 + .iter() + .cloned() + .collect(), + false, + false, + ), + WebGLVersion::WebGL2 => ( + Default::default(), + Default::default(), + Default::default(), + Default::default(), + true, + true, + ), }; Self { gl_extensions: Default::default(), @@ -144,35 +149,45 @@ impl WebGLExtensions { } } - pub fn init_once<F>(&self, cb: F) where F: FnOnce() -> String { + pub fn init_once<F>(&self, cb: F) + where + F: FnOnce() -> String, + { if self.extensions.borrow().len() == 0 { let gl_str = cb(); - self.features.borrow_mut().gl_extensions = FnvHashSet::from_iter(gl_str.split(&[',', ' '][..]) - .map(|s| s.into())); + self.features.borrow_mut().gl_extensions = + FnvHashSet::from_iter(gl_str.split(&[',', ' '][..]).map(|s| s.into())); self.register_all_extensions(); } } - pub fn register<T:'static + WebGLExtension + JSTraceable + MallocSizeOf>(&self) { + pub fn register<T: 'static + WebGLExtension + JSTraceable + MallocSizeOf>(&self) { let name = T::name().to_uppercase(); - self.extensions.borrow_mut().insert(name, Box::new(TypedWebGLExtensionWrapper::<T>::new())); + self.extensions + .borrow_mut() + .insert(name, Box::new(TypedWebGLExtensionWrapper::<T>::new())); } pub fn get_suported_extensions(&self) -> Vec<&'static str> { - self.extensions.borrow().iter() - .filter(|ref v| { - if let WebGLExtensionSpec::Specific(version) = v.1.spec() { - if self.webgl_version != version { - return false; - } - } - v.1.is_supported(&self) - }) - .map(|ref v| v.1.name()) - .collect() + self.extensions + .borrow() + .iter() + .filter(|ref v| { + if let WebGLExtensionSpec::Specific(version) = v.1.spec() { + if self.webgl_version != version { + return false; + } + } + v.1.is_supported(&self) + }).map(|ref v| v.1.name()) + .collect() } - pub fn get_or_init_extension(&self, name: &str, ctx: &WebGLRenderingContext) -> Option<NonNull<JSObject>> { + pub fn get_or_init_extension( + &self, + name: &str, + ctx: &WebGLRenderingContext, + ) -> Option<NonNull<JSObject>> { let name = name.to_uppercase(); self.extensions.borrow().get(&name).and_then(|extension| { if extension.is_supported(self) { @@ -185,10 +200,13 @@ impl WebGLExtensions { pub fn is_enabled<T>(&self) -> bool where - T: 'static + WebGLExtension + JSTraceable + MallocSizeOf + T: 'static + WebGLExtension + JSTraceable + MallocSizeOf, { let name = T::name().to_uppercase(); - self.extensions.borrow().get(&name).map_or(false, |ext| { ext.is_enabled() }) + self.extensions + .borrow() + .get(&name) + .map_or(false, |ext| ext.is_enabled()) } pub fn supports_gl_extension(&self, name: &str) -> bool { @@ -197,42 +215,66 @@ impl WebGLExtensions { pub fn supports_any_gl_extension(&self, names: &[&str]) -> bool { let features = self.features.borrow(); - names.iter().any(|name| features.gl_extensions.contains(*name)) + names + .iter() + .any(|name| features.gl_extensions.contains(*name)) } pub fn enable_tex_type(&self, data_type: GLenum) { - self.features.borrow_mut().disabled_tex_types.remove(&data_type); + self.features + .borrow_mut() + .disabled_tex_types + .remove(&data_type); } pub fn is_tex_type_enabled(&self, data_type: GLenum) -> bool { - self.features.borrow().disabled_tex_types.get(&data_type).is_none() + self.features + .borrow() + .disabled_tex_types + .get(&data_type) + .is_none() } - pub fn add_effective_tex_internal_format(&self, - source_internal_format: u32, - source_data_type: u32, - effective_internal_format: u32) - { + pub fn add_effective_tex_internal_format( + &self, + source_internal_format: u32, + source_data_type: u32, + effective_internal_format: u32, + ) { let format = TexFormatType(source_internal_format, source_data_type); - self.features.borrow_mut().effective_tex_internal_formats.insert(format, - effective_internal_format); - + self.features + .borrow_mut() + .effective_tex_internal_formats + .insert(format, effective_internal_format); } - pub fn get_effective_tex_internal_format(&self, - source_internal_format: u32, - source_data_type: u32) -> u32 { + pub fn get_effective_tex_internal_format( + &self, + source_internal_format: u32, + source_data_type: u32, + ) -> u32 { let format = TexFormatType(source_internal_format, source_data_type); - *(self.features.borrow().effective_tex_internal_formats.get(&format) - .unwrap_or(&source_internal_format)) + *(self + .features + .borrow() + .effective_tex_internal_formats + .get(&format) + .unwrap_or(&source_internal_format)) } pub fn enable_filterable_tex_type(&self, text_data_type: GLenum) { - self.features.borrow_mut().not_filterable_tex_types.remove(&text_data_type); + self.features + .borrow_mut() + .not_filterable_tex_types + .remove(&text_data_type); } pub fn is_filterable(&self, text_data_type: u32) -> bool { - self.features.borrow().not_filterable_tex_types.get(&text_data_type).is_none() + self.features + .borrow() + .not_filterable_tex_types + .get(&text_data_type) + .is_none() } pub fn enable_hint_target(&self, name: GLenum) { @@ -244,27 +286,48 @@ impl WebGLExtensions { } pub fn enable_get_parameter_name(&self, name: GLenum) { - self.features.borrow_mut().disabled_get_parameter_names.remove(&name); + self.features + .borrow_mut() + .disabled_get_parameter_names + .remove(&name); } pub fn is_get_parameter_name_enabled(&self, name: GLenum) -> bool { - !self.features.borrow().disabled_get_parameter_names.contains(&name) + !self + .features + .borrow() + .disabled_get_parameter_names + .contains(&name) } pub fn enable_get_tex_parameter_name(&self, name: GLenum) { - self.features.borrow_mut().disabled_get_tex_parameter_names.remove(&name); + self.features + .borrow_mut() + .disabled_get_tex_parameter_names + .remove(&name); } pub fn is_get_tex_parameter_name_enabled(&self, name: GLenum) -> bool { - !self.features.borrow().disabled_get_tex_parameter_names.contains(&name) + !self + .features + .borrow() + .disabled_get_tex_parameter_names + .contains(&name) } pub fn enable_get_vertex_attrib_name(&self, name: GLenum) { - self.features.borrow_mut().disabled_get_vertex_attrib_names.remove(&name); + self.features + .borrow_mut() + .disabled_get_vertex_attrib_names + .remove(&name); } pub fn is_get_vertex_attrib_name_enabled(&self, name: GLenum) -> bool { - !self.features.borrow().disabled_get_vertex_attrib_names.contains(&name) + !self + .features + .borrow() + .disabled_get_vertex_attrib_names + .contains(&name) } fn register_all_extensions(&self) { diff --git a/components/script/dom/webgl_extensions/mod.rs b/components/script/dom/webgl_extensions/mod.rs index 3e90d4a7c8d..bf195c916ca 100644 --- a/components/script/dom/webgl_extensions/mod.rs +++ b/components/script/dom/webgl_extensions/mod.rs @@ -9,16 +9,16 @@ mod wrapper; // Some extra constants not exposed in WebGLRenderingContext constants pub mod ext_constants { - pub const ALPHA16F_ARB: u32 = 0x881C; - pub const ALPHA32F_ARB: u32 = 0x8816; - pub const LUMINANCE16F_ARB: u32 = 0x881E; - pub const LUMINANCE32F_ARB: u32 = 0x8818; - pub const LUMINANCE_ALPHA16F_ARB: u32 = 0x881F; - pub const LUMINANCE_ALPHA32F_ARB: u32 = 0x8819; - pub const RGBA16F: u32 = 0x881A; - pub const RGB16F: u32 = 0x881B; - pub const RGBA32F: u32 = 0x8814; - pub const RGB32F: u32 = 0x8815; + pub const ALPHA16F_ARB: u32 = 0x881C; + pub const ALPHA32F_ARB: u32 = 0x8816; + pub const LUMINANCE16F_ARB: u32 = 0x881E; + pub const LUMINANCE32F_ARB: u32 = 0x8818; + pub const LUMINANCE_ALPHA16F_ARB: u32 = 0x881F; + pub const LUMINANCE_ALPHA32F_ARB: u32 = 0x8819; + pub const RGBA16F: u32 = 0x881A; + pub const RGB16F: u32 = 0x881B; + pub const RGBA32F: u32 = 0x8814; + pub const RGB32F: u32 = 0x8815; } pub use self::extension::WebGLExtension; diff --git a/components/script/dom/webgl_extensions/wrapper.rs b/components/script/dom/webgl_extensions/wrapper.rs index b5166327381..f45d3ff8045 100644 --- a/components/script/dom/webgl_extensions/wrapper.rs +++ b/components/script/dom/webgl_extensions/wrapper.rs @@ -15,10 +15,11 @@ use super::{WebGLExtension, WebGLExtensions, WebGLExtensionSpec}; /// Trait used internally by WebGLExtensions to store and /// handle the different WebGL extensions in a common list. pub trait WebGLExtensionWrapper: JSTraceable + MallocSizeOf { - fn instance_or_init(&self, - ctx: &WebGLRenderingContext, - ext: &WebGLExtensions) - -> NonNull<JSObject>; + fn instance_or_init( + &self, + ctx: &WebGLRenderingContext, + ext: &WebGLExtensions, + ) -> NonNull<JSObject>; fn spec(&self) -> WebGLExtensionSpec; fn is_supported(&self, &WebGLExtensions) -> bool; fn is_enabled(&self) -> bool; @@ -30,7 +31,7 @@ pub trait WebGLExtensionWrapper: JSTraceable + MallocSizeOf { #[must_root] #[derive(JSTraceable, MallocSizeOf)] pub struct TypedWebGLExtensionWrapper<T: WebGLExtension> { - extension: MutNullableDom<T::Extension> + extension: MutNullableDom<T::Extension>, } /// Typed WebGL Extension implementation. @@ -38,18 +39,21 @@ pub struct TypedWebGLExtensionWrapper<T: WebGLExtension> { impl<T: WebGLExtension> TypedWebGLExtensionWrapper<T> { pub fn new() -> TypedWebGLExtensionWrapper<T> { TypedWebGLExtensionWrapper { - extension: MutNullableDom::new(None) + extension: MutNullableDom::new(None), } } } impl<T> WebGLExtensionWrapper for TypedWebGLExtensionWrapper<T> - where T: WebGLExtension + JSTraceable + MallocSizeOf + 'static { +where + T: WebGLExtension + JSTraceable + MallocSizeOf + 'static, +{ #[allow(unsafe_code)] - fn instance_or_init(&self, - ctx: &WebGLRenderingContext, - ext: &WebGLExtensions) - -> NonNull<JSObject> { + fn instance_or_init( + &self, + ctx: &WebGLRenderingContext, + ext: &WebGLExtensions, + ) -> NonNull<JSObject> { let mut enabled = true; let extension = self.extension.or_init(|| { enabled = false; @@ -58,13 +62,11 @@ impl<T> WebGLExtensionWrapper for TypedWebGLExtensionWrapper<T> if !enabled { self.enable(ext); } - unsafe { - NonNull::new_unchecked(extension.reflector().get_jsobject().get()) - } + unsafe { NonNull::new_unchecked(extension.reflector().get_jsobject().get()) } } fn spec(&self) -> WebGLExtensionSpec { - T::spec() + T::spec() } fn is_supported(&self, ext: &WebGLExtensions) -> bool { diff --git a/components/script/dom/webgl_validations/tex_image_2d.rs b/components/script/dom/webgl_validations/tex_image_2d.rs index e00c988bcb3..46b85dddec7 100644 --- a/components/script/dom/webgl_validations/tex_image_2d.rs +++ b/components/script/dom/webgl_validations/tex_image_2d.rs @@ -46,39 +46,32 @@ impl std::error::Error for TexImageValidationError { fn description(&self) -> &str { use self::TexImageValidationError::*; match *self { - InvalidTextureTarget(_) - => "Invalid texture target", - TextureTargetNotBound(_) - => "Texture was not bound", - InvalidCubicTextureDimensions - => "Invalid dimensions were given for a cubic texture target", - NegativeLevel - => "A negative level was passed", - LevelTooHigh - => "Level too high", - NegativeDimension - => "Negative dimensions were passed", - TextureTooBig - => "Dimensions given are too big", - InvalidDataType - => "Invalid data type", - InvalidTextureFormat - => "Invalid texture format", - TextureFormatMismatch - => "Texture format mismatch", - InvalidTypeForFormat - => "Invalid type for the given format", - InvalidBorder - => "Invalid border", - NonPotTexture - => "Expected a power of two texture", + InvalidTextureTarget(_) => "Invalid texture target", + TextureTargetNotBound(_) => "Texture was not bound", + InvalidCubicTextureDimensions => { + "Invalid dimensions were given for a cubic texture target" + }, + NegativeLevel => "A negative level was passed", + LevelTooHigh => "Level too high", + NegativeDimension => "Negative dimensions were passed", + TextureTooBig => "Dimensions given are too big", + InvalidDataType => "Invalid data type", + InvalidTextureFormat => "Invalid texture format", + TextureFormatMismatch => "Texture format mismatch", + InvalidTypeForFormat => "Invalid type for the given format", + InvalidBorder => "Invalid border", + NonPotTexture => "Expected a power of two texture", } } } impl fmt::Display for TexImageValidationError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "TexImageValidationError({})", std::error::Error::description(self)) + write!( + f, + "TexImageValidationError({})", + std::error::Error::description(self) + ) } } @@ -119,16 +112,19 @@ impl<'a> WebGLValidator for CommonTexImage2DValidator<'a> { None => { self.context.webgl_error(InvalidEnum); return Err(TexImageValidationError::InvalidTextureTarget(self.target)); - } + }, }; - let texture = self.context.textures().active_texture_for_image_target(target); + let texture = self + .context + .textures() + .active_texture_for_image_target(target); let limits = self.context.limits(); let max_size = if target.is_cubic() { - limits.max_cube_map_tex_size + limits.max_cube_map_tex_size } else { - limits.max_tex_size + limits.max_tex_size }; // If an attempt is made to call this function with no WebGLTexture @@ -138,7 +134,7 @@ impl<'a> WebGLValidator for CommonTexImage2DValidator<'a> { None => { self.context.webgl_error(InvalidOperation); return Err(TexImageValidationError::TextureTargetNotBound(self.target)); - } + }, }; // GL_INVALID_ENUM is generated if internal_format is not an accepted @@ -148,7 +144,7 @@ impl<'a> WebGLValidator for CommonTexImage2DValidator<'a> { None => { self.context.webgl_error(InvalidEnum); return Err(TexImageValidationError::InvalidTextureFormat); - } + }, }; // GL_INVALID_VALUE is generated if target is one of the six cube map 2D @@ -217,11 +213,15 @@ impl<'a> WebGLValidator for CommonTexImage2DValidator<'a> { } impl<'a> CommonTexImage2DValidator<'a> { - pub fn new(context: &'a WebGLRenderingContext, - target: u32, level: i32, - internal_format: u32, - width: i32, height: i32, - border: i32) -> Self { + pub fn new( + context: &'a WebGLRenderingContext, + target: u32, + level: i32, + internal_format: u32, + width: i32, + height: i32, + border: i32, + ) -> Self { CommonTexImage2DValidator { context: context, target: target, @@ -229,7 +229,7 @@ impl<'a> CommonTexImage2DValidator<'a> { internal_format: internal_format, width: width, height: height, - border: border + border: border, } } } @@ -242,21 +242,27 @@ pub struct TexImage2DValidator<'a> { impl<'a> TexImage2DValidator<'a> { // TODO: Move data validation logic here. - pub fn new(context: &'a WebGLRenderingContext, - target: u32, - level: i32, - internal_format: u32, - width: i32, - height: i32, - border: i32, - format: u32, - data_type: u32) -> Self { + pub fn new( + context: &'a WebGLRenderingContext, + target: u32, + level: i32, + internal_format: u32, + width: i32, + height: i32, + border: i32, + format: u32, + data_type: u32, + ) -> Self { TexImage2DValidator { - common_validator: CommonTexImage2DValidator::new(context, target, - level, - internal_format, - width, height, - border), + common_validator: CommonTexImage2DValidator::new( + context, + target, + level, + internal_format, + width, + height, + border, + ), format: format, data_type: data_type, } @@ -309,7 +315,7 @@ impl<'a> WebGLValidator for TexImage2DValidator<'a> { None => { context.webgl_error(InvalidEnum); return Err(TexImageValidationError::InvalidTextureFormat); - } + }, }; // GL_INVALID_OPERATION is generated if format does not match @@ -319,7 +325,6 @@ impl<'a> WebGLValidator for TexImage2DValidator<'a> { return Err(TexImageValidationError::TextureFormatMismatch); } - // GL_INVALID_OPERATION is generated if type is // GL_UNSIGNED_SHORT_4_4_4_4 or GL_UNSIGNED_SHORT_5_5_5_1 and format is // not GL_RGBA. @@ -327,11 +332,12 @@ impl<'a> WebGLValidator for TexImage2DValidator<'a> { // GL_INVALID_OPERATION is generated if type is GL_UNSIGNED_SHORT_5_6_5 // and format is not GL_RGB. match data_type { - TexDataType::UnsignedShort4444 | - TexDataType::UnsignedShort5551 if format != TexFormat::RGBA => { + TexDataType::UnsignedShort4444 | TexDataType::UnsignedShort5551 + if format != TexFormat::RGBA => + { context.webgl_error(InvalidOperation); return Err(TexImageValidationError::InvalidTypeForFormat); - }, + } TexDataType::UnsignedShort565 if format != TexFormat::RGB => { context.webgl_error(InvalidOperation); return Err(TexImageValidationError::InvalidTypeForFormat); diff --git a/components/script/dom/webgl_validations/types.rs b/components/script/dom/webgl_validations/types.rs index a2bdaa0de2f..f3741d218f7 100644 --- a/components/script/dom/webgl_validations/types.rs +++ b/components/script/dom/webgl_validations/types.rs @@ -67,9 +67,7 @@ impl TexDataType { use self::TexDataType::*; match *self { UnsignedByte => 1, - UnsignedShort4444 | - UnsignedShort5551 | - UnsignedShort565 => 2, + UnsignedShort4444 | UnsignedShort5551 | UnsignedShort565 => 2, Float => 4, HalfFloat => 2, } diff --git a/components/script/dom/webglactiveinfo.rs b/components/script/dom/webglactiveinfo.rs index 245f6194105..11eb96a7a0f 100644 --- a/components/script/dom/webglactiveinfo.rs +++ b/components/script/dom/webglactiveinfo.rs @@ -34,7 +34,7 @@ impl WebGLActiveInfo { reflect_dom_object( Box::new(WebGLActiveInfo::new_inherited(size, ty, name)), window, - WebGLActiveInfoBinding::Wrap + WebGLActiveInfoBinding::Wrap, ) } } diff --git a/components/script/dom/webglbuffer.rs b/components/script/dom/webglbuffer.rs index c49a3852709..eca72566ea4 100644 --- a/components/script/dom/webglbuffer.rs +++ b/components/script/dom/webglbuffer.rs @@ -45,7 +45,10 @@ impl WebGLBuffer { pub fn maybe_new(context: &WebGLRenderingContext) -> Option<DomRoot<Self>> { let (sender, receiver) = webgl_channel().unwrap(); context.send_command(WebGLCommand::CreateBuffer(sender)); - receiver.recv().unwrap().map(|id| WebGLBuffer::new(context, id)) + receiver + .recv() + .unwrap() + .map(|id| WebGLBuffer::new(context, id)) } pub fn new(context: &WebGLRenderingContext, id: WebGLBufferId) -> DomRoot<Self> { @@ -57,7 +60,6 @@ impl WebGLBuffer { } } - impl WebGLBuffer { pub fn id(&self) -> WebGLBufferId { self.id @@ -76,7 +78,11 @@ impl WebGLBuffer { let (sender, receiver) = ipc::bytes_channel().unwrap(); self.upcast::<WebGLObject>() .context() - .send_command(WebGLCommand::BufferData(self.target.get().unwrap(), receiver, usage)); + .send_command(WebGLCommand::BufferData( + self.target.get().unwrap(), + receiver, + usage, + )); sender.send(data).unwrap(); Ok(()) } @@ -128,13 +134,19 @@ impl WebGLBuffer { pub fn increment_attached_counter(&self) { self.attached_counter.set( - self.attached_counter.get().checked_add(1).expect("refcount overflowed"), + self.attached_counter + .get() + .checked_add(1) + .expect("refcount overflowed"), ); } pub fn decrement_attached_counter(&self) { self.attached_counter.set( - self.attached_counter.get().checked_sub(1).expect("refcount underflowed"), + self.attached_counter + .get() + .checked_sub(1) + .expect("refcount underflowed"), ); if self.is_deleted() { self.delete(); diff --git a/components/script/dom/webglcontextevent.rs b/components/script/dom/webglcontextevent.rs index aeec60f8cf1..bdecb299bd0 100644 --- a/components/script/dom/webglcontextevent.rs +++ b/components/script/dom/webglcontextevent.rs @@ -48,20 +48,24 @@ impl WebGLContextEvent { // available. let status_message = DOMString::new(); reflect_dom_object( - Box::new(WebGLContextEvent::new_inherited(status_message)), - window, - WebGLContextEventBinding::Wrap) + Box::new(WebGLContextEvent::new_inherited(status_message)), + window, + WebGLContextEventBinding::Wrap, + ) } - pub fn new(window: &Window, - type_: Atom, - bubbles: EventBubbles, - cancelable: EventCancelable, - status_message: DOMString) -> DomRoot<WebGLContextEvent> { + pub fn new( + window: &Window, + type_: Atom, + bubbles: EventBubbles, + cancelable: EventCancelable, + status_message: DOMString, + ) -> DomRoot<WebGLContextEvent> { let event = reflect_dom_object( - Box::new(WebGLContextEvent::new_inherited(status_message)), - window, - WebGLContextEventBinding::Wrap); + Box::new(WebGLContextEvent::new_inherited(status_message)), + window, + WebGLContextEventBinding::Wrap, + ); { let parent = event.upcast::<Event>(); @@ -71,9 +75,11 @@ impl WebGLContextEvent { event } - pub fn Constructor(window: &Window, - type_: DOMString, - init: &WebGLContextEventInit) -> Fallible<DomRoot<WebGLContextEvent>> { + pub fn Constructor( + window: &Window, + type_: DOMString, + init: &WebGLContextEventInit, + ) -> Fallible<DomRoot<WebGLContextEvent>> { let status_message = match init.statusMessage.as_ref() { Some(message) => message.clone(), None => DOMString::new(), @@ -83,10 +89,12 @@ impl WebGLContextEvent { let cancelable = EventCancelable::from(init.parent.cancelable); - Ok(WebGLContextEvent::new(window, - Atom::from(type_), - bubbles, - cancelable, - status_message)) + Ok(WebGLContextEvent::new( + window, + Atom::from(type_), + bubbles, + cancelable, + status_message, + )) } } diff --git a/components/script/dom/webglframebuffer.rs b/components/script/dom/webglframebuffer.rs index c3df02c8e0b..c9da9ae39a5 100644 --- a/components/script/dom/webglframebuffer.rs +++ b/components/script/dom/webglframebuffer.rs @@ -28,7 +28,10 @@ pub enum CompleteForRendering { #[derive(Clone, JSTraceable, MallocSizeOf)] enum WebGLFramebufferAttachment { Renderbuffer(Dom<WebGLRenderbuffer>), - Texture { texture: Dom<WebGLTexture>, level: i32 }, + Texture { + texture: Dom<WebGLTexture>, + level: i32, + }, } impl WebGLFramebufferAttachment { @@ -42,16 +45,18 @@ impl WebGLFramebufferAttachment { fn mark_initialized(&self) { match *self { WebGLFramebufferAttachment::Renderbuffer(ref r) => r.mark_initialized(), - WebGLFramebufferAttachment::Texture { .. } => () + WebGLFramebufferAttachment::Texture { .. } => (), } } fn root(&self) -> WebGLFramebufferAttachmentRoot { match *self { - WebGLFramebufferAttachment::Renderbuffer(ref rb) => - WebGLFramebufferAttachmentRoot::Renderbuffer(DomRoot::from_ref(&rb)), - WebGLFramebufferAttachment::Texture { ref texture, .. } => - WebGLFramebufferAttachmentRoot::Texture(DomRoot::from_ref(&texture)), + WebGLFramebufferAttachment::Renderbuffer(ref rb) => { + WebGLFramebufferAttachmentRoot::Renderbuffer(DomRoot::from_ref(&rb)) + }, + WebGLFramebufferAttachment::Texture { ref texture, .. } => { + WebGLFramebufferAttachmentRoot::Texture(DomRoot::from_ref(&texture)) + }, } } } @@ -100,13 +105,13 @@ impl WebGLFramebuffer { pub fn maybe_new(context: &WebGLRenderingContext) -> Option<DomRoot<Self>> { let (sender, receiver) = webgl_channel().unwrap(); context.send_command(WebGLCommand::CreateFramebuffer(sender)); - receiver.recv().unwrap().map(|id| WebGLFramebuffer::new(context, id)) + receiver + .recv() + .unwrap() + .map(|id| WebGLFramebuffer::new(context, id)) } - pub fn new( - context: &WebGLRenderingContext, - id: WebGLFramebufferId, - ) -> DomRoot<Self> { + pub fn new(context: &WebGLRenderingContext, id: WebGLFramebufferId) -> DomRoot<Self> { reflect_dom_object( Box::new(WebGLFramebuffer::new_inherited(context, id)), &*context.global(), @@ -115,7 +120,6 @@ impl WebGLFramebuffer { } } - impl WebGLFramebuffer { pub fn id(&self) -> WebGLFramebufferId { self.id @@ -128,9 +132,12 @@ impl WebGLFramebuffer { self.update_status(); self.target.set(Some(target)); - self.upcast::<WebGLObject>().context().send_command( - WebGLCommand::BindFramebuffer(target, WebGLFramebufferBindingRequest::Explicit(self.id)), - ); + self.upcast::<WebGLObject>() + .context() + .send_command(WebGLCommand::BindFramebuffer( + target, + WebGLFramebufferBindingRequest::Explicit(self.id), + )); } pub fn delete(&self) { @@ -161,7 +168,12 @@ impl WebGLFramebuffer { let has_zs = zs.is_some(); let attachments = [&*c, &*z, &*s, &*zs]; let attachment_constraints = [ - &[constants::RGBA4, constants::RGB5_A1, constants::RGB565, constants::RGBA][..], + &[ + constants::RGBA4, + constants::RGB5_A1, + constants::RGB565, + constants::RGBA, + ][..], &[constants::DEPTH_COMPONENT16][..], &[constants::STENCIL_INDEX8][..], &[constants::DEPTH_STENCIL][..], @@ -180,8 +192,7 @@ impl WebGLFramebuffer { // If any of the constraints above are violated, then: // // checkFramebufferStatus must return FRAMEBUFFER_UNSUPPORTED." - if (has_zs && (has_z || has_s)) || - (has_z && has_s) { + if (has_zs && (has_z || has_s)) || (has_z && has_s) { self.status.set(constants::FRAMEBUFFER_UNSUPPORTED); return; } @@ -192,12 +203,17 @@ impl WebGLFramebuffer { let (format, size) = match **attachment { Some(WebGLFramebufferAttachment::Renderbuffer(ref att_rb)) => { (Some(att_rb.internal_format()), att_rb.size()) - } - Some(WebGLFramebufferAttachment::Texture { texture: ref att_tex, level } ) => { + }, + Some(WebGLFramebufferAttachment::Texture { + texture: ref att_tex, + level, + }) => { let info = att_tex.image_info_at_face(0, level as u32); - (info.internal_format().map(|t| t.as_gl_constant()), - Some((info.width() as i32, info.height() as i32))) - } + ( + info.internal_format().map(|t| t.as_gl_constant()), + Some((info.width() as i32, info.height() as i32)), + ) + }, None => (None, None), }; @@ -205,7 +221,8 @@ impl WebGLFramebuffer { // that the size matches. if size.is_some() { if fb_size.is_some() && size != fb_size { - self.status.set(constants::FRAMEBUFFER_INCOMPLETE_DIMENSIONS); + self.status + .set(constants::FRAMEBUFFER_INCOMPLETE_DIMENSIONS); return; } else { fb_size = size; @@ -214,7 +231,8 @@ impl WebGLFramebuffer { if let Some(format) = format { if constraints.iter().all(|c| *c != format) { - self.status.set(constants::FRAMEBUFFER_INCOMPLETE_ATTACHMENT); + self.status + .set(constants::FRAMEBUFFER_INCOMPLETE_ATTACHMENT); return; } } @@ -225,10 +243,12 @@ impl WebGLFramebuffer { if self.size.get().map_or(false, |(w, h)| w != 0 && h != 0) { self.status.set(constants::FRAMEBUFFER_COMPLETE); } else { - self.status.set(constants::FRAMEBUFFER_INCOMPLETE_ATTACHMENT); + self.status + .set(constants::FRAMEBUFFER_INCOMPLETE_ATTACHMENT); } } else { - self.status.set(constants::FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT); + self.status + .set(constants::FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT); } } @@ -251,7 +271,10 @@ impl WebGLFramebuffer { (&self.color, constants::COLOR_BUFFER_BIT), (&self.depth, constants::DEPTH_BUFFER_BIT), (&self.stencil, constants::STENCIL_BUFFER_BIT), - (&self.depthstencil, constants::DEPTH_BUFFER_BIT | constants::STENCIL_BUFFER_BIT) + ( + &self.depthstencil, + constants::DEPTH_BUFFER_BIT | constants::STENCIL_BUFFER_BIT, + ), ]; let mut clear_bits = 0; for &(attachment, bits) in &attachments { @@ -262,7 +285,9 @@ impl WebGLFramebuffer { } } } - self.upcast::<WebGLObject>().context().initialize_framebuffer(clear_bits); + self.upcast::<WebGLObject>() + .context() + .initialize_framebuffer(clear_bits); self.is_initialized.set(true); } @@ -270,28 +295,31 @@ impl WebGLFramebuffer { } pub fn renderbuffer(&self, attachment: u32, rb: Option<&WebGLRenderbuffer>) -> WebGLResult<()> { - let binding = self.attachment_binding(attachment).ok_or(WebGLError::InvalidEnum)?; + let binding = self + .attachment_binding(attachment) + .ok_or(WebGLError::InvalidEnum)?; let rb_id = match rb { Some(rb) => { if !rb.ever_bound() { return Err(WebGLError::InvalidOperation); } - *binding.borrow_mut() = Some(WebGLFramebufferAttachment::Renderbuffer(Dom::from_ref(rb))); + *binding.borrow_mut() = + Some(WebGLFramebufferAttachment::Renderbuffer(Dom::from_ref(rb))); Some(rb.id()) - } + }, - _ => None + _ => None, }; - self.upcast::<WebGLObject>().context().send_command( - WebGLCommand::FramebufferRenderbuffer( + self.upcast::<WebGLObject>() + .context() + .send_command(WebGLCommand::FramebufferRenderbuffer( constants::FRAMEBUFFER, attachment, constants::RENDERBUFFER, rb_id, - ), - ); + )); if rb.is_none() { self.detach_binding(binding, attachment); @@ -315,15 +343,14 @@ impl WebGLFramebuffer { fn attachment_binding( &self, - attachment: u32 - ) -> Option<&DomRefCell<Option<WebGLFramebufferAttachment>>> - { + attachment: u32, + ) -> Option<&DomRefCell<Option<WebGLFramebufferAttachment>>> { match attachment { constants::COLOR_ATTACHMENT0 => Some(&self.color), constants::DEPTH_ATTACHMENT => Some(&self.depth), constants::STENCIL_ATTACHMENT => Some(&self.stencil), constants::DEPTH_STENCIL_ATTACHMENT => Some(&self.depthstencil), - _ => None + _ => None, } } @@ -332,26 +359,22 @@ impl WebGLFramebuffer { let context = self.upcast::<WebGLObject>().context(); match *attachment { WebGLFramebufferAttachment::Renderbuffer(ref rb) => { - context.send_command( - WebGLCommand::FramebufferRenderbuffer( - constants::FRAMEBUFFER, - attachment_point, - constants::RENDERBUFFER, - Some(rb.id()) - ) - ); - } + context.send_command(WebGLCommand::FramebufferRenderbuffer( + constants::FRAMEBUFFER, + attachment_point, + constants::RENDERBUFFER, + Some(rb.id()), + )); + }, WebGLFramebufferAttachment::Texture { ref texture, level } => { - context.send_command( - WebGLCommand::FramebufferTexture2D( - constants::FRAMEBUFFER, - attachment_point, - texture.target().expect("missing texture target"), - Some(texture.id()), - level - ) - ); - } + context.send_command(WebGLCommand::FramebufferTexture2D( + constants::FRAMEBUFFER, + attachment_point, + texture.target().expect("missing texture target"), + Some(texture.id()), + level, + )); + }, } }; @@ -372,12 +395,22 @@ impl WebGLFramebuffer { pub fn attachment(&self, attachment: u32) -> Option<WebGLFramebufferAttachmentRoot> { let binding = self.attachment_binding(attachment)?; - binding.borrow().as_ref().map(WebGLFramebufferAttachment::root) + binding + .borrow() + .as_ref() + .map(WebGLFramebufferAttachment::root) } - pub fn texture2d(&self, attachment: u32, textarget: u32, texture: Option<&WebGLTexture>, - level: i32) -> WebGLResult<()> { - let binding = self.attachment_binding(attachment).ok_or(WebGLError::InvalidEnum)?; + pub fn texture2d( + &self, + attachment: u32, + textarget: u32, + texture: Option<&WebGLTexture>, + level: i32, + ) -> WebGLResult<()> { + let binding = self + .attachment_binding(attachment) + .ok_or(WebGLError::InvalidEnum)?; let tex_id = match texture { // Note, from the GLES 2.0.25 spec, page 113: @@ -417,33 +450,31 @@ impl WebGLFramebuffer { }; match texture.target() { - Some(constants::TEXTURE_CUBE_MAP) if is_cube => {} - Some(_) if !is_cube => {} + Some(constants::TEXTURE_CUBE_MAP) if is_cube => {}, + Some(_) if !is_cube => {}, _ => return Err(WebGLError::InvalidOperation), } *binding.borrow_mut() = Some(WebGLFramebufferAttachment::Texture { texture: Dom::from_ref(texture), - level: level } - ); + level: level, + }); Some(texture.id()) - } + }, - _ => { - None - } + _ => None, }; - self.upcast::<WebGLObject>().context().send_command( - WebGLCommand::FramebufferTexture2D( + self.upcast::<WebGLObject>() + .context() + .send_command(WebGLCommand::FramebufferTexture2D( constants::FRAMEBUFFER, attachment, textarget, tex_id, level, - ), - ); + )); if texture.is_none() { self.detach_binding(binding, attachment); @@ -455,20 +486,24 @@ impl WebGLFramebuffer { } fn with_matching_renderbuffers<F>(&self, rb: &WebGLRenderbuffer, mut closure: F) - where F: FnMut(&DomRefCell<Option<WebGLFramebufferAttachment>>, u32) + where + F: FnMut(&DomRefCell<Option<WebGLFramebufferAttachment>>, u32), { let attachments = [ (&self.color, constants::COLOR_ATTACHMENT0), (&self.depth, constants::DEPTH_ATTACHMENT), (&self.stencil, constants::STENCIL_ATTACHMENT), - (&self.depthstencil, constants::DEPTH_STENCIL_ATTACHMENT) + (&self.depthstencil, constants::DEPTH_STENCIL_ATTACHMENT), ]; for (attachment, name) in &attachments { let matched = { match *attachment.borrow() { Some(WebGLFramebufferAttachment::Renderbuffer(ref att_rb)) - if rb.id() == att_rb.id() => true, + if rb.id() == att_rb.id() => + { + true + }, _ => false, } }; @@ -480,20 +515,27 @@ impl WebGLFramebuffer { } fn with_matching_textures<F>(&self, texture: &WebGLTexture, mut closure: F) - where F: FnMut(&DomRefCell<Option<WebGLFramebufferAttachment>>, u32) + where + F: FnMut(&DomRefCell<Option<WebGLFramebufferAttachment>>, u32), { let attachments = [ (&self.color, constants::COLOR_ATTACHMENT0), (&self.depth, constants::DEPTH_ATTACHMENT), (&self.stencil, constants::STENCIL_ATTACHMENT), - (&self.depthstencil, constants::DEPTH_STENCIL_ATTACHMENT) + (&self.depthstencil, constants::DEPTH_STENCIL_ATTACHMENT), ]; for (attachment, name) in &attachments { let matched = { match *attachment.borrow() { - Some(WebGLFramebufferAttachment::Texture { texture: ref att_texture, .. }) - if texture.id() == att_texture.id() => true, + Some(WebGLFramebufferAttachment::Texture { + texture: ref att_texture, + .. + }) + if texture.id() == att_texture.id() => + { + true + }, _ => false, } }; diff --git a/components/script/dom/webglprogram.rs b/components/script/dom/webglprogram.rs index 4fb1147e042..e6cf894feca 100644 --- a/components/script/dom/webglprogram.rs +++ b/components/script/dom/webglprogram.rs @@ -56,7 +56,10 @@ impl WebGLProgram { pub fn maybe_new(context: &WebGLRenderingContext) -> Option<DomRoot<Self>> { let (sender, receiver) = webgl_channel().unwrap(); context.send_command(WebGLCommand::CreateProgram(sender)); - receiver.recv().unwrap().map(|id| WebGLProgram::new(context, id)) + receiver + .recv() + .unwrap() + .map(|id| WebGLProgram::new(context, id)) } pub fn new(context: &WebGLRenderingContext, id: WebGLProgramId) -> DomRoot<Self> { @@ -68,7 +71,6 @@ impl WebGLProgram { } } - impl WebGLProgram { pub fn id(&self) -> WebGLProgramId { self.id @@ -129,7 +131,8 @@ impl WebGLProgram { /// glLinkProgram pub fn link(&self) -> WebGLResult<()> { self.linked.set(false); - self.link_generation.set(self.link_generation.get().checked_add(1).unwrap()); + self.link_generation + .set(self.link_generation.get().checked_add(1).unwrap()); *self.active_attribs.borrow_mut() = Box::new([]); *self.active_uniforms.borrow_mut() = Box::new([]); @@ -214,7 +217,7 @@ impl WebGLProgram { _ => { error!("detachShader: Unexpected shader type"); return Err(WebGLError::InvalidValue); - } + }, }; if shader_slot.get().is_some() { @@ -243,11 +246,11 @@ impl WebGLProgram { }; match shader_slot.get() { - Some(ref attached_shader) if attached_shader.id() != shader.id() => - return Err(WebGLError::InvalidOperation), - None => - return Err(WebGLError::InvalidOperation), - _ => {} + Some(ref attached_shader) if attached_shader.id() != shader.id() => { + return Err(WebGLError::InvalidOperation) + }, + None => return Err(WebGLError::InvalidOperation), + _ => {}, } shader_slot.set(None); @@ -276,7 +279,11 @@ impl WebGLProgram { self.upcast::<WebGLObject>() .context() - .send_command(WebGLCommand::BindAttribLocation(self.id, index, name.into())); + .send_command(WebGLCommand::BindAttribLocation( + self.id, + index, + name.into(), + )); Ok(()) } @@ -285,7 +292,9 @@ impl WebGLProgram { return Err(WebGLError::InvalidValue); } let uniforms = self.active_uniforms.borrow(); - let data = uniforms.get(index as usize).ok_or(WebGLError::InvalidValue)?; + let data = uniforms + .get(index as usize) + .ok_or(WebGLError::InvalidValue)?; Ok(WebGLActiveInfo::new( self.global().as_window(), data.size.unwrap_or(1), @@ -300,7 +309,9 @@ impl WebGLProgram { return Err(WebGLError::InvalidValue); } let attribs = self.active_attribs.borrow(); - let data = attribs.get(index as usize).ok_or(WebGLError::InvalidValue)?; + let data = attribs + .get(index as usize) + .ok_or(WebGLError::InvalidValue)?; Ok(WebGLActiveInfo::new( self.global().as_window(), data.size, @@ -328,7 +339,8 @@ impl WebGLProgram { return Ok(-1); } - let location = self.active_attribs + let location = self + .active_attribs .borrow() .iter() .find(|attrib| attrib.name == &*name) @@ -365,10 +377,16 @@ impl WebGLProgram { }; let uniforms = self.active_uniforms.borrow(); - match uniforms.iter().find(|attrib| &*attrib.base_name == base_name) { - Some(uniform) if array_index.is_none() || array_index < uniform.size => { - (uniform.size.map(|size| size - array_index.unwrap_or_default()), uniform.type_) - }, + match uniforms + .iter() + .find(|attrib| &*attrib.base_name == base_name) + { + Some(uniform) if array_index.is_none() || array_index < uniform.size => ( + uniform + .size + .map(|size| size - array_index.unwrap_or_default()), + uniform.type_, + ), _ => return Ok(None), } }; @@ -376,7 +394,11 @@ impl WebGLProgram { let (sender, receiver) = webgl_channel().unwrap(); self.upcast::<WebGLObject>() .context() - .send_command(WebGLCommand::GetUniformLocation(self.id, name.into(), sender)); + .send_command(WebGLCommand::GetUniformLocation( + self.id, + name.into(), + sender, + )); let location = receiver.recv().unwrap(); Ok(Some(WebGLUniformLocation::new( @@ -397,7 +419,7 @@ impl WebGLProgram { if self.link_called.get() { let shaders_compiled = match (self.fragment_shader.get(), self.vertex_shader.get()) { (Some(fs), Some(vs)) => fs.successfully_compiled() && vs.successfully_compiled(), - _ => false + _ => false, }; if !shaders_compiled { return Ok("One or more shaders failed to compile".to_string()); @@ -414,13 +436,15 @@ impl WebGLProgram { if self.marked_for_deletion.get() { return Err(WebGLError::InvalidValue); } - Ok(match (self.vertex_shader.get(), self.fragment_shader.get()) { - (Some(vertex_shader), Some(fragment_shader)) => { - vec![vertex_shader, fragment_shader] - } - (Some(shader), None) | (None, Some(shader)) => vec![shader], - (None, None) => vec![] - }) + Ok( + match (self.vertex_shader.get(), self.fragment_shader.get()) { + (Some(vertex_shader), Some(fragment_shader)) => { + vec![vertex_shader, fragment_shader] + }, + (Some(shader), None) | (None, Some(shader)) => vec![shader], + (None, None) => vec![], + }, + ) } pub fn link_generation(&self) -> u64 { @@ -435,12 +459,13 @@ impl Drop for WebGLProgram { } } - fn parse_uniform_name(name: &str) -> Option<(&str, Option<i32>)> { if !name.ends_with(']') { return Some((name, None)); } let bracket_pos = name[..name.len() - 1].rfind('[')?; - let index = name[(bracket_pos + 1)..(name.len() - 1)].parse::<i32>().ok()?; + let index = name[(bracket_pos + 1)..(name.len() - 1)] + .parse::<i32>() + .ok()?; Some((&name[..bracket_pos], Some(index))) } diff --git a/components/script/dom/webglrenderbuffer.rs b/components/script/dom/webglrenderbuffer.rs index 60cc25ed8f8..fd85a1b3ec7 100644 --- a/components/script/dom/webglrenderbuffer.rs +++ b/components/script/dom/webglrenderbuffer.rs @@ -42,7 +42,10 @@ impl WebGLRenderbuffer { pub fn maybe_new(context: &WebGLRenderingContext) -> Option<DomRoot<Self>> { let (sender, receiver) = webgl_channel().unwrap(); context.send_command(WebGLCommand::CreateRenderbuffer(sender)); - receiver.recv().unwrap().map(|id| WebGLRenderbuffer::new(context, id)) + receiver + .recv() + .unwrap() + .map(|id| WebGLRenderbuffer::new(context, id)) } pub fn new(context: &WebGLRenderingContext, id: WebGLRenderbufferId) -> DomRoot<Self> { @@ -54,7 +57,6 @@ impl WebGLRenderbuffer { } } - impl WebGLRenderbuffer { pub fn id(&self) -> WebGLRenderbufferId { self.id @@ -95,9 +97,7 @@ impl WebGLRenderbuffer { - GLES 2.0, 4.4.3, "Attaching Renderbuffer Images to a Framebuffer" */ let currently_bound_framebuffer = - self.upcast::<WebGLObject>() - .context() - .bound_framebuffer(); + self.upcast::<WebGLObject>().context().bound_framebuffer(); if let Some(fb) = currently_bound_framebuffer { fb.detach_renderbuffer(self); } @@ -149,14 +149,14 @@ impl WebGLRenderbuffer { // FIXME: Invalidate completeness after the call - self.upcast::<WebGLObject>().context().send_command( - WebGLCommand::RenderbufferStorage( + self.upcast::<WebGLObject>() + .context() + .send_command(WebGLCommand::RenderbufferStorage( constants::RENDERBUFFER, actual_format, width, height, - ) - ); + )); self.size.set(Some((width, height))); diff --git a/components/script/dom/webglrenderingcontext.rs b/components/script/dom/webglrenderingcontext.rs index fba14223df9..61671ee3b15 100644 --- a/components/script/dom/webglrenderingcontext.rs +++ b/components/script/dom/webglrenderingcontext.rs @@ -100,17 +100,14 @@ macro_rules! handle_object_deletion { }; } - macro_rules! optional_root_object_to_js_or_null { - ($cx: expr, $binding:expr) => { - { - rooted!(in($cx) let mut rval = NullValue()); - if let Some(object) = $binding { - object.to_jsval($cx, rval.handle_mut()); - } - rval.get() + ($cx: expr, $binding:expr) => {{ + rooted!(in($cx) let mut rval = NullValue()); + if let Some(object) = $binding { + object.to_jsval($cx, rval.handle_mut()); } - }; + rval.get() + }}; } fn has_invalid_blend_constants(arg1: u32, arg2: u32) -> bool { @@ -119,7 +116,7 @@ fn has_invalid_blend_constants(arg1: u32, arg2: u32) -> bool { (constants::ONE_MINUS_CONSTANT_COLOR, constants::ONE_MINUS_CONSTANT_ALPHA) => true, (constants::ONE_MINUS_CONSTANT_COLOR, constants::CONSTANT_ALPHA) => true, (constants::CONSTANT_COLOR, constants::ONE_MINUS_CONSTANT_ALPHA) => true, - (_, _) => false + (_, _) => false, } } @@ -176,9 +173,12 @@ impl WebGLRenderingContext { canvas: &HTMLCanvasElement, webgl_version: WebGLVersion, size: Size2D<i32>, - attrs: GLContextAttributes + attrs: GLContextAttributes, ) -> Result<WebGLRenderingContext, String> { - if let Some(true) = PREFS.get("webgl.testing.context_creation_error").as_boolean() { + if let Some(true) = PREFS + .get("webgl.testing.context_creation_error") + .as_boolean() + { return Err("WebGL context creation error forced by pref `webgl.testing.context_creation_error`".into()); } @@ -188,8 +188,9 @@ impl WebGLRenderingContext { }; let (sender, receiver) = webgl_channel().unwrap(); - webgl_chan.send(WebGLMsg::CreateContext(webgl_version, size, attrs, sender)) - .unwrap(); + webgl_chan + .send(WebGLMsg::CreateContext(webgl_version, size, attrs, sender)) + .unwrap(); let result = receiver.recv().unwrap(); result.map(|ctx_data| { @@ -229,20 +230,26 @@ impl WebGLRenderingContext { canvas: &HTMLCanvasElement, webgl_version: WebGLVersion, size: Size2D<i32>, - attrs: GLContextAttributes + attrs: GLContextAttributes, ) -> Option<DomRoot<WebGLRenderingContext>> { match WebGLRenderingContext::new_inherited(window, canvas, webgl_version, size, attrs) { - Ok(ctx) => Some(reflect_dom_object(Box::new(ctx), window, WebGLRenderingContextBinding::Wrap)), + Ok(ctx) => Some(reflect_dom_object( + Box::new(ctx), + window, + WebGLRenderingContextBinding::Wrap, + )), Err(msg) => { error!("Couldn't create WebGLRenderingContext: {}", msg); - let event = WebGLContextEvent::new(window, - atom!("webglcontextcreationerror"), - EventBubbles::DoesNotBubble, - EventCancelable::Cancelable, - DOMString::from(msg)); + let event = WebGLContextEvent::new( + window, + atom!("webglcontextcreationerror"), + EventBubbles::DoesNotBubble, + EventCancelable::Cancelable, + DOMString::from(msg), + ); event.upcast::<Event>().fire(canvas.upcast()); None - } + }, } } @@ -253,7 +260,8 @@ impl WebGLRenderingContext { fn current_vao(&self) -> DomRoot<WebGLVertexArrayObjectOES> { self.current_vao.or_init(|| { DomRoot::from_ref( - self.default_vao.init_once(|| WebGLVertexArrayObjectOES::new(self, None)), + self.default_vao + .init_once(|| WebGLVertexArrayObjectOES::new(self, None)), ) }) } @@ -283,8 +291,16 @@ impl WebGLRenderingContext { // Right now offscreen_gl_context generates a new FBO and the bound texture is changed // in order to create a new render to texture attachment. // Send a command to re-bind the TEXTURE_2D, if any. - if let Some(texture) = self.textures.active_texture_slot(constants::TEXTURE_2D).unwrap().get() { - self.send_command(WebGLCommand::BindTexture(constants::TEXTURE_2D, Some(texture.id()))); + if let Some(texture) = self + .textures + .active_texture_slot(constants::TEXTURE_2D) + .unwrap() + .get() + { + self.send_command(WebGLCommand::BindTexture( + constants::TEXTURE_2D, + Some(texture.id()), + )); } // Bound framebuffer must not change when the canvas is resized. @@ -312,7 +328,11 @@ impl WebGLRenderingContext { pub fn webgl_error(&self, err: WebGLError) { // TODO(emilio): Add useful debug messages to this - warn!("WebGL error: {:?}, previous error was {:?}", err, self.last_error.get()); + warn!( + "WebGL error: {:?}, previous error was {:?}", + err, + self.last_error.get() + ); // If an error has been detected no further errors must be // recorded until `getError` has been called @@ -343,10 +363,8 @@ impl WebGLRenderingContext { match self.bound_framebuffer.get() { Some(fb) => match fb.check_status_for_rendering() { CompleteForRendering::Complete => Ok(()), - CompleteForRendering::Incomplete => - Err(InvalidFramebufferOperation), - CompleteForRendering::MissingColorAttachment => - Err(InvalidOperation), + CompleteForRendering::Incomplete => Err(InvalidFramebufferOperation), + CompleteForRendering::MissingColorAttachment => Err(InvalidOperation), }, None => Ok(()), } @@ -371,10 +389,9 @@ impl WebGLRenderingContext { None => return, }; match self.current_program.get() { - Some(ref program) if - program.id() == location.program_id() && - program.link_generation() == location.link_generation() - => {} + Some(ref program) + if program.id() == location.program_id() && + program.link_generation() == location.link_generation() => {}, _ => return self.webgl_error(InvalidOperation), } handle_potential_webgl_error!(self, f(location)); @@ -385,18 +402,15 @@ impl WebGLRenderingContext { } fn tex_parameter(&self, target: u32, param: u32, value: TexParameterValue) { - let texture_slot = handle_potential_webgl_error!( - self, - self.textures.active_texture_slot(target), - return - ); - let texture = handle_potential_webgl_error!( - self, - texture_slot.get().ok_or(InvalidOperation), - return - ); - - if !self.extension_manager.is_get_tex_parameter_name_enabled(param) { + let texture_slot = + handle_potential_webgl_error!(self, self.textures.active_texture_slot(target), return); + let texture = + handle_potential_webgl_error!(self, texture_slot.get().ok_or(InvalidOperation), return); + + if !self + .extension_manager + .is_get_tex_parameter_name_enabled(param) + { return self.webgl_error(InvalidEnum); } @@ -423,7 +437,9 @@ impl WebGLRenderingContext { } fn mark_as_dirty(&self) { - self.canvas.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage); + self.canvas + .upcast::<Node>() + .dirty(NodeDamage::OtherNodeDamage); } fn vertex_attrib(&self, indx: u32, x: f32, y: f32, z: f32, w: f32) { @@ -443,24 +459,27 @@ impl WebGLRenderingContext { Some(fb) => return fb.size(), // The window system framebuffer is bound - None => return Some((self.DrawingBufferWidth(), - self.DrawingBufferHeight())), + None => return Some((self.DrawingBufferWidth(), self.DrawingBufferHeight())), } } // LINEAR filtering may be forbidden when using WebGL extensions. // https://www.khronos.org/registry/webgl/extensions/OES_texture_float_linear/ - fn validate_filterable_texture(&self, - texture: &WebGLTexture, - target: TexImageTarget, - level: u32, - format: TexFormat, - width: u32, - height: u32, - data_type: TexDataType) - -> bool - { - if self.extension_manager.is_filterable(data_type.as_gl_constant()) || !texture.is_using_linear_filtering() { + fn validate_filterable_texture( + &self, + texture: &WebGLTexture, + target: TexImageTarget, + level: u32, + format: TexFormat, + width: u32, + height: u32, + data_type: TexDataType, + ) -> bool { + if self + .extension_manager + .is_filterable(data_type.as_gl_constant()) || + !texture.is_using_linear_filtering() + { return true; } @@ -474,15 +493,23 @@ impl WebGLRenderingContext { } let pixels = self.prepare_pixels(format, data_type, width, height, 1, true, true, pixels); - self.tex_image_2d(texture, target, data_type, format, level, width, height, 0, 1, pixels); + self.tex_image_2d( + texture, target, data_type, format, level, width, height, 0, 1, pixels, + ); false } fn validate_stencil_actions(&self, action: u32) -> bool { match action { - 0 | constants::KEEP | constants::REPLACE | constants::INCR | constants::DECR | - constants::INVERT | constants::INCR_WRAP | constants::DECR_WRAP => true, + 0 | + constants::KEEP | + constants::REPLACE | + constants::INCR | + constants::DECR | + constants::INVERT | + constants::INCR_WRAP | + constants::DECR_WRAP => true, _ => false, } } @@ -510,9 +537,9 @@ impl WebGLRenderingContext { let img = match canvas_utils::request_image_from_cache(&window, img_url) { ImageResponse::Loaded(img, _) => img, - ImageResponse::PlaceholderLoaded(_, _) | ImageResponse::None | - ImageResponse::MetadataLoaded(_) - => return Ok(None), + ImageResponse::PlaceholderLoaded(_, _) | + ImageResponse::None | + ImageResponse::MetadataLoaded(_) => return Ok(None), }; let size = Size2D::new(img.width as i32, img.height as i32); @@ -550,14 +577,15 @@ impl WebGLRenderingContext { } // TODO(emilio): Move this logic to a validator. - fn validate_tex_image_2d_data(&self, - width: u32, - height: u32, - format: TexFormat, - data_type: TexDataType, - unpacking_alignment: u32, - data: &Option<ArrayBufferView>) - -> Result<u32, ()> { + fn validate_tex_image_2d_data( + &self, + width: u32, + height: u32, + format: TexFormat, + data_type: TexDataType, + unpacking_alignment: u32, + data: &Option<ArrayBufferView>, + ) -> Result<u32, ()> { let element_size = data_type.element_size(); let components_per_element = data_type.components_per_element(); let components = format.components(); @@ -578,8 +606,8 @@ impl WebGLRenderingContext { _ => { self.webgl_error(InvalidOperation); return Err(()); - } - } + }, + }, }; if received_size != element_size { @@ -603,19 +631,25 @@ impl WebGLRenderingContext { /// Flips the pixels in the Vec on the Y axis if /// UNPACK_FLIP_Y_WEBGL is currently enabled. - fn flip_teximage_y(&self, - pixels: Vec<u8>, - internal_format: TexFormat, - data_type: TexDataType, - width: usize, - height: usize, - unpacking_alignment: usize) -> Vec<u8> { - if !self.texture_unpacking_settings.get().contains(TextureUnpacking::FLIP_Y_AXIS) { + fn flip_teximage_y( + &self, + pixels: Vec<u8>, + internal_format: TexFormat, + data_type: TexDataType, + width: usize, + height: usize, + unpacking_alignment: usize, + ) -> Vec<u8> { + if !self + .texture_unpacking_settings + .get() + .contains(TextureUnpacking::FLIP_Y_AXIS) + { return pixels; } - let cpp = (data_type.element_size() * - internal_format.components() / data_type.components_per_element()) as usize; + let cpp = (data_type.element_size() * internal_format.components() / + data_type.components_per_element()) as usize; let stride = (width * cpp + unpacking_alignment - 1) & !(unpacking_alignment - 1); @@ -635,7 +669,11 @@ impl WebGLRenderingContext { /// Performs premultiplication of the pixels if /// UNPACK_PREMULTIPLY_ALPHA_WEBGL is currently enabled. fn premultiply_pixels(&self, format: TexFormat, data_type: TexDataType, pixels: &mut [u8]) { - if !self.texture_unpacking_settings.get().contains(TextureUnpacking::PREMULTIPLY_ALPHA) { + if !self + .texture_unpacking_settings + .get() + .contains(TextureUnpacking::PREMULTIPLY_ALPHA) + { return; } @@ -670,9 +708,9 @@ impl WebGLRenderingContext { NativeEndian::write_u16( rgba, ((multiply_u8_pixel(r, a) & 0xf0) as u16) << 8 | - ((multiply_u8_pixel(g, a) & 0xf0) as u16) << 4 | - ((multiply_u8_pixel(b, a) & 0xf0) as u16) | - ((a & 0x0f) as u16), + ((multiply_u8_pixel(g, a) & 0xf0) as u16) << 4 | + ((multiply_u8_pixel(b, a) & 0xf0) as u16) | + ((a & 0x0f) as u16), ); } }, @@ -681,16 +719,21 @@ impl WebGLRenderingContext { } } - fn prepare_pixels(&self, - internal_format: TexFormat, - data_type: TexDataType, - width: u32, - height: u32, - unpacking_alignment: u32, - source_premultiplied: bool, - source_from_image_or_canvas: bool, - mut pixels: Vec<u8>) -> Vec<u8> { - let dest_premultiply = self.texture_unpacking_settings.get().contains(TextureUnpacking::PREMULTIPLY_ALPHA); + fn prepare_pixels( + &self, + internal_format: TexFormat, + data_type: TexDataType, + width: u32, + height: u32, + unpacking_alignment: u32, + source_premultiplied: bool, + source_from_image_or_canvas: bool, + mut pixels: Vec<u8>, + ) -> Vec<u8> { + let dest_premultiply = self + .texture_unpacking_settings + .get() + .contains(TextureUnpacking::PREMULTIPLY_ALPHA); if !source_premultiplied && dest_premultiply { if source_from_image_or_canvas { // When the pixels come from image or canvas or imagedata, use RGBA8 format @@ -707,40 +750,60 @@ impl WebGLRenderingContext { } // FINISHME: Consider doing premultiply and flip in a single mutable Vec. - self.flip_teximage_y(pixels, internal_format, data_type, - width as usize, height as usize, unpacking_alignment as usize) - } - - fn tex_image_2d(&self, - texture: &WebGLTexture, - target: TexImageTarget, - data_type: TexDataType, - internal_format: TexFormat, - level: u32, - width: u32, - height: u32, - _border: u32, - unpacking_alignment: u32, - pixels: Vec<u8>) { // NB: pixels should NOT be premultipied + self.flip_teximage_y( + pixels, + internal_format, + data_type, + width as usize, + height as usize, + unpacking_alignment as usize, + ) + } + + fn tex_image_2d( + &self, + texture: &WebGLTexture, + target: TexImageTarget, + data_type: TexDataType, + internal_format: TexFormat, + level: u32, + width: u32, + height: u32, + _border: u32, + unpacking_alignment: u32, + pixels: Vec<u8>, + ) { + // NB: pixels should NOT be premultipied // TexImage2D depth is always equal to 1 - handle_potential_webgl_error!(self, texture.initialize(target, - width, - height, 1, - internal_format, - level, - Some(data_type))); + handle_potential_webgl_error!( + self, + texture.initialize( + target, + width, + height, + 1, + internal_format, + level, + Some(data_type) + ) + ); // Set the unpack alignment. For textures coming from arrays, // this will be the current value of the context's // GL_UNPACK_ALIGNMENT, while for textures from images or // canvas (produced by rgba8_image_to_tex_image_data()), it // will be 1. - self.send_command(WebGLCommand::PixelStorei(constants::UNPACK_ALIGNMENT, unpacking_alignment as i32)); + self.send_command(WebGLCommand::PixelStorei( + constants::UNPACK_ALIGNMENT, + unpacking_alignment as i32, + )); let format = internal_format.as_gl_constant(); let data_type = data_type.as_gl_constant(); - let internal_format = self.extension_manager.get_effective_tex_internal_format(format, data_type); + let internal_format = self + .extension_manager + .get_effective_tex_internal_format(format, data_type); // TODO(emilio): convert colorspace if requested let (sender, receiver) = ipc::bytes_channel().unwrap(); @@ -748,7 +811,8 @@ impl WebGLRenderingContext { target.as_gl_constant(), level as i32, internal_format as i32, - width as i32, height as i32, + width as i32, + height as i32, format, data_type, receiver, @@ -760,18 +824,20 @@ impl WebGLRenderingContext { } } - fn tex_sub_image_2d(&self, - texture: DomRoot<WebGLTexture>, - target: TexImageTarget, - level: u32, - xoffset: i32, - yoffset: i32, - width: u32, - height: u32, - format: TexFormat, - data_type: TexDataType, - unpacking_alignment: u32, - pixels: Vec<u8>) { + fn tex_sub_image_2d( + &self, + texture: DomRoot<WebGLTexture>, + target: TexImageTarget, + level: u32, + xoffset: i32, + yoffset: i32, + width: u32, + height: u32, + format: TexFormat, + data_type: TexDataType, + unpacking_alignment: u32, + pixels: Vec<u8>, + ) { // We have already validated level let image_info = texture.image_info_for_target(&target, level); @@ -779,14 +845,18 @@ impl WebGLRenderingContext { // - xoffset or yoffset is less than 0 // - x offset plus the width is greater than the texture width // - y offset plus the height is greater than the texture height - if xoffset < 0 || (xoffset as u32 + width) > image_info.width() || - yoffset < 0 || (yoffset as u32 + height) > image_info.height() { + if xoffset < 0 || + (xoffset as u32 + width) > image_info.width() || + yoffset < 0 || + (yoffset as u32 + height) > image_info.height() + { return self.webgl_error(InvalidValue); } // NB: format and internal_format must match. if format != image_info.internal_format().unwrap() || - data_type != image_info.data_type().unwrap() { + data_type != image_info.data_type().unwrap() + { return self.webgl_error(InvalidOperation); } @@ -795,7 +865,10 @@ impl WebGLRenderingContext { // GL_UNPACK_ALIGNMENT, while for textures from images or // canvas (produced by rgba8_image_to_tex_image_data()), it // will be 1. - self.send_command(WebGLCommand::PixelStorei(constants::UNPACK_ALIGNMENT, unpacking_alignment as i32)); + self.send_command(WebGLCommand::PixelStorei( + constants::UNPACK_ALIGNMENT, + unpacking_alignment as i32, + )); // TODO(emilio): convert colorspace if requested let (sender, receiver) = ipc::bytes_channel().unwrap(); @@ -838,7 +911,7 @@ impl WebGLRenderingContext { let (sender, receiver) = webgl_channel().unwrap(); self.webgl_sender.send_update_wr_image(sender).unwrap(); receiver.recv().unwrap() - } + }, } } @@ -851,13 +924,16 @@ impl WebGLRenderingContext { primcount: i32, ) -> WebGLResult<()> { match mode { - constants::POINTS | constants::LINE_STRIP | - constants::LINE_LOOP | constants::LINES | - constants::TRIANGLE_STRIP | constants::TRIANGLE_FAN | + constants::POINTS | + constants::LINE_STRIP | + constants::LINE_LOOP | + constants::LINES | + constants::TRIANGLE_STRIP | + constants::TRIANGLE_FAN | constants::TRIANGLES => {}, _ => { return Err(InvalidEnum); - } + }, } if first < 0 || count < 0 || primcount < 0 { return Err(InvalidValue); @@ -866,7 +942,10 @@ impl WebGLRenderingContext { let current_program = self.current_program.get().ok_or(InvalidOperation)?; let required_len = if count > 0 { - first.checked_add(count).map(|len| len as u32).ok_or(InvalidOperation)? + first + .checked_add(count) + .map(|len| len as u32) + .ok_or(InvalidOperation)? } else { 0 }; @@ -886,7 +965,12 @@ impl WebGLRenderingContext { self.send_command(if primcount == 1 { WebGLCommand::DrawArrays { mode, first, count } } else { - WebGLCommand::DrawArraysInstanced { mode, first, count, primcount } + WebGLCommand::DrawArraysInstanced { + mode, + first, + count, + primcount, + } }); self.mark_as_dirty(); Ok(()) @@ -902,13 +986,16 @@ impl WebGLRenderingContext { primcount: i32, ) -> WebGLResult<()> { match mode { - constants::POINTS | constants::LINE_STRIP | - constants::LINE_LOOP | constants::LINES | - constants::TRIANGLE_STRIP | constants::TRIANGLE_FAN | + constants::POINTS | + constants::LINE_STRIP | + constants::LINE_LOOP | + constants::LINES | + constants::TRIANGLE_STRIP | + constants::TRIANGLE_FAN | constants::TRIANGLES => {}, _ => { return Err(InvalidEnum); - } + }, } if count < 0 || offset < 0 || primcount < 0 { return Err(InvalidValue); @@ -924,7 +1011,11 @@ impl WebGLRenderingContext { } let current_program = self.current_program.get().ok_or(InvalidOperation)?; - let array_buffer = self.current_vao().element_array_buffer().get().ok_or(InvalidOperation)?; + let array_buffer = self + .current_vao() + .element_array_buffer() + .get() + .ok_or(InvalidOperation)?; if count > 0 && primcount > 0 { // This operation cannot overflow in u64 and we know all those values are nonnegative. @@ -935,7 +1026,11 @@ impl WebGLRenderingContext { } // TODO(nox): Pass the correct number of vertices required. - self.current_vao().validate_for_draw(0, primcount as u32, ¤t_program.active_attribs())?; + self.current_vao().validate_for_draw( + 0, + primcount as u32, + ¤t_program.active_attribs(), + )?; self.validate_framebuffer()?; @@ -945,9 +1040,20 @@ impl WebGLRenderingContext { let offset = offset as u32; self.send_command(if primcount == 1 { - WebGLCommand::DrawElements { mode, count, type_, offset } + WebGLCommand::DrawElements { + mode, + count, + type_, + offset, + } } else { - WebGLCommand::DrawElementsInstanced { mode, count, type_, offset, primcount } + WebGLCommand::DrawElementsInstanced { + mode, + count, + type_, + offset, + primcount, + } }); self.mark_as_dirty(); Ok(()) @@ -1007,7 +1113,10 @@ impl WebGLRenderingContext { pub fn create_vertex_array(&self) -> Option<DomRoot<WebGLVertexArrayObjectOES>> { let (sender, receiver) = webgl_channel().unwrap(); self.send_command(WebGLCommand::CreateVertexArray(sender)); - receiver.recv().unwrap().map(|id| WebGLVertexArrayObjectOES::new(self, Some(id))) + receiver + .recv() + .unwrap() + .map(|id| WebGLVertexArrayObjectOES::new(self, Some(id))) } pub fn delete_vertex_array(&self, vao: Option<&WebGLVertexArrayObjectOES>) { @@ -1054,15 +1163,14 @@ impl WebGLRenderingContext { fn validate_blend_mode(&self, mode: u32) -> WebGLResult<()> { match mode { - constants::FUNC_ADD | - constants::FUNC_SUBTRACT | - constants::FUNC_REVERSE_SUBTRACT => { + constants::FUNC_ADD | constants::FUNC_SUBTRACT | constants::FUNC_REVERSE_SUBTRACT => { Ok(()) - } - EXTBlendMinmaxConstants::MIN_EXT | - EXTBlendMinmaxConstants::MAX_EXT if self.extension_manager.is_blend_minmax_enabled() => { + }, + EXTBlendMinmaxConstants::MIN_EXT | EXTBlendMinmaxConstants::MAX_EXT + if self.extension_manager.is_blend_minmax_enabled() => + { Ok(()) - } + }, _ => Err(InvalidEnum), } } @@ -1123,15 +1231,11 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 - unsafe fn GetBufferParameter( - &self, - _cx: *mut JSContext, - target: u32, - parameter: u32, - ) -> JSVal { + unsafe fn GetBufferParameter(&self, _cx: *mut JSContext, target: u32, parameter: u32) -> JSVal { let buffer = handle_potential_webgl_error!( self, - self.bound_buffer(target).and_then(|buf| buf.ok_or(InvalidOperation)), + self.bound_buffer(target) + .and_then(|buf| buf.ok_or(InvalidOperation)), return NullValue() ); @@ -1141,14 +1245,17 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { _ => { self.webgl_error(InvalidEnum); NullValue() - } + }, } } #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 unsafe fn GetParameter(&self, cx: *mut JSContext, parameter: u32) -> JSVal { - if !self.extension_manager.is_get_parameter_name_enabled(parameter) { + if !self + .extension_manager + .is_get_parameter_name_enabled(parameter) + { self.webgl_error(WebGLError::InvalidEnum); return NullValue(); } @@ -1156,78 +1263,90 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { match parameter { constants::ARRAY_BUFFER_BINDING => { return optional_root_object_to_js_or_null!(cx, &self.bound_buffer_array.get()); - } + }, constants::CURRENT_PROGRAM => { return optional_root_object_to_js_or_null!(cx, &self.current_program.get()); - } + }, constants::ELEMENT_ARRAY_BUFFER_BINDING => { let buffer = self.current_vao().element_array_buffer().get(); return optional_root_object_to_js_or_null!(cx, buffer); - } + }, constants::FRAMEBUFFER_BINDING => { return optional_root_object_to_js_or_null!(cx, &self.bound_framebuffer.get()); - } + }, constants::RENDERBUFFER_BINDING => { return optional_root_object_to_js_or_null!(cx, &self.bound_renderbuffer.get()); - } + }, constants::TEXTURE_BINDING_2D => { - let texture = self.textures.active_texture_slot(constants::TEXTURE_2D).unwrap().get(); + let texture = self + .textures + .active_texture_slot(constants::TEXTURE_2D) + .unwrap() + .get(); return optional_root_object_to_js_or_null!(cx, texture); - } + }, constants::TEXTURE_BINDING_CUBE_MAP => { - let texture = self.textures.active_texture_slot(constants::TEXTURE_CUBE_MAP).unwrap().get(); + let texture = self + .textures + .active_texture_slot(constants::TEXTURE_CUBE_MAP) + .unwrap() + .get(); return optional_root_object_to_js_or_null!(cx, texture); - } + }, OESVertexArrayObjectConstants::VERTEX_ARRAY_BINDING_OES => { let vao = self.current_vao.get().filter(|vao| vao.id().is_some()); return optional_root_object_to_js_or_null!(cx, vao); - } + }, // In readPixels we currently support RGBA/UBYTE only. If // we wanted to support other formats, we could ask the // driver, but we would need to check for // GL_OES_read_format support (assuming an underlying GLES // driver. Desktop is happy to format convert for us). constants::IMPLEMENTATION_COLOR_READ_FORMAT => { - handle_potential_webgl_error!(self, self.validate_framebuffer(), return NullValue()); + handle_potential_webgl_error!( + self, + self.validate_framebuffer(), + return NullValue() + ); return Int32Value(constants::RGBA as i32); - } + }, constants::IMPLEMENTATION_COLOR_READ_TYPE => { - handle_potential_webgl_error!(self, self.validate_framebuffer(), return NullValue()); + handle_potential_webgl_error!( + self, + self.validate_framebuffer(), + return NullValue() + ); return Int32Value(constants::UNSIGNED_BYTE as i32); - } + }, constants::COMPRESSED_TEXTURE_FORMATS => { // FIXME(nox): https://github.com/servo/servo/issues/20594 rooted!(in(cx) let mut rval = ptr::null_mut::<JSObject>()); - let _ = Uint32Array::create( - cx, - CreateWith::Slice(&[]), - rval.handle_mut(), - ).unwrap(); + let _ = Uint32Array::create(cx, CreateWith::Slice(&[]), rval.handle_mut()).unwrap(); return ObjectValue(rval.get()); - } + }, constants::VERSION => { rooted!(in(cx) let mut rval = UndefinedValue()); "WebGL 1.0".to_jsval(cx, rval.handle_mut()); return rval.get(); - } + }, constants::RENDERER | constants::VENDOR => { rooted!(in(cx) let mut rval = UndefinedValue()); "Mozilla/Servo".to_jsval(cx, rval.handle_mut()); return rval.get(); - } + }, constants::SHADING_LANGUAGE_VERSION => { rooted!(in(cx) let mut rval = UndefinedValue()); "WebGL GLSL ES 1.0".to_jsval(cx, rval.handle_mut()); return rval.get(); - } + }, constants::UNPACK_FLIP_Y_WEBGL => { let unpack = self.texture_unpacking_settings.get(); return BooleanValue(unpack.contains(TextureUnpacking::FLIP_Y_AXIS)); - } + }, constants::UNPACK_PREMULTIPLY_ALPHA_WEBGL => { let unpack = self.texture_unpacking_settings.get(); return BooleanValue(unpack.contains(TextureUnpacking::PREMULTIPLY_ALPHA)); - } + }, constants::PACK_ALIGNMENT => { return UInt32Value(self.texture_packing_alignment.get() as u32); }, @@ -1248,26 +1367,22 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // Handle any MAX_ parameters by retrieving the limits that were stored // when this context was created. let limit = match parameter { - constants::MAX_VERTEX_ATTRIBS => - Some(self.limits.max_vertex_attribs), - constants::MAX_TEXTURE_SIZE => - Some(self.limits.max_tex_size), - constants::MAX_CUBE_MAP_TEXTURE_SIZE => - Some(self.limits.max_cube_map_tex_size), - constants::MAX_COMBINED_TEXTURE_IMAGE_UNITS => - Some(self.limits.max_combined_texture_image_units), - constants::MAX_FRAGMENT_UNIFORM_VECTORS => - Some(self.limits.max_fragment_uniform_vectors), - constants::MAX_RENDERBUFFER_SIZE => - Some(self.limits.max_renderbuffer_size), - constants::MAX_TEXTURE_IMAGE_UNITS => - Some(self.limits.max_texture_image_units), - constants::MAX_VARYING_VECTORS => - Some(self.limits.max_varying_vectors), - constants::MAX_VERTEX_TEXTURE_IMAGE_UNITS => - Some(self.limits.max_vertex_texture_image_units), - constants::MAX_VERTEX_UNIFORM_VECTORS => - Some(self.limits.max_vertex_uniform_vectors), + constants::MAX_VERTEX_ATTRIBS => Some(self.limits.max_vertex_attribs), + constants::MAX_TEXTURE_SIZE => Some(self.limits.max_tex_size), + constants::MAX_CUBE_MAP_TEXTURE_SIZE => Some(self.limits.max_cube_map_tex_size), + constants::MAX_COMBINED_TEXTURE_IMAGE_UNITS => { + Some(self.limits.max_combined_texture_image_units) + }, + constants::MAX_FRAGMENT_UNIFORM_VECTORS => { + Some(self.limits.max_fragment_uniform_vectors) + }, + constants::MAX_RENDERBUFFER_SIZE => Some(self.limits.max_renderbuffer_size), + constants::MAX_TEXTURE_IMAGE_UNITS => Some(self.limits.max_texture_image_units), + constants::MAX_VARYING_VECTORS => Some(self.limits.max_varying_vectors), + constants::MAX_VERTEX_TEXTURE_IMAGE_UNITS => { + Some(self.limits.max_vertex_texture_image_units) + }, + constants::MAX_VERTEX_UNIFORM_VECTORS => Some(self.limits.max_vertex_uniform_vectors), _ => None, }; if let Some(limit) = limit { @@ -1278,24 +1393,28 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { return BooleanValue(value); } - match handle_potential_webgl_error!(self, Parameter::from_u32(parameter), return NullValue()) { + match handle_potential_webgl_error!( + self, + Parameter::from_u32(parameter), + return NullValue() + ) { Parameter::Bool(param) => { let (sender, receiver) = webgl_channel().unwrap(); self.send_command(WebGLCommand::GetParameterBool(param, sender)); BooleanValue(receiver.recv().unwrap()) - } + }, Parameter::Bool4(param) => { let (sender, receiver) = webgl_channel().unwrap(); self.send_command(WebGLCommand::GetParameterBool4(param, sender)); rooted!(in(cx) let mut rval = UndefinedValue()); receiver.recv().unwrap().to_jsval(cx, rval.handle_mut()); rval.get() - } + }, Parameter::Int(param) => { let (sender, receiver) = webgl_channel().unwrap(); self.send_command(WebGLCommand::GetParameterInt(param, sender)); Int32Value(receiver.recv().unwrap()) - } + }, Parameter::Int2(param) => { let (sender, receiver) = webgl_channel().unwrap(); self.send_command(WebGLCommand::GetParameterInt2(param, sender)); @@ -1306,7 +1425,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { rval.handle_mut(), ).unwrap(); ObjectValue(rval.get()) - } + }, Parameter::Int4(param) => { let (sender, receiver) = webgl_channel().unwrap(); self.send_command(WebGLCommand::GetParameterInt4(param, sender)); @@ -1317,12 +1436,12 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { rval.handle_mut(), ).unwrap(); ObjectValue(rval.get()) - } + }, Parameter::Float(param) => { let (sender, receiver) = webgl_channel().unwrap(); self.send_command(WebGLCommand::GetParameterFloat(param, sender)); DoubleValue(receiver.recv().unwrap() as f64) - } + }, Parameter::Float2(param) => { let (sender, receiver) = webgl_channel().unwrap(); self.send_command(WebGLCommand::GetParameterFloat2(param, sender)); @@ -1333,7 +1452,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { rval.handle_mut(), ).unwrap(); ObjectValue(rval.get()) - } + }, Parameter::Float4(param) => { let (sender, receiver) = webgl_channel().unwrap(); self.send_command(WebGLCommand::GetParameterFloat4(param, sender)); @@ -1344,7 +1463,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { rval.handle_mut(), ).unwrap(); ObjectValue(rval.get()) - } + }, } } @@ -1362,7 +1481,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { return NullValue() ); - if !self.extension_manager.is_get_tex_parameter_name_enabled(pname) { + if !self + .extension_manager + .is_get_tex_parameter_name_enabled(pname) + { self.webgl_error(InvalidEnum); return NullValue(); } @@ -1370,20 +1492,21 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { match pname { constants::TEXTURE_MAG_FILTER => return UInt32Value(texture.mag_filter()), constants::TEXTURE_MIN_FILTER => return UInt32Value(texture.min_filter()), - _ => {} + _ => {}, } - match handle_potential_webgl_error!(self, TexParameter::from_u32(pname), return NullValue()) { + match handle_potential_webgl_error!(self, TexParameter::from_u32(pname), return NullValue()) + { TexParameter::Float(param) => { let (sender, receiver) = webgl_channel().unwrap(); self.send_command(WebGLCommand::GetTexParameterFloat(target, param, sender)); DoubleValue(receiver.recv().unwrap() as f64) - } + }, TexParameter::Int(param) => { let (sender, receiver) = webgl_channel().unwrap(); self.send_command(WebGLCommand::GetTexParameterInt(target, param, sender)); Int32Value(receiver.recv().unwrap()) - } + }, } } @@ -1410,7 +1533,11 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { let (sender, receiver) = webgl_channel().unwrap(); // If the send does not succeed, assume context lost - if self.webgl_sender.send(WebGLCommand::GetContextAttributes(sender)).is_err() { + if self + .webgl_sender + .send(WebGLCommand::GetContextAttributes(sender)) + .is_err() + { return None; } @@ -1424,36 +1551,38 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { preferLowPowerToHighPerformance: false, premultipliedAlpha: attrs.premultiplied_alpha, preserveDrawingBuffer: attrs.preserve_drawing_buffer, - stencil: attrs.stencil + stencil: attrs.stencil, }) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14 fn GetSupportedExtensions(&self) -> Option<Vec<DOMString>> { - self.extension_manager.init_once(|| { - self.get_gl_extensions() - }); + self.extension_manager + .init_once(|| self.get_gl_extensions()); let extensions = self.extension_manager.get_suported_extensions(); - Some(extensions.iter().map(|name| DOMString::from(*name)).collect()) + Some( + extensions + .iter() + .map(|name| DOMString::from(*name)) + .collect(), + ) } #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14 - unsafe fn GetExtension(&self, _cx: *mut JSContext, name: DOMString) - -> Option<NonNull<JSObject>> { - self.extension_manager.init_once(|| { - self.get_gl_extensions() - }); + unsafe fn GetExtension( + &self, + _cx: *mut JSContext, + name: DOMString, + ) -> Option<NonNull<JSObject>> { + self.extension_manager + .init_once(|| self.get_gl_extensions()); self.extension_manager.get_or_init_extension(&name, self) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn ActiveTexture(&self, texture: u32) { - handle_potential_webgl_error!( - self, - self.textures.set_active_unit_enum(texture), - return - ); + handle_potential_webgl_error!(self, self.textures.set_active_unit_enum(texture), return); self.send_command(WebGLCommand::ActiveTexture(texture)); } @@ -1506,7 +1635,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { return self.webgl_error(InvalidOperation); } - self.send_command(WebGLCommand::BlendFuncSeparate(src_rgb, dest_rgb, src_alpha, dest_alpha)); + self.send_command(WebGLCommand::BlendFuncSeparate( + src_rgb, dest_rgb, src_alpha, dest_alpha, + )); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 @@ -1537,13 +1668,11 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { let current_vao; let slot = match target { - constants::ARRAY_BUFFER => { - &self.bound_buffer_array - } + constants::ARRAY_BUFFER => &self.bound_buffer_array, constants::ELEMENT_ARRAY_BUFFER => { current_vao = self.current_vao(); current_vao.element_array_buffer() - } + }, _ => return self.webgl_error(InvalidEnum), }; @@ -1585,7 +1714,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } } else { // Bind the default framebuffer - let cmd = WebGLCommand::BindFramebuffer(target, WebGLFramebufferBindingRequest::Default); + let cmd = + WebGLCommand::BindFramebuffer(target, WebGLFramebufferBindingRequest::Default); self.send_command(cmd); self.bound_framebuffer.set(framebuffer); } @@ -1608,7 +1738,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { Some(renderbuffer) if !renderbuffer.is_deleted() => { self.bound_renderbuffer.set(Some(renderbuffer)); renderbuffer.bind(target); - } + }, _ => { if renderbuffer.is_some() { self.webgl_error(InvalidOperation); @@ -1617,7 +1747,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { self.bound_renderbuffer.set(None); // Unbind the currently bound renderbuffer self.send_command(WebGLCommand::BindRenderbuffer(target, None)); - } + }, } } @@ -1627,11 +1757,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { handle_potential_webgl_error!(self, self.validate_ownership(texture), return); } - let texture_slot = handle_potential_webgl_error!( - self, - self.textures.active_texture_slot(target), - return - ); + let texture_slot = + handle_potential_webgl_error!(self, self.textures.active_texture_slot(target), return); if let Some(texture) = texture { handle_potential_webgl_error!(self, texture.bind(target), return); @@ -1643,31 +1770,21 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 fn GenerateMipmap(&self, target: u32) { - let texture_slot = handle_potential_webgl_error!( - self, - self.textures.active_texture_slot(target), - return - ); - let texture = handle_potential_webgl_error!( - self, - texture_slot.get().ok_or(InvalidOperation), - return - ); + let texture_slot = + handle_potential_webgl_error!(self, self.textures.active_texture_slot(target), return); + let texture = + handle_potential_webgl_error!(self, texture_slot.get().ok_or(InvalidOperation), return); handle_potential_webgl_error!(self, texture.generate_mipmap()); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 #[allow(unsafe_code)] - fn BufferData( - &self, - target: u32, - data: Option<ArrayBufferViewOrArrayBuffer>, - usage: u32, - ) { + fn BufferData(&self, target: u32, data: Option<ArrayBufferViewOrArrayBuffer>, usage: u32) { let data = handle_potential_webgl_error!(self, data.ok_or(InvalidValue), return); let bound_buffer = handle_potential_webgl_error!(self, self.bound_buffer(target), return); - let bound_buffer = handle_potential_webgl_error!(self, bound_buffer.ok_or(InvalidOperation), return); + let bound_buffer = + handle_potential_webgl_error!(self, bound_buffer.ok_or(InvalidOperation), return); let data = unsafe { // Safe because we don't do anything with JS until the end of the method. @@ -1682,7 +1799,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 fn BufferData_(&self, target: u32, size: i64, usage: u32) { let bound_buffer = handle_potential_webgl_error!(self, self.bound_buffer(target), return); - let bound_buffer = handle_potential_webgl_error!(self, bound_buffer.ok_or(InvalidOperation), return); + let bound_buffer = + handle_potential_webgl_error!(self, bound_buffer.ok_or(InvalidOperation), return); if size < 0 { return self.webgl_error(InvalidValue); @@ -1698,7 +1816,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] fn BufferSubData(&self, target: u32, offset: i64, data: ArrayBufferViewOrArrayBuffer) { let bound_buffer = handle_potential_webgl_error!(self, self.bound_buffer(target), return); - let bound_buffer = handle_potential_webgl_error!(self, bound_buffer.ok_or(InvalidOperation), return); + let bound_buffer = + handle_potential_webgl_error!(self, bound_buffer.ok_or(InvalidOperation), return); if offset < 0 { return self.webgl_error(InvalidValue); @@ -1724,31 +1843,61 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn CompressedTexImage2D(&self, _target: u32, _level: i32, _internal_format: u32, - _width: i32, _height: i32, _border: i32, - _data: CustomAutoRooterGuard<ArrayBufferView>) { + fn CompressedTexImage2D( + &self, + _target: u32, + _level: i32, + _internal_format: u32, + _width: i32, + _height: i32, + _border: i32, + _data: CustomAutoRooterGuard<ArrayBufferView>, + ) { // FIXME: No compressed texture format is currently supported, so error out as per // https://www.khronos.org/registry/webgl/specs/latest/1.0/#COMPRESSED_TEXTURE_SUPPORT self.webgl_error(InvalidEnum); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn CompressedTexSubImage2D(&self, _target: u32, _level: i32, _xoffset: i32, - _yoffset: i32, _width: i32, _height: i32, _format: u32, - _data: CustomAutoRooterGuard<ArrayBufferView>) { + fn CompressedTexSubImage2D( + &self, + _target: u32, + _level: i32, + _xoffset: i32, + _yoffset: i32, + _width: i32, + _height: i32, + _format: u32, + _data: CustomAutoRooterGuard<ArrayBufferView>, + ) { // FIXME: No compressed texture format is currently supported, so error out as per // https://www.khronos.org/registry/webgl/specs/latest/1.0/#COMPRESSED_TEXTURE_SUPPORT self.webgl_error(InvalidEnum); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn CopyTexImage2D(&self, target: u32, level: i32, internal_format: u32, - x: i32, y: i32, width: i32, height: i32, border: i32) { + fn CopyTexImage2D( + &self, + target: u32, + level: i32, + internal_format: u32, + x: i32, + y: i32, + width: i32, + height: i32, + border: i32, + ) { handle_potential_webgl_error!(self, self.validate_framebuffer(), return); - let validator = CommonTexImage2DValidator::new(self, target, level, - internal_format, width, - height, border); + let validator = CommonTexImage2DValidator::new( + self, + target, + level, + internal_format, + width, + height, + border, + ); let CommonTexImage2DValidatorResult { texture, target, @@ -1763,33 +1912,58 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { }; // NB: TexImage2D depth is always equal to 1 - handle_potential_webgl_error!(self, texture.initialize(target, - width as u32, - height as u32, 1, - internal_format, - level as u32, - None)); - - let msg = WebGLCommand::CopyTexImage2D(target.as_gl_constant(), - level as i32, - internal_format.as_gl_constant(), - x, y, - width as i32, height as i32, - border as i32); + handle_potential_webgl_error!( + self, + texture.initialize( + target, + width as u32, + height as u32, + 1, + internal_format, + level as u32, + None + ) + ); + + let msg = WebGLCommand::CopyTexImage2D( + target.as_gl_constant(), + level as i32, + internal_format.as_gl_constant(), + x, + y, + width as i32, + height as i32, + border as i32, + ); self.send_command(msg); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn CopyTexSubImage2D(&self, target: u32, level: i32, xoffset: i32, yoffset: i32, - x: i32, y: i32, width: i32, height: i32) { + fn CopyTexSubImage2D( + &self, + target: u32, + level: i32, + xoffset: i32, + yoffset: i32, + x: i32, + y: i32, + width: i32, + height: i32, + ) { handle_potential_webgl_error!(self, self.validate_framebuffer(), return); // NB: We use a dummy (valid) format and border in order to reuse the // common validations, but this should have its own validator. - let validator = CommonTexImage2DValidator::new(self, target, level, - TexFormat::RGBA.as_gl_constant(), - width, height, 0); + let validator = CommonTexImage2DValidator::new( + self, + target, + level, + TexFormat::RGBA.as_gl_constant(), + width, + height, + 0, + ); let CommonTexImage2DValidatorResult { texture, target, @@ -1808,16 +1982,25 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // - xoffset or yoffset is less than 0 // - x offset plus the width is greater than the texture width // - y offset plus the height is greater than the texture height - if xoffset < 0 || (xoffset as u32 + width) > image_info.width() || - yoffset < 0 || (yoffset as u32 + height) > image_info.height() { - self.webgl_error(InvalidValue); - return; + if xoffset < 0 || + (xoffset as u32 + width) > image_info.width() || + yoffset < 0 || + (yoffset as u32 + height) > image_info.height() + { + self.webgl_error(InvalidValue); + return; } - let msg = WebGLCommand::CopyTexSubImage2D(target.as_gl_constant(), - level as i32, xoffset, yoffset, - x, y, - width as i32, height as i32); + let msg = WebGLCommand::CopyTexSubImage2D( + target.as_gl_constant(), + level as i32, + xoffset, + yoffset, + x, + y, + width as i32, + height as i32, + ); self.send_command(msg); } @@ -1825,7 +2008,11 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11 fn Clear(&self, mask: u32) { handle_potential_webgl_error!(self, self.validate_framebuffer(), return); - if mask & !(constants::DEPTH_BUFFER_BIT | constants::STENCIL_BUFFER_BIT | constants::COLOR_BUFFER_BIT) != 0 { + if mask & !(constants::DEPTH_BUFFER_BIT | + constants::STENCIL_BUFFER_BIT | + constants::COLOR_BUFFER_BIT) != + 0 + { return self.webgl_error(InvalidValue); } @@ -1857,8 +2044,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn CullFace(&self, mode: u32) { match mode { - constants::FRONT | constants::BACK | constants::FRONT_AND_BACK => - self.send_command(WebGLCommand::CullFace(mode)), + constants::FRONT | constants::BACK | constants::FRONT_AND_BACK => { + self.send_command(WebGLCommand::CullFace(mode)) + }, _ => self.webgl_error(InvalidEnum), } } @@ -1866,19 +2054,21 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn FrontFace(&self, mode: u32) { match mode { - constants::CW | constants::CCW => - self.send_command(WebGLCommand::FrontFace(mode)), + constants::CW | constants::CCW => self.send_command(WebGLCommand::FrontFace(mode)), _ => self.webgl_error(InvalidEnum), } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn DepthFunc(&self, func: u32) { match func { - constants::NEVER | constants::LESS | - constants::EQUAL | constants::LEQUAL | - constants::GREATER | constants::NOTEQUAL | - constants::GEQUAL | constants::ALWAYS => - self.send_command(WebGLCommand::DepthFunc(func)), + constants::NEVER | + constants::LESS | + constants::EQUAL | + constants::LEQUAL | + constants::GREATER | + constants::NOTEQUAL | + constants::GEQUAL | + constants::ALWAYS => self.send_command(WebGLCommand::DepthFunc(func)), _ => self.webgl_error(InvalidEnum), } } @@ -1957,7 +2147,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { _ => { self.webgl_error(InvalidEnum); return None; - } + }, } WebGLShader::maybe_new(self, shader_type) } @@ -1973,7 +2163,11 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { return; } self.current_vao().unbind_buffer(buffer); - if self.bound_buffer_array.get().map_or(false, |b| buffer == &*b) { + if self + .bound_buffer_array + .get() + .map_or(false, |b| buffer == &*b) + { self.bound_buffer_array.set(None); buffer.decrement_attached_counter(); } @@ -1984,9 +2178,15 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { fn DeleteFramebuffer(&self, framebuffer: Option<&WebGLFramebuffer>) { if let Some(framebuffer) = framebuffer { handle_potential_webgl_error!(self, self.validate_ownership(framebuffer), return); - handle_object_deletion!(self, self.bound_framebuffer, framebuffer, - Some(WebGLCommand::BindFramebuffer(constants::FRAMEBUFFER, - WebGLFramebufferBindingRequest::Default))); + handle_object_deletion!( + self, + self.bound_framebuffer, + framebuffer, + Some(WebGLCommand::BindFramebuffer( + constants::FRAMEBUFFER, + WebGLFramebufferBindingRequest::Default + )) + ); framebuffer.delete() } } @@ -1995,8 +2195,15 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { fn DeleteRenderbuffer(&self, renderbuffer: Option<&WebGLRenderbuffer>) { if let Some(renderbuffer) = renderbuffer { handle_potential_webgl_error!(self, self.validate_ownership(renderbuffer), return); - handle_object_deletion!(self, self.bound_renderbuffer, renderbuffer, - Some(WebGLCommand::BindRenderbuffer(constants::RENDERBUFFER, None))); + handle_object_deletion!( + self, + self.bound_renderbuffer, + renderbuffer, + Some(WebGLCommand::BindRenderbuffer( + constants::RENDERBUFFER, + None + )) + ); renderbuffer.delete() } } @@ -2059,7 +2266,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11 fn DrawElements(&self, mode: u32, count: i32, type_: u32, offset: i64) { - handle_potential_webgl_error!(self, self.draw_elements_instanced(mode, count, type_, offset, 1)); + handle_potential_webgl_error!( + self, + self.draw_elements_instanced(mode, count, type_, offset, 1) + ); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 @@ -2068,7 +2278,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { return self.webgl_error(InvalidValue); } - self.current_vao().enabled_vertex_attrib_array(attrib_id, true); + self.current_vao() + .enabled_vertex_attrib_array(attrib_id, true); self.send_command(WebGLCommand::EnableVertexAttribArray(attrib_id)); } @@ -2078,24 +2289,33 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { return self.webgl_error(InvalidValue); } - self.current_vao().enabled_vertex_attrib_array(attrib_id, false); + self.current_vao() + .enabled_vertex_attrib_array(attrib_id, false); self.send_command(WebGLCommand::DisableVertexAttribArray(attrib_id)); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn GetActiveUniform(&self, program: &WebGLProgram, index: u32) -> Option<DomRoot<WebGLActiveInfo>> { + fn GetActiveUniform( + &self, + program: &WebGLProgram, + index: u32, + ) -> Option<DomRoot<WebGLActiveInfo>> { handle_potential_webgl_error!(self, self.validate_ownership(program), return None); match program.get_active_uniform(index) { Ok(ret) => Some(ret), Err(e) => { self.webgl_error(e); return None; - } + }, } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn GetActiveAttrib(&self, program: &WebGLProgram, index: u32) -> Option<DomRoot<WebGLActiveInfo>> { + fn GetActiveAttrib( + &self, + program: &WebGLProgram, + index: u32, + ) -> Option<DomRoot<WebGLActiveInfo>> { handle_potential_webgl_error!(self, self.validate_ownership(program), return None); handle_potential_webgl_error!(self, program.get_active_attrib(index).map(Some), None) } @@ -2113,7 +2333,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { cx: *mut JSContext, target: u32, attachment: u32, - pname: u32 + pname: u32, ) -> JSVal { // Check if currently bound framebuffer is non-zero as per spec. if self.bound_framebuffer.get().is_none() { @@ -2126,7 +2346,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // constants::READ_FRAMEBUFFER | // constants::DRAW_FRAMEBUFFER => true, constants::FRAMEBUFFER => true, - _ => false + _ => false, }; let attachment_matches = match attachment { // constants::MAX_COLOR_ATTACHMENTS ... gl::COLOR_ATTACHMENT0 | @@ -2151,37 +2371,30 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { constants::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE | constants::FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE | constants::FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL => true, - _ => false + _ => false, }; - let bound_attachment_matches = match self.bound_framebuffer.get().unwrap().attachment(attachment) { - Some(attachment_root) => { - match attachment_root { - WebGLFramebufferAttachmentRoot::Renderbuffer(_) => { - match pname { - constants::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE | - constants::FRAMEBUFFER_ATTACHMENT_OBJECT_NAME => true, - _ => false - } + let bound_attachment_matches = + match self.bound_framebuffer.get().unwrap().attachment(attachment) { + Some(attachment_root) => match attachment_root { + WebGLFramebufferAttachmentRoot::Renderbuffer(_) => match pname { + constants::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE | + constants::FRAMEBUFFER_ATTACHMENT_OBJECT_NAME => true, + _ => false, }, - WebGLFramebufferAttachmentRoot::Texture(_) => { - match pname { - constants::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE | - constants::FRAMEBUFFER_ATTACHMENT_OBJECT_NAME | - constants::FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL | - constants::FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE => true, - _ => false - } - } - } - }, - _ => { - match pname { + WebGLFramebufferAttachmentRoot::Texture(_) => match pname { + constants::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE | + constants::FRAMEBUFFER_ATTACHMENT_OBJECT_NAME | + constants::FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL | + constants::FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE => true, + _ => false, + }, + }, + _ => match pname { constants::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE => true, - _ => false - } - } - }; + _ => false, + }, + }; if !target_matches || !attachment_matches || !pname_matches || !bound_attachment_matches { self.webgl_error(InvalidEnum); @@ -2217,7 +2430,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } let (sender, receiver) = webgl_channel().unwrap(); - self.send_command(WebGLCommand::GetFramebufferAttachmentParameter(target, attachment, pname, sender)); + self.send_command(WebGLCommand::GetFramebufferAttachmentParameter( + target, attachment, pname, sender, + )); Int32Value(receiver.recv().unwrap()) } @@ -2228,7 +2443,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { &self, _cx: *mut JSContext, target: u32, - pname: u32 + pname: u32, ) -> JSVal { let target_matches = target == constants::RENDERBUFFER; @@ -2260,11 +2475,12 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { rb.internal_format() as i32 } else { let (sender, receiver) = webgl_channel().unwrap(); - self.send_command(WebGLCommand::GetRenderbufferParameter(target, pname, sender)); + self.send_command(WebGLCommand::GetRenderbufferParameter( + target, pname, sender, + )); receiver.recv().unwrap() }; - Int32Value(result) } @@ -2276,13 +2492,18 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { Err(e) => { self.webgl_error(e); None - } + }, } } #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - unsafe fn GetProgramParameter(&self, _: *mut JSContext, program: &WebGLProgram, param: u32) -> JSVal { + unsafe fn GetProgramParameter( + &self, + _: *mut JSContext, + program: &WebGLProgram, + param: u32, + ) -> JSVal { handle_potential_webgl_error!(self, self.validate_ownership(program), return NullValue()); if program.is_deleted() { self.webgl_error(InvalidOperation); @@ -2297,17 +2518,22 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { let (sender, receiver) = webgl_channel().unwrap(); self.send_command(WebGLCommand::GetProgramValidateStatus(program.id(), sender)); BooleanValue(receiver.recv().unwrap()) - } + }, constants::ATTACHED_SHADERS => { // FIXME(nox): This allocates a vector and roots a couple of shaders for nothing. - Int32Value(program.attached_shaders().map(|shaders| shaders.len() as i32).unwrap_or(0)) - } + Int32Value( + program + .attached_shaders() + .map(|shaders| shaders.len() as i32) + .unwrap_or(0), + ) + }, constants::ACTIVE_ATTRIBUTES => Int32Value(program.active_attribs().len() as i32), constants::ACTIVE_UNIFORMS => Int32Value(program.active_uniforms().len() as i32), _ => { self.webgl_error(InvalidEnum); NullValue() - } + }, } } @@ -2319,7 +2545,12 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - unsafe fn GetShaderParameter(&self, _: *mut JSContext, shader: &WebGLShader, param: u32) -> JSVal { + unsafe fn GetShaderParameter( + &self, + _: *mut JSContext, + shader: &WebGLShader, + param: u32, + ) -> JSVal { handle_potential_webgl_error!(self, self.validate_ownership(shader), return NullValue()); if shader.is_deleted() { self.webgl_error(InvalidValue); @@ -2332,7 +2563,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { _ => { self.webgl_error(InvalidEnum); NullValue() - } + }, } } @@ -2340,7 +2571,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { fn GetShaderPrecisionFormat( &self, shader_type: u32, - precision_type: u32 + precision_type: u32, ) -> Option<DomRoot<WebGLShaderPrecisionFormat>> { match precision_type { constants::LOW_FLOAT | @@ -2356,12 +2587,19 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } let (sender, receiver) = webgl_channel().unwrap(); - self.send_command(WebGLCommand::GetShaderPrecisionFormat(shader_type, - precision_type, - sender)); + self.send_command(WebGLCommand::GetShaderPrecisionFormat( + shader_type, + precision_type, + sender, + )); let (range_min, range_max, precision) = receiver.recv().unwrap(); - Some(WebGLShaderPrecisionFormat::new(self.global().as_window(), range_min, range_max, precision)) + Some(WebGLShaderPrecisionFormat::new( + self.global().as_window(), + range_min, + range_max, + precision, + )) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 @@ -2393,15 +2631,15 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { receiver.recv().unwrap() }; rooted!(in(cx) let mut result = ptr::null_mut::<JSObject>()); - let _ = Float32Array::create( - cx, - CreateWith::Slice(&value), - result.handle_mut(), - ).unwrap(); + let _ = + Float32Array::create(cx, CreateWith::Slice(&value), result.handle_mut()).unwrap(); return ObjectValue(result.get()); } - if !self.extension_manager.is_get_vertex_attrib_name_enabled(param) { + if !self + .extension_manager + .is_get_vertex_attrib_name_enabled(param) + { self.webgl_error(WebGLError::InvalidEnum); return NullValue(); } @@ -2418,14 +2656,14 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { buffer.to_jsval(cx, jsval.handle_mut()); } jsval.get() - } + }, ANGLEInstancedArraysConstants::VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE => { UInt32Value(data.divisor) - } + }, _ => { self.webgl_error(InvalidEnum); NullValue() - } + }, } } @@ -2446,14 +2684,14 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn Hint(&self, target: u32, mode: u32) { - if target != constants::GENERATE_MIPMAP_HINT && !self.extension_manager.is_hint_target_enabled(target) { + if target != constants::GENERATE_MIPMAP_HINT && + !self.extension_manager.is_hint_target_enabled(target) + { return self.webgl_error(InvalidEnum); } match mode { - constants::FASTEST | - constants::NICEST | - constants::DONT_CARE => (), + constants::FASTEST | constants::NICEST | constants::DONT_CARE => (), _ => return self.webgl_error(InvalidEnum), } @@ -2482,7 +2720,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn IsProgram(&self, program: Option<&WebGLProgram>) -> bool { - program.map_or(false, |p| self.validate_ownership(p).is_ok() && !p.is_deleted()) + program.map_or(false, |p| { + self.validate_ownership(p).is_ok() && !p.is_deleted() + }) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 @@ -2494,7 +2734,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn IsShader(&self, shader: Option<&WebGLShader>) -> bool { - shader.map_or(false, |s| self.validate_ownership(s).is_ok() && !s.is_deleted()) + shader.map_or(false, |s| { + self.validate_ownership(s).is_ok() && !s.is_deleted() + }) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 @@ -2551,7 +2793,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // and then write the result at the right place in ReadPixels. self.texture_packing_alignment.set(param_value as u8); return; - } + }, _ => return self.webgl_error(InvalidEnum), } self.texture_unpacking_settings.set(texture_settings); @@ -2564,13 +2806,18 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.12 #[allow(unsafe_code)] - fn ReadPixels(&self, x: i32, y: i32, width: i32, height: i32, format: u32, pixel_type: u32, - mut pixels: CustomAutoRooterGuard<Option<ArrayBufferView>>) { - let pixels = handle_potential_webgl_error!( - self, - pixels.as_mut().ok_or(InvalidValue), - return - ); + fn ReadPixels( + &self, + x: i32, + y: i32, + width: i32, + height: i32, + format: u32, + pixel_type: u32, + mut pixels: CustomAutoRooterGuard<Option<ArrayBufferView>>, + ) { + let pixels = + handle_potential_webgl_error!(self, pixels.as_mut().ok_or(InvalidValue), return); if width < 0 || height < 0 { return self.webgl_error(InvalidValue); @@ -2658,13 +2905,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { let (sender, receiver) = ipc::bytes_channel().unwrap(); self.send_command(WebGLCommand::ReadPixels( - src_x, - src_y, - src_width, - src_height, - format, - pixel_type, - sender, + src_x, src_y, src_width, src_height, format, pixel_type, sender, )); let src = receiver.recv().unwrap(); @@ -2686,7 +2927,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.4 fn Scissor(&self, x: i32, y: i32, width: i32, height: i32) { if width < 0 || height < 0 { - return self.webgl_error(InvalidValue) + return self.webgl_error(InvalidValue); } self.current_scissor.set((x, y, width, height)); @@ -2696,9 +2937,14 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn StencilFunc(&self, func: u32, ref_: i32, mask: u32) { match func { - constants::NEVER | constants::LESS | constants::EQUAL | constants::LEQUAL | - constants::GREATER | constants::NOTEQUAL | constants::GEQUAL | constants::ALWAYS => - self.send_command(WebGLCommand::StencilFunc(func, ref_, mask)), + constants::NEVER | + constants::LESS | + constants::EQUAL | + constants::LEQUAL | + constants::GREATER | + constants::NOTEQUAL | + constants::GEQUAL | + constants::ALWAYS => self.send_command(WebGLCommand::StencilFunc(func, ref_, mask)), _ => self.webgl_error(InvalidEnum), } } @@ -2711,9 +2957,16 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } match func { - constants::NEVER | constants::LESS | constants::EQUAL | constants::LEQUAL | - constants::GREATER | constants::NOTEQUAL | constants::GEQUAL | constants::ALWAYS => - self.send_command(WebGLCommand::StencilFuncSeparate(face, func, ref_, mask)), + constants::NEVER | + constants::LESS | + constants::EQUAL | + constants::LEQUAL | + constants::GREATER | + constants::NOTEQUAL | + constants::GEQUAL | + constants::ALWAYS => { + self.send_command(WebGLCommand::StencilFuncSeparate(face, func, ref_, mask)) + }, _ => self.webgl_error(InvalidEnum), } } @@ -2726,19 +2979,20 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn StencilMaskSeparate(&self, face: u32, mask: u32) { match face { - constants::FRONT | - constants::BACK | - constants::FRONT_AND_BACK => - self.send_command(WebGLCommand::StencilMaskSeparate(face, mask)), + constants::FRONT | constants::BACK | constants::FRONT_AND_BACK => { + self.send_command(WebGLCommand::StencilMaskSeparate(face, mask)) + }, _ => return self.webgl_error(InvalidEnum), }; } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn StencilOp(&self, fail: u32, zfail: u32, zpass: u32) { - if self.validate_stencil_actions(fail) && self.validate_stencil_actions(zfail) && - self.validate_stencil_actions(zpass) { - self.send_command(WebGLCommand::StencilOp(fail, zfail, zpass)); + if self.validate_stencil_actions(fail) && + self.validate_stencil_actions(zfail) && + self.validate_stencil_actions(zpass) + { + self.send_command(WebGLCommand::StencilOp(fail, zfail, zpass)); } else { self.webgl_error(InvalidEnum) } @@ -2751,9 +3005,11 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { _ => return self.webgl_error(InvalidEnum), } - if self.validate_stencil_actions(fail) && self.validate_stencil_actions(zfail) && - self.validate_stencil_actions(zpass) { - self.send_command(WebGLCommand::StencilOpSeparate(face, fail, zfail, zpass)) + if self.validate_stencil_actions(fail) && + self.validate_stencil_actions(zfail) && + self.validate_stencil_actions(zpass) + { + self.send_command(WebGLCommand::StencilOpSeparate(face, fail, zfail, zpass)) } else { self.webgl_error(InvalidEnum) } @@ -2781,14 +3037,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform1f( - &self, - location: Option<&WebGLUniformLocation>, - val: f32, - ) { + fn Uniform1f(&self, location: Option<&WebGLUniformLocation>, val: f32) { self.with_location(location, |location| { match location.type_() { - constants::BOOL | constants::FLOAT => {} + constants::BOOL | constants::FLOAT => {}, _ => return Err(InvalidOperation), } self.send_command(WebGLCommand::Uniform1f(location.id(), val)); @@ -2797,19 +3049,15 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform1i( - &self, - location: Option<&WebGLUniformLocation>, - val: i32, - ) { + fn Uniform1i(&self, location: Option<&WebGLUniformLocation>, val: i32) { self.with_location(location, |location| { match location.type_() { - constants::BOOL | constants::INT => {} + constants::BOOL | constants::INT => {}, constants::SAMPLER_2D | constants::SAMPLER_CUBE => { if val < 0 || val as u32 >= self.limits.max_combined_texture_image_units { return Err(InvalidValue); } - } + }, _ => return Err(InvalidOperation), } self.send_command(WebGLCommand::Uniform1i(location.id(), val)); @@ -2818,14 +3066,13 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform1iv( - &self, - location: Option<&WebGLUniformLocation>, - val: Int32ArrayOrLongSequence, - ) { + fn Uniform1iv(&self, location: Option<&WebGLUniformLocation>, val: Int32ArrayOrLongSequence) { self.with_location(location, |location| { match location.type_() { - constants::BOOL | constants::INT | constants::SAMPLER_2D | constants::SAMPLER_CUBE => {} + constants::BOOL | + constants::INT | + constants::SAMPLER_2D | + constants::SAMPLER_CUBE => {}, _ => return Err(InvalidOperation), } let val = match val { @@ -2840,13 +3087,16 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } match location.type_() { constants::SAMPLER_2D | constants::SAMPLER_CUBE => { - for &v in val.iter().take(cmp::min(location.size().unwrap_or(1) as usize, val.len())) { + for &v in val + .iter() + .take(cmp::min(location.size().unwrap_or(1) as usize, val.len())) + { if v < 0 || v as u32 >= self.limits.max_combined_texture_image_units { return Err(InvalidValue); } } - } - _ => {} + }, + _ => {}, } self.send_command(WebGLCommand::Uniform1iv(location.id(), val)); Ok(()) @@ -2861,7 +3111,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { ) { self.with_location(location, |location| { match location.type_() { - constants::BOOL | constants::FLOAT => {} + constants::BOOL | constants::FLOAT => {}, _ => return Err(InvalidOperation), } let val = match val { @@ -2880,15 +3130,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform2f( - &self, - location: Option<&WebGLUniformLocation>, - x: f32, - y: f32, - ) { + fn Uniform2f(&self, location: Option<&WebGLUniformLocation>, x: f32, y: f32) { self.with_location(location, |location| { match location.type_() { - constants::BOOL_VEC2 | constants::FLOAT_VEC2 => {} + constants::BOOL_VEC2 | constants::FLOAT_VEC2 => {}, _ => return Err(InvalidOperation), } self.send_command(WebGLCommand::Uniform2f(location.id(), x, y)); @@ -2904,7 +3149,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { ) { self.with_location(location, |location| { match location.type_() { - constants::BOOL_VEC2 | constants::FLOAT_VEC2 => {} + constants::BOOL_VEC2 | constants::FLOAT_VEC2 => {}, _ => return Err(InvalidOperation), } let val = match val { @@ -2923,15 +3168,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform2i( - &self, - location: Option<&WebGLUniformLocation>, - x: i32, - y: i32, - ) { + fn Uniform2i(&self, location: Option<&WebGLUniformLocation>, x: i32, y: i32) { self.with_location(location, |location| { match location.type_() { - constants::BOOL_VEC2 | constants::INT_VEC2 => {} + constants::BOOL_VEC2 | constants::INT_VEC2 => {}, _ => return Err(InvalidOperation), } self.send_command(WebGLCommand::Uniform2i(location.id(), x, y)); @@ -2940,14 +3180,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform2iv( - &self, - location: Option<&WebGLUniformLocation>, - val: Int32ArrayOrLongSequence, - ) { + fn Uniform2iv(&self, location: Option<&WebGLUniformLocation>, val: Int32ArrayOrLongSequence) { self.with_location(location, |location| { match location.type_() { - constants::BOOL_VEC2 | constants::INT_VEC2 => {} + constants::BOOL_VEC2 | constants::INT_VEC2 => {}, _ => return Err(InvalidOperation), } let val = match val { @@ -2966,16 +3202,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform3f( - &self, - location: Option<&WebGLUniformLocation>, - x: f32, - y: f32, - z: f32, - ) { + fn Uniform3f(&self, location: Option<&WebGLUniformLocation>, x: f32, y: f32, z: f32) { self.with_location(location, |location| { match location.type_() { - constants::BOOL_VEC3 | constants::FLOAT_VEC3 => {} + constants::BOOL_VEC3 | constants::FLOAT_VEC3 => {}, _ => return Err(InvalidOperation), } self.send_command(WebGLCommand::Uniform3f(location.id(), x, y, z)); @@ -2991,7 +3221,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { ) { self.with_location(location, |location| { match location.type_() { - constants::BOOL_VEC3 | constants::FLOAT_VEC3 => {} + constants::BOOL_VEC3 | constants::FLOAT_VEC3 => {}, _ => return Err(InvalidOperation), } let val = match val { @@ -3010,16 +3240,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform3i( - &self, - location: Option<&WebGLUniformLocation>, - x: i32, - y: i32, - z: i32, - ) { + fn Uniform3i(&self, location: Option<&WebGLUniformLocation>, x: i32, y: i32, z: i32) { self.with_location(location, |location| { match location.type_() { - constants::BOOL_VEC3 | constants::INT_VEC3 => {} + constants::BOOL_VEC3 | constants::INT_VEC3 => {}, _ => return Err(InvalidOperation), } self.send_command(WebGLCommand::Uniform3i(location.id(), x, y, z)); @@ -3028,14 +3252,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform3iv( - &self, - location: Option<&WebGLUniformLocation>, - val: Int32ArrayOrLongSequence, - ) { + fn Uniform3iv(&self, location: Option<&WebGLUniformLocation>, val: Int32ArrayOrLongSequence) { self.with_location(location, |location| { match location.type_() { - constants::BOOL_VEC3 | constants::INT_VEC3 => {} + constants::BOOL_VEC3 | constants::INT_VEC3 => {}, _ => return Err(InvalidOperation), } let val = match val { @@ -3054,17 +3274,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform4i( - &self, - location: Option<&WebGLUniformLocation>, - x: i32, - y: i32, - z: i32, - w: i32, - ) { + fn Uniform4i(&self, location: Option<&WebGLUniformLocation>, x: i32, y: i32, z: i32, w: i32) { self.with_location(location, |location| { match location.type_() { - constants::BOOL_VEC4 | constants::INT_VEC4 => {} + constants::BOOL_VEC4 | constants::INT_VEC4 => {}, _ => return Err(InvalidOperation), } self.send_command(WebGLCommand::Uniform4i(location.id(), x, y, z, w)); @@ -3072,16 +3285,11 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { }); } - // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform4iv( - &self, - location: Option<&WebGLUniformLocation>, - val: Int32ArrayOrLongSequence, - ) { + fn Uniform4iv(&self, location: Option<&WebGLUniformLocation>, val: Int32ArrayOrLongSequence) { self.with_location(location, |location| { match location.type_() { - constants::BOOL_VEC4 | constants::INT_VEC4 => {} + constants::BOOL_VEC4 | constants::INT_VEC4 => {}, _ => return Err(InvalidOperation), } let val = match val { @@ -3100,17 +3308,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform4f( - &self, - location: Option<&WebGLUniformLocation>, - x: f32, - y: f32, - z: f32, - w: f32, - ) { + fn Uniform4f(&self, location: Option<&WebGLUniformLocation>, x: f32, y: f32, z: f32, w: f32) { self.with_location(location, |location| { match location.type_() { - constants::BOOL_VEC4 | constants::FLOAT_VEC4 => {} + constants::BOOL_VEC4 | constants::FLOAT_VEC4 => {}, _ => return Err(InvalidOperation), } self.send_command(WebGLCommand::Uniform4f(location.id(), x, y, z, w)); @@ -3126,7 +3327,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { ) { self.with_location(location, |location| { match location.type_() { - constants::BOOL_VEC4 | constants::FLOAT_VEC4 => {} + constants::BOOL_VEC4 | constants::FLOAT_VEC4 => {}, _ => return Err(InvalidOperation), } let val = match val { @@ -3153,7 +3354,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { ) { self.with_location(location, |location| { match location.type_() { - constants::FLOAT_MAT2 => {} + constants::FLOAT_MAT2 => {}, _ => return Err(InvalidOperation), } let val = match val { @@ -3183,7 +3384,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { ) { self.with_location(location, |location| { match location.type_() { - constants::FLOAT_MAT3 => {} + constants::FLOAT_MAT3 => {}, _ => return Err(InvalidOperation), } let val = match val { @@ -3213,7 +3414,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { ) { self.with_location(location, |location| { match location.type_() { - constants::FLOAT_MAT4 => {} + constants::FLOAT_MAT4 => {}, _ => return Err(InvalidOperation), } let val = match val { @@ -3244,8 +3445,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { ) -> JSVal { handle_potential_webgl_error!(self, self.validate_ownership(program), return NullValue()); - if - program.is_deleted() || + if program.is_deleted() || !program.is_linked() || program.id() != location.program_id() || program.link_generation() != location.link_generation() @@ -3254,10 +3454,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { return NullValue(); } - fn get<T, F>( - triple: (&WebGLRenderingContext, WebGLProgramId, i32), - f: F, - ) -> T + fn get<T, F>(triple: (&WebGLRenderingContext, WebGLProgramId, i32), f: F) -> T where F: FnOnce(WebGLProgramId, i32, WebGLSender<T>) -> WebGLCommand, T: for<'de> Deserialize<'de> + Serialize, @@ -3274,7 +3471,11 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { T: TypedArrayElementCreator, { rooted!(in(cx) let mut rval = ptr::null_mut::<JSObject>()); - <TypedArray<T, *mut JSObject>>::create(cx, CreateWith::Slice(&value), rval.handle_mut()).unwrap(); + <TypedArray<T, *mut JSObject>>::create( + cx, + CreateWith::Slice(&value), + rval.handle_mut(), + ).unwrap(); ObjectValue(rval.get()) } @@ -3284,31 +3485,39 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { rooted!(in(cx) let mut rval = NullValue()); get(triple, WebGLCommand::GetUniformBool2).to_jsval(cx, rval.handle_mut()); rval.get() - } + }, constants::BOOL_VEC3 => { rooted!(in(cx) let mut rval = NullValue()); get(triple, WebGLCommand::GetUniformBool3).to_jsval(cx, rval.handle_mut()); rval.get() - } + }, constants::BOOL_VEC4 => { rooted!(in(cx) let mut rval = NullValue()); get(triple, WebGLCommand::GetUniformBool4).to_jsval(cx, rval.handle_mut()); rval.get() - } + }, constants::INT | constants::SAMPLER_2D | constants::SAMPLER_CUBE => { Int32Value(get(triple, WebGLCommand::GetUniformInt)) - } + }, constants::INT_VEC2 => typed::<Int32>(cx, &get(triple, WebGLCommand::GetUniformInt2)), constants::INT_VEC3 => typed::<Int32>(cx, &get(triple, WebGLCommand::GetUniformInt3)), constants::INT_VEC4 => typed::<Int32>(cx, &get(triple, WebGLCommand::GetUniformInt4)), constants::FLOAT => DoubleValue(get(triple, WebGLCommand::GetUniformFloat) as f64), - constants::FLOAT_VEC2 => typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat2)), - constants::FLOAT_VEC3 => typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat3)), + constants::FLOAT_VEC2 => { + typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat2)) + }, + constants::FLOAT_VEC3 => { + typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat3)) + }, constants::FLOAT_VEC4 | constants::FLOAT_MAT2 => { typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat4)) - } - constants::FLOAT_MAT3 => typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat9)), - constants::FLOAT_MAT4 => typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat16)), + }, + constants::FLOAT_MAT3 => { + typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat9)) + }, + constants::FLOAT_MAT4 => { + typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat16)) + }, _ => panic!("wrong uniform type"), } } @@ -3327,7 +3536,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } match self.current_program.get() { Some(ref current) if program != Some(&**current) => current.in_use(false), - _ => {} + _ => {}, } self.send_command(WebGLCommand::UseProgram(program.map(|p| p.id()))); self.current_program.set(program); @@ -3425,21 +3634,15 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { ) { handle_potential_webgl_error!( self, - self.current_vao().vertex_attrib_pointer( - index, - size, - type_, - normalized, - stride, - offset, - ) + self.current_vao() + .vertex_attrib_pointer(index, size, type_, normalized, stride, offset, ) ); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.4 fn Viewport(&self, x: i32, y: i32, width: i32, height: i32) { if width < 0 || height < 0 { - return self.webgl_error(InvalidValue) + return self.webgl_error(InvalidValue); } self.send_command(WebGLCommand::SetViewport(x, y, width, height)) @@ -3462,9 +3665,17 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { return Ok(self.webgl_error(InvalidEnum)); } - let validator = TexImage2DValidator::new(self, target, level, - internal_format, width, height, - border, format, data_type); + let validator = TexImage2DValidator::new( + self, + target, + level, + internal_format, + width, + height, + border, + format, + data_type, + ); let TexImage2DValidatorResult { texture, @@ -3482,13 +3693,19 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { let unpacking_alignment = self.texture_unpacking_alignment.get(); - let expected_byte_length = - match { self.validate_tex_image_2d_data(width, height, - format, data_type, - unpacking_alignment, &*pixels) } { - Ok(byte_length) => byte_length, - Err(()) => return Ok(()), - }; + let expected_byte_length = match { + self.validate_tex_image_2d_data( + width, + height, + format, + data_type, + unpacking_alignment, + &*pixels, + ) + } { + Ok(byte_length) => byte_length, + Err(()) => return Ok(()), + }; // If data is null, a buffer of sufficient size // initialized to 0 is passed. @@ -3507,15 +3724,35 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { return Ok(self.webgl_error(InvalidOperation)); } - if !self.validate_filterable_texture(&texture, target, level, format, width, height, data_type) { + if !self + .validate_filterable_texture(&texture, target, level, format, width, height, data_type) + { return Ok(()); // The validator sets the correct error for use } - let pixels = self.prepare_pixels(format, data_type, width, height, - unpacking_alignment, false, false, buff); + let pixels = self.prepare_pixels( + format, + data_type, + width, + height, + unpacking_alignment, + false, + false, + buff, + ); - self.tex_image_2d(&texture, target, data_type, format, - level, width, height, border, unpacking_alignment, pixels); + self.tex_image_2d( + &texture, + target, + data_type, + format, + level, + width, + height, + border, + unpacking_alignment, + pixels, + ); Ok(()) } @@ -3539,10 +3776,17 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { None => return Ok(()), }; - let validator = TexImage2DValidator::new(self, - target, level, internal_format, - size.width, size.height, - 0, format, data_type); + let validator = TexImage2DValidator::new( + self, + target, + level, + internal_format, + size.width, + size.height, + 0, + format, + data_type, + ); let TexImage2DValidatorResult { texture, @@ -3558,52 +3802,79 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { Err(_) => return Ok(()), // NB: The validator sets the correct error for us. }; - if !self.validate_filterable_texture(&texture, target, level, format, width, height, data_type) { + if !self + .validate_filterable_texture(&texture, target, level, format, width, height, data_type) + { return Ok(()); // The validator sets the correct error for use } let unpacking_alignment = 1; - let pixels = self.prepare_pixels(format, data_type, width, height, - unpacking_alignment, premultiplied, true, pixels); + let pixels = self.prepare_pixels( + format, + data_type, + width, + height, + unpacking_alignment, + premultiplied, + true, + pixels, + ); - self.tex_image_2d(&texture, target, data_type, format, - level, width, height, border, 1, pixels); + self.tex_image_2d( + &texture, target, data_type, format, level, width, height, border, 1, pixels, + ); Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn TexImageDOM(&self, - target: u32, - level: i32, - internal_format: u32, - width: i32, - height: i32, - format: u32, - data_type: u32, - source: &HTMLIFrameElement) -> ErrorResult { + fn TexImageDOM( + &self, + target: u32, + level: i32, + internal_format: u32, + width: i32, + height: i32, + format: u32, + data_type: u32, + source: &HTMLIFrameElement, + ) -> ErrorResult { // Currently DOMToTexture only supports TEXTURE_2D, RGBA, UNSIGNED_BYTE and no levels. - if target != constants::TEXTURE_2D || level != 0 || internal_format != constants::RGBA || - format != constants::RGBA || data_type != constants::UNSIGNED_BYTE { + if target != constants::TEXTURE_2D || + level != 0 || + internal_format != constants::RGBA || + format != constants::RGBA || + data_type != constants::UNSIGNED_BYTE + { return Ok(self.webgl_error(InvalidValue)); } // Get bound texture let texture = handle_potential_webgl_error!( self, - self.textures.active_texture_slot(constants::TEXTURE_2D).unwrap().get().ok_or(InvalidOperation), + self.textures + .active_texture_slot(constants::TEXTURE_2D) + .unwrap() + .get() + .ok_or(InvalidOperation), return Ok(()) ); let pipeline_id = source.pipeline_id().ok_or(Error::InvalidState)?; - let document_id = self.global().downcast::<Window>().ok_or(Error::InvalidState)?.webrender_document(); + let document_id = self + .global() + .downcast::<Window>() + .ok_or(Error::InvalidState)? + .webrender_document(); texture.set_attached_to_dom(); - let command = DOMToTextureCommand::Attach(self.webgl_sender.context_id(), - texture.id(), - document_id, - pipeline_id.to_webrender(), - Size2D::new(width, height)); + let command = DOMToTextureCommand::Attach( + self.webgl_sender.context_id(), + texture.id(), + document_id, + pipeline_id.to_webrender(), + Size2D::new(width, height), + ); self.webgl_sender.send_dom_to_texture(command).unwrap(); Ok(()) @@ -3622,9 +3893,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { data_type: u32, pixels: CustomAutoRooterGuard<Option<ArrayBufferView>>, ) -> ErrorResult { - let validator = TexImage2DValidator::new(self, target, level, - format, width, height, - 0, format, data_type); + let validator = TexImage2DValidator::new( + self, target, level, format, width, height, 0, format, data_type, + ); let TexImage2DValidatorResult { texture, target, @@ -3641,13 +3912,19 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { let unpacking_alignment = self.texture_unpacking_alignment.get(); - let expected_byte_length = - match { self.validate_tex_image_2d_data(width, height, - format, data_type, - unpacking_alignment, &*pixels) } { - Ok(byte_length) => byte_length, - Err(()) => return Ok(()), - }; + let expected_byte_length = match { + self.validate_tex_image_2d_data( + width, + height, + format, + data_type, + unpacking_alignment, + &*pixels, + ) + } { + Ok(byte_length) => byte_length, + Err(()) => return Ok(()), + }; // If data is null, a buffer of sufficient size // initialized to 0 is passed. @@ -3668,11 +3945,30 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } let unpacking_alignment = self.texture_unpacking_alignment.get(); - let pixels = self.prepare_pixels(format, data_type, width, height, - unpacking_alignment, false, false, buff); + let pixels = self.prepare_pixels( + format, + data_type, + width, + height, + unpacking_alignment, + false, + false, + buff, + ); - self.tex_sub_image_2d(texture, target, level, xoffset, yoffset, - width, height, format, data_type, unpacking_alignment, pixels); + self.tex_sub_image_2d( + texture, + target, + level, + xoffset, + yoffset, + width, + height, + format, + data_type, + unpacking_alignment, + pixels, + ); Ok(()) } @@ -3692,9 +3988,17 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { None => return Ok(()), }; - let validator = TexImage2DValidator::new(self, target, level, format, - size.width, size.height, - 0, format, data_type); + let validator = TexImage2DValidator::new( + self, + target, + level, + format, + size.width, + size.height, + 0, + format, + data_type, + ); let TexImage2DValidatorResult { texture, target, @@ -3710,11 +4014,20 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { }; let unpacking_alignment = 1; - let pixels = self.prepare_pixels(format, data_type, width, height, - unpacking_alignment, premultiplied, true, pixels); + let pixels = self.prepare_pixels( + format, + data_type, + width, + height, + unpacking_alignment, + premultiplied, + true, + pixels, + ); - self.tex_sub_image_2d(texture, target, level, xoffset, yoffset, - width, height, format, data_type, 1, pixels); + self.tex_sub_image_2d( + texture, target, level, xoffset, yoffset, width, height, format, data_type, 1, pixels, + ); Ok(()) } @@ -3764,7 +4077,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { if let Some(fb) = self.bound_framebuffer.get() { fb.invalidate_renderbuffer(&*rb); } - } + }, None => self.webgl_error(InvalidOperation), }; @@ -3812,7 +4125,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } match self.bound_framebuffer.get() { - Some(fb) => handle_potential_webgl_error!(self, fb.texture2d(attachment, textarget, texture, level)), + Some(fb) => handle_potential_webgl_error!( + self, + fb.texture2d(attachment, textarget, texture, level) + ), None => self.webgl_error(InvalidOperation), }; } @@ -3913,7 +4229,10 @@ impl Textures { fn new(max_combined_textures: u32) -> Self { Self { active_unit: Default::default(), - units: (0..max_combined_textures).map(|_| Default::default()).collect::<Vec<_>>().into(), + units: (0..max_combined_textures) + .map(|_| Default::default()) + .collect::<Vec<_>>() + .into(), } } @@ -3922,7 +4241,8 @@ impl Textures { } fn set_active_unit_enum(&self, index: u32) -> WebGLResult<()> { - if index < constants::TEXTURE0 || (index - constants::TEXTURE0) as usize > self.units.len() { + if index < constants::TEXTURE0 || (index - constants::TEXTURE0) as usize > self.units.len() + { return Err(InvalidEnum); } self.active_unit.set(index - constants::TEXTURE0); @@ -3959,7 +4279,10 @@ impl Textures { } fn iter(&self) -> impl Iterator<Item = (u32, &TextureUnit)> { - self.units.iter().enumerate().map(|(index, unit)| (index as u32 + constants::TEXTURE0, unit)) + self.units + .iter() + .enumerate() + .map(|(index, unit)| (index as u32 + constants::TEXTURE0, unit)) } } @@ -4065,9 +4388,9 @@ fn rgba8_image_to_tex_image_data( let p = { let rgba = &pixels[i * 4..i * 4 + 4]; (rgba[0] as u16 & 0xf0) << 8 | - (rgba[1] as u16 & 0xf0) << 4 | - (rgba[2] as u16 & 0xf0) | - (rgba[3] as u16 & 0xf0) >> 4 + (rgba[1] as u16 & 0xf0) << 4 | + (rgba[2] as u16 & 0xf0) | + (rgba[3] as u16 & 0xf0) >> 4 }; NativeEndian::write_u16(&mut pixels[i * 2..i * 2 + 2], p); } @@ -4079,9 +4402,9 @@ fn rgba8_image_to_tex_image_data( let p = { let rgba = &pixels[i * 4..i * 4 + 4]; (rgba[0] as u16 & 0xf8) << 8 | - (rgba[1] as u16 & 0xf8) << 3 | - (rgba[2] as u16 & 0xf8) >> 2 | - (rgba[3] as u16) >> 7 + (rgba[1] as u16 & 0xf8) << 3 | + (rgba[2] as u16 & 0xf8) >> 2 | + (rgba[3] as u16) >> 7 }; NativeEndian::write_u16(&mut pixels[i * 2..i * 2 + 2], p); } @@ -4093,8 +4416,8 @@ fn rgba8_image_to_tex_image_data( let p = { let rgb = &pixels[i * 4..i * 4 + 3]; (rgb[0] as u16 & 0xf8) << 8 | - (rgb[1] as u16 & 0xfc) << 3 | - (rgb[2] as u16 & 0xf8) >> 3 + (rgb[1] as u16 & 0xfc) << 3 | + (rgb[2] as u16 & 0xf8) >> 3 }; NativeEndian::write_u16(&mut pixels[i * 2..i * 2 + 2], p); } @@ -4110,7 +4433,7 @@ fn rgba8_image_to_tex_image_data( rgbaf32.write_f32::<NativeEndian>(rgba8[3] as f32).unwrap(); } rgbaf32 - } + }, (TexFormat::RGB, TexDataType::Float) => { let mut rgbf32 = Vec::<u8>::with_capacity(pixel_count * 12); @@ -4120,7 +4443,7 @@ fn rgba8_image_to_tex_image_data( rgbf32.write_f32::<NativeEndian>(rgba8[2] as f32).unwrap(); } rgbf32 - } + }, (TexFormat::Alpha, TexDataType::Float) => { for rgba8 in pixels.chunks_mut(4) { @@ -4150,10 +4473,18 @@ fn rgba8_image_to_tex_image_data( (TexFormat::RGBA, TexDataType::HalfFloat) => { let mut rgbaf16 = Vec::<u8>::with_capacity(pixel_count * 8); for rgba8 in pixels.chunks(4) { - rgbaf16.write_u16::<NativeEndian>(f16::from_f32(rgba8[0] as f32).as_bits()).unwrap(); - rgbaf16.write_u16::<NativeEndian>(f16::from_f32(rgba8[1] as f32).as_bits()).unwrap(); - rgbaf16.write_u16::<NativeEndian>(f16::from_f32(rgba8[2] as f32).as_bits()).unwrap(); - rgbaf16.write_u16::<NativeEndian>(f16::from_f32(rgba8[3] as f32).as_bits()).unwrap(); + rgbaf16 + .write_u16::<NativeEndian>(f16::from_f32(rgba8[0] as f32).as_bits()) + .unwrap(); + rgbaf16 + .write_u16::<NativeEndian>(f16::from_f32(rgba8[1] as f32).as_bits()) + .unwrap(); + rgbaf16 + .write_u16::<NativeEndian>(f16::from_f32(rgba8[2] as f32).as_bits()) + .unwrap(); + rgbaf16 + .write_u16::<NativeEndian>(f16::from_f32(rgba8[3] as f32).as_bits()) + .unwrap(); } rgbaf16 }, @@ -4161,9 +4492,15 @@ fn rgba8_image_to_tex_image_data( (TexFormat::RGB, TexDataType::HalfFloat) => { let mut rgbf16 = Vec::<u8>::with_capacity(pixel_count * 6); for rgba8 in pixels.chunks(4) { - rgbf16.write_u16::<NativeEndian>(f16::from_f32(rgba8[0] as f32).as_bits()).unwrap(); - rgbf16.write_u16::<NativeEndian>(f16::from_f32(rgba8[1] as f32).as_bits()).unwrap(); - rgbf16.write_u16::<NativeEndian>(f16::from_f32(rgba8[2] as f32).as_bits()).unwrap(); + rgbf16 + .write_u16::<NativeEndian>(f16::from_f32(rgba8[0] as f32).as_bits()) + .unwrap(); + rgbf16 + .write_u16::<NativeEndian>(f16::from_f32(rgba8[1] as f32).as_bits()) + .unwrap(); + rgbf16 + .write_u16::<NativeEndian>(f16::from_f32(rgba8[2] as f32).as_bits()) + .unwrap(); } rgbf16 }, @@ -4196,6 +4533,6 @@ fn rgba8_image_to_tex_image_data( // Validation should have ensured that we only hit the // above cases, but we haven't turned the (format, type) // into an enum yet so there's a default case here. - _ => unreachable!("Unsupported formats {:?} {:?}", format, data_type) + _ => unreachable!("Unsupported formats {:?} {:?}", format, data_type), } } diff --git a/components/script/dom/webglshader.rs b/components/script/dom/webglshader.rs index c3ca74fde1f..685ae99505a 100644 --- a/components/script/dom/webglshader.rs +++ b/components/script/dom/webglshader.rs @@ -46,11 +46,7 @@ pub struct WebGLShader { static GLSLANG_INITIALIZATION: Once = ONCE_INIT; impl WebGLShader { - fn new_inherited( - context: &WebGLRenderingContext, - id: WebGLShaderId, - shader_type: u32, - ) -> Self { + fn new_inherited(context: &WebGLRenderingContext, id: WebGLShaderId, shader_type: u32) -> Self { GLSLANG_INITIALIZATION.call_once(|| ::mozangle::shaders::initialize().unwrap()); Self { webgl_object: WebGLObject::new_inherited(context), @@ -67,7 +63,10 @@ impl WebGLShader { pub fn maybe_new(context: &WebGLRenderingContext, shader_type: u32) -> Option<DomRoot<Self>> { let (sender, receiver) = webgl_channel().unwrap(); context.send_command(WebGLCommand::CreateShader(shader_type, sender)); - receiver.recv().unwrap().map(|id| WebGLShader::new(context, id, shader_type)) + receiver + .recv() + .unwrap() + .map(|id| WebGLShader::new(context, id, shader_type)) } pub fn new( @@ -83,7 +82,6 @@ impl WebGLShader { } } - impl WebGLShader { pub fn id(&self) -> WebGLShaderId { self.id @@ -130,9 +128,7 @@ impl WebGLShader { } else { Output::Glsl }; - ShaderValidator::for_webgl(self.gl_type, - output_format, - ¶ms).unwrap() + ShaderValidator::for_webgl(self.gl_type, output_format, ¶ms).unwrap() }, WebGLVersion::WebGL2 => { let output_format = if cfg!(any(target_os = "android", target_os = "ios")) { @@ -149,12 +145,10 @@ impl WebGLShader { (4, 30) => Output::Glsl430Core, (4, 40) => Output::Glsl440Core, (4, _) => Output::Glsl450Core, - _ => Output::Glsl140 + _ => Output::Glsl140, } }; - ShaderValidator::for_webgl2(self.gl_type, - output_format, - ¶ms).unwrap() + ShaderValidator::for_webgl2(self.gl_type, output_format, ¶ms).unwrap() }, }; @@ -167,7 +161,8 @@ impl WebGLShader { self.upcast::<WebGLObject>() .context() .send_command(WebGLCommand::CompileShader(self.id, translated_source)); - self.compilation_status.set(ShaderCompilationStatus::Succeeded); + self.compilation_status + .set(ShaderCompilationStatus::Succeeded); }, Err(error) => { self.compilation_status.set(ShaderCompilationStatus::Failed); diff --git a/components/script/dom/webglshaderprecisionformat.rs b/components/script/dom/webglshaderprecisionformat.rs index 17f32c8375d..5ac6c770c6c 100644 --- a/components/script/dom/webglshaderprecisionformat.rs +++ b/components/script/dom/webglshaderprecisionformat.rs @@ -30,14 +30,19 @@ impl WebGLShaderPrecisionFormat { } } - pub fn new(window: &Window, - range_min: i32, - range_max: i32, - precision: i32) -> DomRoot<WebGLShaderPrecisionFormat> { + pub fn new( + window: &Window, + range_min: i32, + range_max: i32, + precision: i32, + ) -> DomRoot<WebGLShaderPrecisionFormat> { reflect_dom_object( - Box::new(WebGLShaderPrecisionFormat::new_inherited(range_min, range_max, precision)), + Box::new(WebGLShaderPrecisionFormat::new_inherited( + range_min, range_max, precision, + )), window, - WebGLShaderPrecisionFormatBinding::Wrap) + WebGLShaderPrecisionFormatBinding::Wrap, + ) } } diff --git a/components/script/dom/webgltexture.rs b/components/script/dom/webgltexture.rs index 4d8e58380f7..7037656ed5c 100644 --- a/components/script/dom/webgltexture.rs +++ b/components/script/dom/webgltexture.rs @@ -69,7 +69,10 @@ impl WebGLTexture { pub fn maybe_new(context: &WebGLRenderingContext) -> Option<DomRoot<Self>> { let (sender, receiver) = webgl_channel().unwrap(); context.send_command(WebGLCommand::CreateTexture(sender)); - receiver.recv().unwrap().map(|id| WebGLTexture::new(context, id)) + receiver + .recv() + .unwrap() + .map(|id| WebGLTexture::new(context, id)) } pub fn new(context: &WebGLRenderingContext, id: WebGLTextureId) -> DomRoot<Self> { @@ -81,7 +84,6 @@ impl WebGLTexture { } } - impl WebGLTexture { pub fn id(&self) -> WebGLTextureId { self.id @@ -102,7 +104,7 @@ impl WebGLTexture { let face_count = match target { constants::TEXTURE_2D => 1, constants::TEXTURE_CUBE_MAP => 6, - _ => return Err(WebGLError::InvalidEnum) + _ => return Err(WebGLError::InvalidEnum), }; self.face_count.set(face_count); self.target.set(Some(target)); @@ -115,14 +117,16 @@ impl WebGLTexture { Ok(()) } - pub fn initialize(&self, - target: TexImageTarget, - width: u32, - height: u32, - depth: u32, - internal_format: TexFormat, - level: u32, - data_type: Option<TexDataType>) -> WebGLResult<()> { + pub fn initialize( + &self, + target: TexImageTarget, + width: u32, + height: u32, + depth: u32, + internal_format: TexFormat, + level: u32, + data_type: Option<TexDataType>, + ) -> WebGLResult<()> { let image_info = ImageInfo { width: width, height: height, @@ -143,7 +147,7 @@ impl WebGLTexture { None => { error!("Cannot generate mipmap on texture that has no target!"); return Err(WebGLError::InvalidOperation); - } + }, }; let base_image_info = self.base_image_info(); @@ -182,9 +186,9 @@ impl WebGLTexture { let context = self.upcast::<WebGLObject>().context(); // Notify WR to release the frame output when using DOMToTexture feature if self.attached_to_dom.get() { - let _ = context.webgl_sender().send_dom_to_texture( - DOMToTextureCommand::Detach(self.id), - ); + let _ = context + .webgl_sender() + .send_dom_to_texture(DOMToTextureCommand::Detach(self.id)); } /* @@ -195,9 +199,7 @@ impl WebGLTexture { - GLES 2.0, 4.4.3, "Attaching Texture Images to a Framebuffer" */ let currently_bound_framebuffer = - self.upcast::<WebGLObject>() - .context() - .bound_framebuffer(); + self.upcast::<WebGLObject>().context().bound_framebuffer(); if let Some(fb) = currently_bound_framebuffer { fb.detach_texture(self); } @@ -217,11 +219,7 @@ impl WebGLTexture { /// We have to follow the conversion rules for GLES 2.0. See: /// https://www.khronos.org/webgl/public-mailing-list/archives/1008/msg00014.html /// - pub fn tex_parameter( - &self, - param: u32, - value: TexParameterValue, - ) -> WebGLResult<()> { + pub fn tex_parameter(&self, param: u32, value: TexParameterValue) -> WebGLResult<()> { let target = self.target().unwrap(); let (int_value, float_value) = match value { @@ -240,36 +238,28 @@ impl WebGLTexture { Ok(()) }; match param { - constants::TEXTURE_MIN_FILTER => { - match int_value as u32 { - constants::NEAREST | - constants::LINEAR | - constants::NEAREST_MIPMAP_NEAREST | - constants::LINEAR_MIPMAP_NEAREST | - constants::NEAREST_MIPMAP_LINEAR | - constants::LINEAR_MIPMAP_LINEAR => update_filter(&self.min_filter), - _ => Err(WebGLError::InvalidEnum), - } - } - constants::TEXTURE_MAG_FILTER => { - match int_value as u32 { - constants::NEAREST | constants::LINEAR => update_filter(&self.mag_filter), - _ => return Err(WebGLError::InvalidEnum), - } - } - constants::TEXTURE_WRAP_S | constants::TEXTURE_WRAP_T => { - match int_value as u32 { - constants::CLAMP_TO_EDGE | - constants::MIRRORED_REPEAT | - constants::REPEAT => { - self.upcast::<WebGLObject>() - .context() - .send_command(WebGLCommand::TexParameteri(target, param, int_value)); - Ok(()) - } - _ => Err(WebGLError::InvalidEnum), - } - } + constants::TEXTURE_MIN_FILTER => match int_value as u32 { + constants::NEAREST | + constants::LINEAR | + constants::NEAREST_MIPMAP_NEAREST | + constants::LINEAR_MIPMAP_NEAREST | + constants::NEAREST_MIPMAP_LINEAR | + constants::LINEAR_MIPMAP_LINEAR => update_filter(&self.min_filter), + _ => Err(WebGLError::InvalidEnum), + }, + constants::TEXTURE_MAG_FILTER => match int_value as u32 { + constants::NEAREST | constants::LINEAR => update_filter(&self.mag_filter), + _ => return Err(WebGLError::InvalidEnum), + }, + constants::TEXTURE_WRAP_S | constants::TEXTURE_WRAP_T => match int_value as u32 { + constants::CLAMP_TO_EDGE | constants::MIRRORED_REPEAT | constants::REPEAT => { + self.upcast::<WebGLObject>() + .context() + .send_command(WebGLCommand::TexParameteri(target, param, int_value)); + Ok(()) + }, + _ => Err(WebGLError::InvalidEnum), + }, EXTTextureFilterAnisotropicConstants::TEXTURE_MAX_ANISOTROPY_EXT => { // NaN is not less than 1., what a time to be alive. if !(float_value >= 1.) { @@ -279,7 +269,7 @@ impl WebGLTexture { .context() .send_command(WebGLCommand::TexParameterf(target, param, float_value)); Ok(()) - } + }, _ => Err(WebGLError::InvalidEnum), } } @@ -294,14 +284,12 @@ impl WebGLTexture { pub fn is_using_linear_filtering(&self) -> bool { let filters = [self.min_filter.get(), self.mag_filter.get()]; - filters.iter().any(|filter| { - match *filter { - constants::LINEAR | - constants::NEAREST_MIPMAP_LINEAR | - constants::LINEAR_MIPMAP_NEAREST | - constants::LINEAR_MIPMAP_LINEAR => true, - _=> false - } + filters.iter().any(|filter| match *filter { + constants::LINEAR | + constants::NEAREST_MIPMAP_LINEAR | + constants::LINEAR_MIPMAP_NEAREST | + constants::LINEAR_MIPMAP_LINEAR => true, + _ => false, }) } @@ -359,8 +347,9 @@ impl WebGLTexture { // Compares height with width to enforce square dimensions if current_image_info.internal_format != ref_format || - current_image_info.width != ref_width || - current_image_info.height != ref_width { + current_image_info.width != ref_width || + current_image_info.height != ref_width + { return false; } } @@ -368,8 +357,7 @@ impl WebGLTexture { true } - fn face_index_for_target(&self, - target: &TexImageTarget) -> u8 { + fn face_index_for_target(&self, target: &TexImageTarget) -> u8 { match *target { TexImageTarget::Texture2D => 0, TexImageTarget::CubeMapPositiveX => 0, @@ -381,9 +369,7 @@ impl WebGLTexture { } } - pub fn image_info_for_target(&self, - target: &TexImageTarget, - level: u32) -> ImageInfo { + pub fn image_info_for_target(&self, target: &TexImageTarget, level: u32) -> ImageInfo { let face_index = self.face_index_for_target(&target); self.image_info_at_face(face_index, level) } @@ -462,8 +448,8 @@ impl ImageInfo { fn is_power_of_two(&self) -> bool { self.width.is_power_of_two() && - self.height.is_power_of_two() && - self.depth.is_power_of_two() + self.height.is_power_of_two() && + self.depth.is_power_of_two() } pub fn is_initialized(&self) -> bool { diff --git a/components/script/dom/webgluniformlocation.rs b/components/script/dom/webgluniformlocation.rs index 83ab87945a9..de3a39bf2c4 100644 --- a/components/script/dom/webgluniformlocation.rs +++ b/components/script/dom/webgluniformlocation.rs @@ -47,7 +47,13 @@ impl WebGLUniformLocation { type_: u32, ) -> DomRoot<Self> { reflect_dom_object( - Box::new(Self::new_inherited(id, program_id, link_generation, size, type_)), + Box::new(Self::new_inherited( + id, + program_id, + link_generation, + size, + type_, + )), window, WebGLUniformLocationBinding::Wrap, ) diff --git a/components/script/dom/webglvertexarrayobjectoes.rs b/components/script/dom/webglvertexarrayobjectoes.rs index ca13b2833f5..899f49d0635 100644 --- a/components/script/dom/webglvertexarrayobjectoes.rs +++ b/components/script/dom/webglvertexarrayobjectoes.rs @@ -77,7 +77,7 @@ impl WebGLVertexArrayObjectOES { } pub fn ever_bound(&self) -> bool { - return self.ever_bound.get() + return self.ever_bound.get(); } pub fn set_ever_bound(&self) { @@ -89,7 +89,9 @@ impl WebGLVertexArrayObjectOES { } pub fn get_vertex_attrib(&self, index: u32) -> Option<Ref<VertexAttribData>> { - ref_filter_map(self.vertex_attribs.borrow(), |attribs| attribs.get(index as usize)) + ref_filter_map(self.vertex_attribs.borrow(), |attribs| { + attribs.get(index as usize) + }) } pub fn vertex_attrib_pointer( @@ -102,7 +104,9 @@ impl WebGLVertexArrayObjectOES { offset: i64, ) -> WebGLResult<()> { let mut attribs = self.vertex_attribs.borrow_mut(); - let data = attribs.get_mut(index as usize).ok_or(WebGLError::InvalidValue)?; + let data = attribs + .get_mut(index as usize) + .ok_or(WebGLError::InvalidValue)?; if size < 1 || size > 4 { return Err(WebGLError::InvalidValue); @@ -129,7 +133,7 @@ impl WebGLVertexArrayObjectOES { Some(ref buffer) => buffer.increment_attached_counter(), None if offset != 0 => { // https://github.com/KhronosGroup/WebGL/pull/2228 - return Err(WebGLError::InvalidOperation) + return Err(WebGLError::InvalidOperation); }, _ => {}, } @@ -178,7 +182,11 @@ impl WebGLVertexArrayObjectOES { } attrib.buffer = None; } - if self.element_array_buffer.get().map_or(false, |b| buffer == &*b) { + if self + .element_array_buffer + .get() + .map_or(false, |b| buffer == &*b) + { buffer.decrement_attached_counter(); self.element_array_buffer.set(None); } @@ -193,7 +201,10 @@ impl WebGLVertexArrayObjectOES { // TODO(nox): Cache limits per VAO. let attribs = self.vertex_attribs.borrow(); // https://www.khronos.org/registry/webgl/specs/latest/1.0/#6.2 - if attribs.iter().any(|data| data.enabled_as_array && data.buffer.is_none()) { + if attribs + .iter() + .any(|data| data.enabled_as_array && data.buffer.is_none()) + { return Err(WebGLError::InvalidOperation); } let mut has_active_attrib = false; @@ -217,7 +228,10 @@ impl WebGLVertexArrayObjectOES { if max_vertices < required_len { return Err(WebGLError::InvalidOperation); } - } else if max_vertices.checked_mul(attrib.divisor).map_or(false, |v| v < instance_count) { + } else if max_vertices + .checked_mul(attrib.divisor) + .map_or(false, |v| v < instance_count) + { return Err(WebGLError::InvalidOperation); } } diff --git a/components/script/dom/websocket.rs b/components/script/dom/websocket.rs index ac0f14ad436..33b4098b01e 100644 --- a/components/script/dom/websocket.rs +++ b/components/script/dom/websocket.rs @@ -81,7 +81,9 @@ pub fn close_the_websocket_connection( code: code, reason: Some(reason), }; - task_source.queue_with_canceller(close_task, &canceller).unwrap(); + task_source + .queue_with_canceller(close_task, &canceller) + .unwrap(); } pub fn fail_the_websocket_connection( @@ -95,7 +97,9 @@ pub fn fail_the_websocket_connection( code: Some(close_code::ABNORMAL), reason: None, }; - task_source.queue_with_canceller(close_task, &canceller).unwrap(); + task_source + .queue_with_canceller(close_task, &canceller) + .unwrap(); } #[dom_struct] @@ -125,16 +129,24 @@ impl WebSocket { } } - fn new(global: &GlobalScope, url: ServoUrl, sender: IpcSender<WebSocketDomAction>) -> DomRoot<WebSocket> { - reflect_dom_object(Box::new(WebSocket::new_inherited(url, sender)), - global, WebSocketBinding::Wrap) + fn new( + global: &GlobalScope, + url: ServoUrl, + sender: IpcSender<WebSocketDomAction>, + ) -> DomRoot<WebSocket> { + reflect_dom_object( + Box::new(WebSocket::new_inherited(url, sender)), + global, + WebSocketBinding::Wrap, + ) } /// <https://html.spec.whatwg.org/multipage/#dom-websocket> - pub fn Constructor(global: &GlobalScope, - url: DOMString, - protocols: Option<StringOrStringSequence>) - -> Fallible<DomRoot<WebSocket>> { + pub fn Constructor( + global: &GlobalScope, + url: DOMString, + protocols: Option<StringOrStringSequence>, + ) -> Fallible<DomRoot<WebSocket>> { // Steps 1-2. let url_record = ServoUrl::parse(&url).or(Err(Error::Syntax))?; @@ -150,13 +162,11 @@ impl WebSocket { } // Step 5. - let protocols = protocols.map_or(vec![], |p| { - match p { - StringOrStringSequence::String(string) => vec![string.into()], - StringOrStringSequence::StringSequence(seq) => { - seq.into_iter().map(String::from).collect() - }, - } + let protocols = protocols.map_or(vec![], |p| match p { + StringOrStringSequence::String(string) => vec![string.into()], + StringOrStringSequence::StringSequence(seq) => { + seq.into_iter().map(String::from).collect() + }, }); // Step 6. @@ -164,7 +174,10 @@ impl WebSocket { // https://tools.ietf.org/html/rfc6455#section-4.1 // Handshake requirements, step 10 - if protocols[i + 1..].iter().any(|p| p.eq_ignore_ascii_case(protocol)) { + if protocols[i + 1..] + .iter() + .any(|p| p.eq_ignore_ascii_case(protocol)) + { return Err(Error::Syntax); } @@ -175,13 +188,14 @@ impl WebSocket { } // Create the interface for communication with the resource thread - let (dom_action_sender, resource_action_receiver): - (IpcSender<WebSocketDomAction>, - IpcReceiver<WebSocketDomAction>) = ipc::channel().unwrap(); - let (resource_event_sender, dom_event_receiver): - (IpcSender<WebSocketNetworkEvent>, - ProfiledIpc::IpcReceiver<WebSocketNetworkEvent>) = - ProfiledIpc::channel(global.time_profiler_chan().clone()).unwrap(); + let (dom_action_sender, resource_action_receiver): ( + IpcSender<WebSocketDomAction>, + IpcReceiver<WebSocketDomAction>, + ) = ipc::channel().unwrap(); + let (resource_event_sender, dom_event_receiver): ( + IpcSender<WebSocketNetworkEvent>, + ProfiledIpc::IpcReceiver<WebSocketNetworkEvent>, + ) = ProfiledIpc::channel(global.time_profiler_chan().clone()).unwrap(); let ws = WebSocket::new(global, url_record.clone(), dom_action_sender); let address = Trusted::new(&*ws); @@ -197,7 +211,9 @@ impl WebSocket { event_sender: resource_event_sender, action_receiver: resource_action_receiver, }; - let _ = global.core_resource_thread().send(CoreResourceMsg::Fetch(request, channels)); + let _ = global + .core_resource_thread() + .send(CoreResourceMsg::Fetch(request, channels)); let task_source = global.websocket_task_source(); let canceller = global.task_canceller(WebsocketTaskSource::NAME); @@ -209,22 +225,30 @@ impl WebSocket { address: address.clone(), protocol_in_use, }; - task_source.queue_with_canceller(open_thread, &canceller).unwrap(); + task_source + .queue_with_canceller(open_thread, &canceller) + .unwrap(); }, WebSocketNetworkEvent::MessageReceived(message) => { let message_thread = MessageReceivedTask { address: address.clone(), message: message, }; - task_source.queue_with_canceller(message_thread, &canceller).unwrap(); + task_source + .queue_with_canceller(message_thread, &canceller) + .unwrap(); }, WebSocketNetworkEvent::Fail => { - fail_the_websocket_connection(address.clone(), - &task_source, &canceller); + fail_the_websocket_connection(address.clone(), &task_source, &canceller); }, WebSocketNetworkEvent::Close(code, reason) => { - close_the_websocket_connection(address.clone(), - &task_source, &canceller, code, reason); + close_the_websocket_connection( + address.clone(), + &task_source, + &canceller, + code, + reason, + ); }, } } @@ -248,7 +272,7 @@ impl WebSocket { match data_byte_len.checked_add(self.buffered_amount.get()) { None => panic!(), - Some(new_amount) => self.buffered_amount.set(new_amount) + Some(new_amount) => self.buffered_amount.set(new_amount), }; if return_after_buffer { @@ -258,9 +282,7 @@ impl WebSocket { if !self.clearing_buffer.get() && self.ready_state.get() == WebSocketRequestState::Open { self.clearing_buffer.set(true); - let task = Box::new(BufferedAmountTask { - address: address, - }); + let task = Box::new(BufferedAmountTask { address: address }); let pipeline_id = self.global().pipeline_id(); self.global() @@ -323,7 +345,7 @@ impl WebSocketMethods for WebSocket { // https://html.spec.whatwg.org/multipage/#dom-websocket-protocol fn Protocol(&self) -> DOMString { - DOMString::from(self.protocol.borrow().clone()) + DOMString::from(self.protocol.borrow().clone()) } // https://html.spec.whatwg.org/multipage/#dom-websocket-send @@ -332,7 +354,9 @@ impl WebSocketMethods for WebSocket { let send_data = self.send_impl(data_byte_len)?; if send_data { - let _ = self.sender.send(WebSocketDomAction::SendMessage(MessageData::Text(data.0))); + let _ = self + .sender + .send(WebSocketDomAction::SendMessage(MessageData::Text(data.0))); } Ok(()) @@ -349,7 +373,9 @@ impl WebSocketMethods for WebSocket { if send_data { let bytes = blob.get_bytes().unwrap_or(vec![]); - let _ = self.sender.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes))); + let _ = self + .sender + .send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes))); } Ok(()) @@ -362,7 +388,9 @@ impl WebSocketMethods for WebSocket { let send_data = self.send_impl(data_byte_len as u64)?; if send_data { - let _ = self.sender.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes))); + let _ = self + .sender + .send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes))); } Ok(()) } @@ -374,7 +402,9 @@ impl WebSocketMethods for WebSocket { let send_data = self.send_impl(data_byte_len as u64)?; if send_data { - let _ = self.sender.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes))); + let _ = self + .sender + .send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes))); } Ok(()) } @@ -388,14 +418,16 @@ impl WebSocketMethods for WebSocket { } } if let Some(ref reason) = reason { - if reason.0.as_bytes().len() > 123 { //reason cannot be larger than 123 bytes + if reason.0.as_bytes().len() > 123 { + //reason cannot be larger than 123 bytes return Err(Error::Syntax); } } match self.ready_state.get() { - WebSocketRequestState::Closing | WebSocketRequestState::Closed => {} //Do nothing - WebSocketRequestState::Connecting => { //Connection is not yet established + WebSocketRequestState::Closing | WebSocketRequestState::Closed => {}, //Do nothing + WebSocketRequestState::Connecting => { + //Connection is not yet established /*By setting the state to closing, the open function will abort connecting the websocket*/ self.ready_state.set(WebSocketRequestState::Closing); @@ -405,10 +437,12 @@ impl WebSocketMethods for WebSocket { // https://html.spec.whatwg.org/multipage/#websocket-task-source // When making the switch, also update the task_canceller call. let task_source = self.global().websocket_task_source(); - fail_the_websocket_connection(address, - &task_source, - &self.global().task_canceller(WebsocketTaskSource::NAME)); - } + fail_the_websocket_connection( + address, + &task_source, + &self.global().task_canceller(WebsocketTaskSource::NAME), + ); + }, WebSocketRequestState::Open => { self.ready_state.set(WebSocketRequestState::Closing); @@ -416,13 +450,12 @@ impl WebSocketMethods for WebSocket { // https://tools.ietf.org/html/rfc6455#section-7.1.2 let reason = reason.map(|reason| reason.0); let _ = self.sender.send(WebSocketDomAction::Close(code, reason)); - } + }, } Ok(()) //Return Ok } } - /// Task queued when *the WebSocket connection is established*. /// <https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol:concept-websocket-established> struct ConnectionEstablishedTask { @@ -500,13 +533,15 @@ impl TaskOnce for CloseTask { let clean_close = !self.failed; let code = self.code.unwrap_or(close_code::NO_STATUS); let reason = DOMString::from(self.reason.unwrap_or("".to_owned())); - let close_event = CloseEvent::new(&ws.global(), - atom!("close"), - EventBubbles::DoesNotBubble, - EventCancelable::NotCancelable, - clean_close, - code, - reason); + let close_event = CloseEvent::new( + &ws.global(), + atom!("close"), + EventBubbles::DoesNotBubble, + EventCancelable::NotCancelable, + clean_close, + code, + reason, + ); close_event.upcast::<Event>().fire(ws.upcast()); } } @@ -520,8 +555,11 @@ impl TaskOnce for MessageReceivedTask { #[allow(unsafe_code)] fn run_once(self) { let ws = self.address.root(); - debug!("MessageReceivedTask::handler({:p}): readyState={:?}", &*ws, - ws.ready_state.get()); + debug!( + "MessageReceivedTask::handler({:p}): readyState={:?}", + &*ws, + ws.ready_state.get() + ); // Step 1. if ws.ready_state.get() != WebSocketRequestState::Open { @@ -537,30 +575,31 @@ impl TaskOnce for MessageReceivedTask { rooted!(in(cx) let mut message = UndefinedValue()); match self.message { MessageData::Text(text) => text.to_jsval(cx, message.handle_mut()), - MessageData::Binary(data) => { - match ws.binary_type.get() { - BinaryType::Blob => { - let blob = Blob::new(&global, BlobImpl::new_from_bytes(data), "".to_owned()); - blob.to_jsval(cx, message.handle_mut()); - } - BinaryType::Arraybuffer => { - rooted!(in(cx) let mut array_buffer = ptr::null_mut::<JSObject>()); - assert!(ArrayBuffer::create(cx, - CreateWith::Slice(&data), - array_buffer.handle_mut()) - .is_ok()); - - (*array_buffer).to_jsval(cx, message.handle_mut()); - } - - } + MessageData::Binary(data) => match ws.binary_type.get() { + BinaryType::Blob => { + let blob = + Blob::new(&global, BlobImpl::new_from_bytes(data), "".to_owned()); + blob.to_jsval(cx, message.handle_mut()); + }, + BinaryType::Arraybuffer => { + rooted!(in(cx) let mut array_buffer = ptr::null_mut::<JSObject>()); + assert!( + ArrayBuffer::create( + cx, + CreateWith::Slice(&data), + array_buffer.handle_mut() + ).is_ok() + ); + + (*array_buffer).to_jsval(cx, message.handle_mut()); + }, }, } MessageEvent::dispatch_jsval( ws.upcast(), &global, message.handle(), - Some(&ws.origin().ascii_serialization()) + Some(&ws.origin().ascii_serialization()), ); } } diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 4c5e955cded..ff905ab55b5 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -139,7 +139,7 @@ use webvr_traits::WebVRMsg; #[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)] enum WindowState { Alive, - Zombie, // Pipeline is closed, but the window hasn't been GCed yet. + Zombie, // Pipeline is closed, but the window hasn't been GCed yet. } /// Extra information concerning the reason for reflowing. @@ -332,7 +332,9 @@ impl Window { fn ignore_all_events(&self) { let mut ignore_flags = self.ignore_further_async_events.borrow_mut(); for task_source_name in TaskSourceName::all() { - let flag = ignore_flags.entry(task_source_name).or_insert(Default::default()); + let flag = ignore_flags + .entry(task_source_name) + .or_insert(Default::default()); flag.store(true, Ordering::Relaxed); } } @@ -407,12 +409,13 @@ impl Window { /// Returns the window proxy if it has not been discarded. /// <https://html.spec.whatwg.org/multipage/#a-browsing-context-is-discarded> pub fn undiscarded_window_proxy(&self) -> Option<DomRoot<WindowProxy>> { - self.window_proxy.get() - .and_then(|window_proxy| if window_proxy.is_browsing_context_discarded() { + self.window_proxy.get().and_then(|window_proxy| { + if window_proxy.is_browsing_context_discarded() { None } else { Some(window_proxy) - }) + } + }) } pub fn bluetooth_thread(&self) -> IpcSender<BluetoothRequest> { @@ -420,7 +423,7 @@ impl Window { } pub fn bluetooth_extra_permission_data(&self) -> &BluetoothExtraPermissionData { - &self.bluetooth_extra_permission_data + &self.bluetooth_extra_permission_data } pub fn css_error_reporter(&self) -> Option<&ParseErrorReporter> { @@ -451,7 +454,9 @@ impl Window { Worklet::new(self, WorkletGlobalScopeType::Paint) } - pub fn permission_state_invocation_results(&self) -> &DomRefCell<HashMap<String, PermissionState>> { + pub fn permission_state_invocation_results( + &self, + ) -> &DomRefCell<HashMap<String, PermissionState>> { &self.permission_state_invocation_results } @@ -469,10 +474,12 @@ impl Window { node.dirty(NodeDamage::OtherNodeDamage); } match response.response { - ImageResponse::MetadataLoaded(_) => {} + ImageResponse::MetadataLoaded(_) => {}, ImageResponse::Loaded(_, _) | ImageResponse::PlaceholderLoaded(_, _) | - ImageResponse::None => { nodes.remove(); } + ImageResponse::None => { + nodes.remove(); + }, } self.add_pending_reflow(); } @@ -504,7 +511,8 @@ pub fn base64_atob(input: DOMString) -> Fallible<DOMString> { fn is_html_space(c: char) -> bool { HTML_SPACE_CHARACTERS.iter().any(|&m| m == c) } - let without_spaces = input.chars() + let without_spaces = input + .chars() .filter(|&c| !is_html_space(c)) .collect::<String>(); let mut input = &*without_spaces; @@ -523,7 +531,7 @@ pub fn base64_atob(input: DOMString) -> Fallible<DOMString> { // "If the length of input divides by 4 leaving a remainder of 1, // throw an InvalidCharacterError exception and abort these steps." if input.len() % 4 == 1 { - return Err(Error::InvalidCharacter) + return Err(Error::InvalidCharacter); } // "If input contains a character that is not in the following list of @@ -533,13 +541,18 @@ pub fn base64_atob(input: DOMString) -> Fallible<DOMString> { // U+002B PLUS SIGN (+) // U+002F SOLIDUS (/) // Alphanumeric ASCII characters" - if input.chars().any(|c| c != '+' && c != '/' && !c.is_alphanumeric()) { - return Err(Error::InvalidCharacter) + if input + .chars() + .any(|c| c != '+' && c != '/' && !c.is_alphanumeric()) + { + return Err(Error::InvalidCharacter); } match base64::decode(&input) { - Ok(data) => Ok(DOMString::from(data.iter().map(|&b| b as char).collect::<String>())), - Err(..) => Err(Error::InvalidCharacter) + Ok(data) => Ok(DOMString::from( + data.iter().map(|&b| b as char).collect::<String>(), + )), + Err(..) => Err(Error::InvalidCharacter), } } @@ -563,7 +576,8 @@ impl WindowMethods for Window { stdout.flush().unwrap(); stderr.flush().unwrap(); } - let (sender, receiver) = ProfiledIpc::channel(self.global().time_profiler_chan().clone()).unwrap(); + let (sender, receiver) = + ProfiledIpc::channel(self.global().time_profiler_chan().clone()).unwrap(); let msg = EmbedderMsg::Alert(s.to_string(), sender); self.send_to_embedder(msg); receiver.recv().unwrap(); @@ -577,11 +591,12 @@ impl WindowMethods for Window { } // https://html.spec.whatwg.org/multipage/#dom-open - fn Open(&self, - url: DOMString, - target: DOMString, - features: DOMString) - -> Option<DomRoot<WindowProxy>> { + fn Open( + &self, + url: DOMString, + target: DOMString, + features: DOMString, + ) -> Option<DomRoot<WindowProxy>> { self.window_proxy().open(url, target, features) } @@ -600,16 +615,19 @@ impl WindowMethods for Window { } // Step 2. let obj = self.reflector().get_jsobject(); - assert!(JS_DefineProperty(cx, - obj, - "opener\0".as_ptr() as *const libc::c_char, - value, - JSPROP_ENUMERATE as u32)); + assert!(JS_DefineProperty( + cx, + obj, + "opener\0".as_ptr() as *const libc::c_char, + value, + JSPROP_ENUMERATE as u32 + )); } // https://html.spec.whatwg.org/multipage/#dom-window-closed fn Closed(&self) -> bool { - self.window_proxy.get() + self.window_proxy + .get() .map(|ref proxy| proxy.is_browsing_context_discarded()) .unwrap_or(true) } @@ -641,7 +659,9 @@ impl WindowMethods for Window { // https://html.spec.whatwg.org/multipage/#dom-document-2 fn Document(&self) -> DomRoot<Document> { - self.document.get().expect("Document accessed before initialization.") + self.document + .get() + .expect("Document accessed before initialization.") } // https://html.spec.whatwg.org/multipage/#dom-history @@ -651,7 +671,8 @@ impl WindowMethods for Window { // https://html.spec.whatwg.org/multipage/#dom-window-customelements fn CustomElements(&self) -> DomRoot<CustomElementRegistry> { - self.custom_element_registry.or_init(|| CustomElementRegistry::new(self)) + self.custom_element_registry + .or_init(|| CustomElementRegistry::new(self)) } // https://html.spec.whatwg.org/multipage/#dom-location @@ -661,12 +682,14 @@ impl WindowMethods for Window { // https://html.spec.whatwg.org/multipage/#dom-sessionstorage fn SessionStorage(&self) -> DomRoot<Storage> { - self.session_storage.or_init(|| Storage::new(self, StorageType::Session)) + self.session_storage + .or_init(|| Storage::new(self, StorageType::Session)) } // https://html.spec.whatwg.org/multipage/#dom-localstorage fn LocalStorage(&self) -> DomRoot<Storage> { - self.local_storage.or_init(|| Storage::new(self, StorageType::Local)) + self.local_storage + .or_init(|| Storage::new(self, StorageType::Local)) } // https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#dfn-GlobalCrypto @@ -684,8 +707,14 @@ impl WindowMethods for Window { // Step 6. let container_doc = document_from_node(container); - let current_doc = GlobalScope::current().expect("No current global object").as_window().Document(); - if !current_doc.origin().same_origin_domain(container_doc.origin()) { + let current_doc = GlobalScope::current() + .expect("No current global object") + .as_window() + .Document(); + if !current_doc + .origin() + .same_origin_domain(container_doc.origin()) + { return None; } // Step 7. @@ -699,51 +728,76 @@ impl WindowMethods for Window { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout - unsafe fn SetTimeout(&self, _cx: *mut JSContext, callback: Rc<Function>, timeout: i32, - args: Vec<HandleValue>) -> i32 { + unsafe fn SetTimeout( + &self, + _cx: *mut JSContext, + callback: Rc<Function>, + timeout: i32, + args: Vec<HandleValue>, + ) -> i32 { self.upcast::<GlobalScope>().set_timeout_or_interval( TimerCallback::FunctionTimerCallback(callback), args, timeout, - IsInterval::NonInterval) + IsInterval::NonInterval, + ) } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout - unsafe fn SetTimeout_(&self, _cx: *mut JSContext, callback: DOMString, - timeout: i32, args: Vec<HandleValue>) -> i32 { + unsafe fn SetTimeout_( + &self, + _cx: *mut JSContext, + callback: DOMString, + timeout: i32, + args: Vec<HandleValue>, + ) -> i32 { self.upcast::<GlobalScope>().set_timeout_or_interval( TimerCallback::StringTimerCallback(callback), args, timeout, - IsInterval::NonInterval) + IsInterval::NonInterval, + ) } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-cleartimeout fn ClearTimeout(&self, handle: i32) { - self.upcast::<GlobalScope>().clear_timeout_or_interval(handle); + self.upcast::<GlobalScope>() + .clear_timeout_or_interval(handle); } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - unsafe fn SetInterval(&self, _cx: *mut JSContext, callback: Rc<Function>, - timeout: i32, args: Vec<HandleValue>) -> i32 { + unsafe fn SetInterval( + &self, + _cx: *mut JSContext, + callback: Rc<Function>, + timeout: i32, + args: Vec<HandleValue>, + ) -> i32 { self.upcast::<GlobalScope>().set_timeout_or_interval( TimerCallback::FunctionTimerCallback(callback), args, timeout, - IsInterval::Interval) + IsInterval::Interval, + ) } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - unsafe fn SetInterval_(&self, _cx: *mut JSContext, callback: DOMString, - timeout: i32, args: Vec<HandleValue>) -> i32 { + unsafe fn SetInterval_( + &self, + _cx: *mut JSContext, + callback: DOMString, + timeout: i32, + args: Vec<HandleValue>, + ) -> i32 { self.upcast::<GlobalScope>().set_timeout_or_interval( TimerCallback::StringTimerCallback(callback), args, timeout, - IsInterval::Interval) + IsInterval::Interval, + ) } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-clearinterval @@ -799,8 +853,11 @@ impl WindowMethods for Window { fn Performance(&self) -> DomRoot<Performance> { self.performance.or_init(|| { let global_scope = self.upcast::<GlobalScope>(); - Performance::new(global_scope, self.navigation_start.get(), - self.navigation_start_precise.get()) + Performance::new( + global_scope, + self.navigation_start.get(), + self.navigation_start_precise.get(), + ) }) } @@ -839,11 +896,12 @@ impl WindowMethods for Window { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-window-postmessage - unsafe fn PostMessage(&self, - cx: *mut JSContext, - message: HandleValue, - origin: DOMString) - -> ErrorResult { + unsafe fn PostMessage( + &self, + cx: *mut JSContext, + message: HandleValue, + origin: DOMString, + ) -> ErrorResult { // Step 3-5. let origin = match &origin[..] { "*" => None, @@ -855,7 +913,7 @@ impl WindowMethods for Window { url => match ServoUrl::parse(&url) { Ok(url) => Some(url.origin().clone()), Err(_) => return Err(Error::Syntax), - } + }, }; // Step 1-2, 6-8. @@ -892,7 +950,9 @@ impl WindowMethods for Window { #[allow(unsafe_code)] fn Trap(&self) { #[cfg(feature = "unstable")] - unsafe { ::std::intrinsics::breakpoint() } + unsafe { + ::std::intrinsics::breakpoint() + } } #[allow(unsafe_code)] @@ -912,39 +972,50 @@ impl WindowMethods for Window { } // https://drafts.csswg.org/cssom/#dom-window-getcomputedstyle - fn GetComputedStyle(&self, - element: &Element, - pseudo: Option<DOMString>) -> DomRoot<CSSStyleDeclaration> { + fn GetComputedStyle( + &self, + element: &Element, + pseudo: Option<DOMString>, + ) -> DomRoot<CSSStyleDeclaration> { // Steps 1-4. - let pseudo = match pseudo.map(|mut s| { s.make_ascii_lowercase(); s }) { - Some(ref pseudo) if pseudo == ":before" || pseudo == "::before" => - Some(PseudoElement::Before), - Some(ref pseudo) if pseudo == ":after" || pseudo == "::after" => - Some(PseudoElement::After), - _ => None + let pseudo = match pseudo.map(|mut s| { + s.make_ascii_lowercase(); + s + }) { + Some(ref pseudo) if pseudo == ":before" || pseudo == "::before" => { + Some(PseudoElement::Before) + }, + Some(ref pseudo) if pseudo == ":after" || pseudo == "::after" => { + Some(PseudoElement::After) + }, + _ => None, }; // Step 5. - CSSStyleDeclaration::new(self, - CSSStyleOwner::Element(Dom::from_ref(element)), - pseudo, - CSSModificationAccess::Readonly) + CSSStyleDeclaration::new( + self, + CSSStyleOwner::Element(Dom::from_ref(element)), + pseudo, + CSSModificationAccess::Readonly, + ) } // https://drafts.csswg.org/cssom-view/#dom-window-innerheight //TODO Include Scrollbar fn InnerHeight(&self) -> i32 { - self.window_size.get() - .and_then(|e| e.initial_viewport.height.to_i32()) - .unwrap_or(0) + self.window_size + .get() + .and_then(|e| e.initial_viewport.height.to_i32()) + .unwrap_or(0) } // https://drafts.csswg.org/cssom-view/#dom-window-innerwidth //TODO Include Scrollbar fn InnerWidth(&self) -> i32 { - self.window_size.get() - .and_then(|e| e.initial_viewport.width.to_i32()) - .unwrap_or(0) + self.window_size + .get() + .and_then(|e| e.initial_viewport.width.to_i32()) + .unwrap_or(0) } // https://drafts.csswg.org/cssom-view/#dom-window-scrollx @@ -973,7 +1044,6 @@ impl WindowMethods for Window { let left = options.left.unwrap_or(0.0f64); let top = options.top.unwrap_or(0.0f64); self.scroll(left, top, options.parent.behavior); - } // https://drafts.csswg.org/cssom-view/#dom-window-scroll @@ -992,7 +1062,7 @@ impl WindowMethods for Window { } // https://drafts.csswg.org/cssom-view/#dom-window-scrollby - fn ScrollBy(&self, options: &ScrollToOptions) { + fn ScrollBy(&self, options: &ScrollToOptions) { // Step 1 let x = options.left.unwrap_or(0.0f64); let y = options.top.unwrap_or(0.0f64); @@ -1001,11 +1071,11 @@ impl WindowMethods for Window { } // https://drafts.csswg.org/cssom-view/#dom-window-scrollby - fn ScrollBy_(&self, x: f64, y: f64) { + fn ScrollBy_(&self, x: f64, y: f64) { // Step 3 let left = x + self.ScrollX() as f64; // Step 4 - let top = y + self.ScrollY() as f64; + let top = y + self.ScrollY() as f64; // Step 5 self.scroll(left, top, ScrollBehavior::Auto); @@ -1024,7 +1094,10 @@ impl WindowMethods for Window { fn ResizeBy(&self, x: i32, y: i32) { let (size, _) = self.client_window(); // Step 1 - self.ResizeTo(x + size.width.to_i32().unwrap_or(1), y + size.height.to_i32().unwrap_or(1)) + self.ResizeTo( + x + size.width.to_i32().unwrap_or(1), + y + size.height.to_i32().unwrap_or(1), + ) } // https://drafts.csswg.org/cssom-view/#dom-window-moveto @@ -1097,8 +1170,7 @@ impl WindowMethods for Window { self.css_error_reporter(), None, ); - let media_query_list = - media_queries::MediaList::parse(&context, &mut parser); + let media_query_list = media_queries::MediaList::parse(&context, &mut parser); let document = self.Document(); let mql = MediaQueryList::new(&document, media_query_list); self.media_query_lists.track(&*mql); @@ -1107,7 +1179,11 @@ impl WindowMethods for Window { #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#fetch-method - fn Fetch(&self, input: RequestOrUSVString, init: RootedTraceableBox<RequestInit>) -> Rc<Promise> { + fn Fetch( + &self, + input: RequestOrUSVString, + init: RootedTraceableBox<RequestInit>, + ) -> Rc<Promise> { fetch::Fetch(&self.upcast(), input, init) } @@ -1160,7 +1236,9 @@ impl Window { pub fn cancel_all_tasks(&self) { let mut ignore_flags = self.ignore_further_async_events.borrow_mut(); for task_source_name in TaskSourceName::all() { - let flag = ignore_flags.entry(task_source_name).or_insert(Default::default()); + let flag = ignore_flags + .entry(task_source_name) + .or_insert(Default::default()); let cancelled = mem::replace(&mut *flag, Default::default()); cancelled.store(true, Ordering::Relaxed); } @@ -1171,7 +1249,9 @@ impl Window { /// `true` and replaces it with a brand new one for future tasks. pub fn cancel_all_tasks_from_source(&self, task_source_name: TaskSourceName) { let mut ignore_flags = self.ignore_further_async_events.borrow_mut(); - let flag = ignore_flags.entry(task_source_name).or_insert(Default::default()); + let flag = ignore_flags + .entry(task_source_name) + .or_insert(Default::default()); let cancelled = mem::replace(&mut *flag, Default::default()); cancelled.store(true, Ordering::Relaxed); } @@ -1234,12 +1314,12 @@ impl Window { let content_size = e.upcast::<Node>().bounding_content_box_or_zero(); let content_height = content_size.size.height.to_f64_px(); let content_width = content_size.size.width.to_f64_px(); - (xfinite.min(content_width - width).max(0.0f64), - yfinite.min(content_height - height).max(0.0f64)) + ( + xfinite.min(content_width - width).max(0.0f64), + yfinite.min(content_height - height).max(0.0f64), + ) }, - None => { - (xfinite.max(0.0f64), yfinite.max(0.0f64)) - } + None => (xfinite.max(0.0f64), yfinite.max(0.0f64)), }; // Step 10 @@ -1255,27 +1335,32 @@ impl Window { let x = x.to_f32().unwrap_or(0.0f32); let y = y.to_f32().unwrap_or(0.0f32); self.update_viewport_for_scroll(x, y); - self.perform_a_scroll(x, - y, - global_scope.pipeline_id().root_scroll_id(), - behavior, - None); + self.perform_a_scroll( + x, + y, + global_scope.pipeline_id().root_scroll_id(), + behavior, + None, + ); } /// <https://drafts.csswg.org/cssom-view/#perform-a-scroll> - pub fn perform_a_scroll(&self, - x: f32, - y: f32, - scroll_id: ExternalScrollId, - _behavior: ScrollBehavior, - _element: Option<&Element>) { + pub fn perform_a_scroll( + &self, + x: f32, + y: f32, + scroll_id: ExternalScrollId, + _behavior: ScrollBehavior, + _element: Option<&Element>, + ) { // TODO Step 1 // TODO(mrobinson, #18709): Add smooth scrolling support to WebRender so that we can // properly process ScrollBehavior here. - self.layout_chan.send(Msg::UpdateScrollStateFromScript(ScrollState { - scroll_id, - scroll_offset: Vector2D::new(-x, -y), - })).unwrap(); + self.layout_chan + .send(Msg::UpdateScrollStateFromScript(ScrollState { + scroll_id, + scroll_offset: Vector2D::new(-x, -y), + })).unwrap(); } pub fn update_viewport_for_scroll(&self, x: f32, y: f32) { @@ -1285,7 +1370,9 @@ impl Window { } pub fn device_pixel_ratio(&self) -> TypedScale<f32, CSSPixel, DevicePixel> { - self.window_size.get().map_or(TypedScale::new(1.0), |data| data.device_pixel_ratio) + self.window_size + .get() + .map_or(TypedScale::new(1.0), |data| data.device_pixel_ratio) } fn client_window(&self) -> (TypedSize2D<u32, CSSPixel>, TypedPoint2D<i32, CSSPixel>) { @@ -1293,15 +1380,22 @@ impl Window { let (send, recv) = ProfiledIpc::channel::<(DeviceUintSize, DeviceIntPoint)>(timer_profile_chan).unwrap(); self.send_to_constellation(ScriptMsg::GetClientWindow(send)); - let (size, point) = recv.recv().unwrap_or((TypedSize2D::zero(), TypedPoint2D::zero())); + let (size, point) = recv + .recv() + .unwrap_or((TypedSize2D::zero(), TypedPoint2D::zero())); let dpr = self.device_pixel_ratio(); - ((size.to_f32() / dpr).to_u32(), (point.to_f32() / dpr).to_i32()) + ( + (size.to_f32() / dpr).to_u32(), + (point.to_f32() / dpr).to_i32(), + ) } /// Advances the layout animation clock by `delta` milliseconds, and then /// forces a reflow if `tick` is true. pub fn advance_animation_clock(&self, delta: i32, tick: bool) { - self.layout_chan.send(Msg::AdvanceClockMs(delta, tick)).unwrap(); + self.layout_chan + .send(Msg::AdvanceClockMs(delta, tick)) + .unwrap(); } /// Reflows the page unconditionally if possible and not suppressed. This @@ -1319,8 +1413,7 @@ impl Window { // Check if we need to unsuppress reflow. Note that this needs to be // *before* any early bailouts, or reflow might never be unsuppresed! match reason { - ReflowReason::FirstLoad | - ReflowReason::RefreshTick => self.suppress_reflow.set(false), + ReflowReason::FirstLoad | ReflowReason::RefreshTick => self.suppress_reflow.set(false), _ => (), } @@ -1332,8 +1425,11 @@ impl Window { let for_display = reflow_goal == ReflowGoal::Full; if for_display && self.suppress_reflow.get() { - debug!("Suppressing reflow pipeline {} for reason {:?} before FirstLoad or RefreshTick", - self.upcast::<GlobalScope>().pipeline_id(), reason); + debug!( + "Suppressing reflow pipeline {} for reason {:?} before FirstLoad or RefreshTick", + self.upcast::<GlobalScope>().pipeline_id(), + reason + ); return false; } @@ -1350,7 +1446,11 @@ impl Window { // On debug mode, print the reflow event information. if opts::get().relayout_event { - debug_reflow_events(self.upcast::<GlobalScope>().pipeline_id(), &reflow_goal, &reason); + debug_reflow_events( + self.upcast::<GlobalScope>().pipeline_id(), + &reflow_goal, + &reason, + ); } let document = self.Document(); @@ -1411,15 +1511,23 @@ impl Window { let mut images = self.pending_layout_images.borrow_mut(); let nodes = images.entry(id).or_insert(vec![]); - if nodes.iter().find(|n| &***n as *const _ == &*node as *const _).is_none() { + if nodes + .iter() + .find(|n| &***n as *const _ == &*node as *const _) + .is_none() + { let (responder, responder_listener) = ProfiledIpc::channel(self.global().time_profiler_chan().clone()).unwrap(); let pipeline = self.upcast::<GlobalScope>().pipeline_id(); let image_cache_chan = self.image_cache_chan.clone(); - ROUTER.add_route(responder_listener.to_opaque(), Box::new(move |message| { - let _ = image_cache_chan.send((pipeline, message.to().unwrap())); - })); - self.image_cache.add_listener(id, ImageResponder::new(responder, id)); + ROUTER.add_route( + responder_listener.to_opaque(), + Box::new(move |message| { + let _ = image_cache_chan.send((pipeline, message.to().unwrap())); + }), + ); + self.image_cache + .add_listener(id, ImageResponder::new(responder, id)); nodes.push(Dom::from_ref(&*node)); } } @@ -1454,12 +1562,17 @@ impl Window { // If window_size is `None`, we don't reflow, so the document stays // dirty. Otherwise, we shouldn't need a reflow immediately after a // reflow, except if we're waiting for a deferred paint. - assert!(!self.Document().needs_reflow() || + assert!( + !self.Document().needs_reflow() || (!for_display && self.Document().needs_paint()) || self.window_size.get().is_none() || - self.suppress_reflow.get()); + self.suppress_reflow.get() + ); } else { - debug!("Document doesn't need reflow - skipping it (reason {:?})", reason); + debug!( + "Document doesn't need reflow - skipping it (reason {:?})", + reason + ); } // If writing a screenshot, check if the script has reached a state @@ -1472,7 +1585,9 @@ impl Window { // perspective at least). if (opts::get().output_file.is_some() || opts::get().exit_after_load || - opts::get().webdriver_port.is_some()) && for_display { + opts::get().webdriver_port.is_some()) && + for_display + { let document = self.Document(); // Checks if the html element has reftest-wait attribute present. @@ -1495,7 +1610,10 @@ impl Window { } pub fn layout_reflow(&self, query_msg: QueryMsg) -> bool { - self.reflow(ReflowGoal::LayoutQuery(query_msg, time::precise_time_ns()), ReflowReason::Query) + self.reflow( + ReflowGoal::LayoutQuery(query_msg, time::precise_time_ns()), + ReflowReason::Query, + ) } pub fn layout(&self) -> &LayoutRPC { @@ -1533,22 +1651,18 @@ impl Window { } pub fn scroll_offset_query(&self, node: &Node) -> Vector2D<f32> { - if let Some(scroll_offset) = self.scroll_offsets - .borrow() - .get(&node.to_untrusted_node_address()) { - return *scroll_offset + if let Some(scroll_offset) = self + .scroll_offsets + .borrow() + .get(&node.to_untrusted_node_address()) + { + return *scroll_offset; } Vector2D::new(0.0, 0.0) } // https://drafts.csswg.org/cssom-view/#element-scrolling-members - pub fn scroll_node( - &self, - node: &Node, - x_: f64, - y_: f64, - behavior: ScrollBehavior - ) { + pub fn scroll_node(&self, node: &Node, x_: f64, y_: f64, behavior: ScrollBehavior) { if !self.layout_reflow(QueryMsg::NodeScrollIdQuery(node.to_trusted_node_address())) { return; } @@ -1556,23 +1670,29 @@ impl Window { // The scroll offsets are immediatly updated since later calls // to topScroll and others may access the properties before // webrender has a chance to update the offsets. - self.scroll_offsets.borrow_mut().insert(node.to_untrusted_node_address(), - Vector2D::new(x_ as f32, y_ as f32)); + self.scroll_offsets.borrow_mut().insert( + node.to_untrusted_node_address(), + Vector2D::new(x_ as f32, y_ as f32), + ); let NodeScrollIdResponse(scroll_id) = self.layout_rpc.node_scroll_id(); // Step 12 - self.perform_a_scroll(x_.to_f32().unwrap_or(0.0f32), - y_.to_f32().unwrap_or(0.0f32), - scroll_id, - behavior, - None); + self.perform_a_scroll( + x_.to_f32().unwrap_or(0.0f32), + y_.to_f32().unwrap_or(0.0f32), + scroll_id, + behavior, + None, + ); } - pub fn resolved_style_query(&self, - element: TrustedNodeAddress, - pseudo: Option<PseudoElement>, - property: PropertyId) -> DOMString { + pub fn resolved_style_query( + &self, + element: TrustedNodeAddress, + pseudo: Option<PseudoElement>, + property: PropertyId, + ) -> DOMString { if !self.layout_reflow(QueryMsg::ResolvedStyleQuery(element, pseudo, property)) { return DOMString::new(); } @@ -1581,7 +1701,10 @@ impl Window { } #[allow(unsafe_code)] - pub fn offset_parent_query(&self, node: TrustedNodeAddress) -> (Option<DomRoot<Element>>, Rect<Au>) { + pub fn offset_parent_query( + &self, + node: TrustedNodeAddress, + ) -> (Option<DomRoot<Element>>, Rect<Au>) { if !self.layout_reflow(QueryMsg::OffsetParentQuery(node)) { return (None, Rect::zero()); } @@ -1598,7 +1721,7 @@ impl Window { pub fn style_query(&self, node: TrustedNodeAddress) -> Option<servo_arc::Arc<ComputedValues>> { if !self.layout_reflow(QueryMsg::StyleQuery(node)) { - return None + return None; } self.layout_rpc.style().0 } @@ -1606,7 +1729,7 @@ impl Window { pub fn text_index_query( &self, node: TrustedNodeAddress, - point_in_node: Point2D<f32> + point_in_node: Point2D<f32>, ) -> TextIndexResponse { if !self.layout_reflow(QueryMsg::TextIndexQuery(node, point_in_node)) { return TextIndexResponse(None); @@ -1636,8 +1759,13 @@ impl Window { let _ = fs::remove_dir_all(&path); match fs::create_dir_all(&path) { Ok(_) => { - *self.unminified_js_dir.borrow_mut() = Some(path.into_os_string().into_string().unwrap()); - debug!("Created folder for {:?} unminified scripts {:?}", host, self.unminified_js_dir.borrow()); + *self.unminified_js_dir.borrow_mut() = + Some(path.into_os_string().into_string().unwrap()); + debug!( + "Created folder for {:?} unminified scripts {:?}", + host, + self.unminified_js_dir.borrow() + ); }, Err(_) => warn!("Could not create unminified dir for {:?}", host), } @@ -1645,21 +1773,27 @@ impl Window { } /// Commence a new URL load which will either replace this window or scroll to a fragment. - pub fn load_url(&self, url: ServoUrl, replace: bool, force_reload: bool, - referrer_policy: Option<ReferrerPolicy>) { + pub fn load_url( + &self, + url: ServoUrl, + replace: bool, + force_reload: bool, + referrer_policy: Option<ReferrerPolicy>, + ) { let doc = self.Document(); let referrer_policy = referrer_policy.or(doc.get_referrer_policy()); // https://html.spec.whatwg.org/multipage/#navigating-across-documents - if !force_reload && url.as_url()[..Position::AfterQuery] == - doc.url().as_url()[..Position::AfterQuery] { - // Step 6 - if let Some(fragment) = url.fragment() { - self.send_to_constellation(ScriptMsg::NavigatedToFragment(url.clone(), replace)); - doc.check_and_scroll_fragment(fragment); - let this = Trusted::new(self); - let old_url = doc.url().into_string(); - let new_url = url.clone().into_string(); - let task = task!(hashchange_event: move || { + if !force_reload && + url.as_url()[..Position::AfterQuery] == doc.url().as_url()[..Position::AfterQuery] + { + // Step 6 + if let Some(fragment) = url.fragment() { + self.send_to_constellation(ScriptMsg::NavigatedToFragment(url.clone(), replace)); + doc.check_and_scroll_fragment(fragment); + let this = Trusted::new(self); + let old_url = doc.url().into_string(); + let new_url = url.clone().into_string(); + let task = task!(hashchange_event: move || { let this = this.root(); let event = HashChangeEvent::new( &this, @@ -1670,16 +1804,19 @@ impl Window { new_url); event.upcast::<Event>().fire(this.upcast::<EventTarget>()); }); - // FIXME(nox): Why are errors silenced here? - let _ = self.script_chan.send(CommonScriptMsg::Task( - ScriptThreadEventCategory::DomEvent, - Box::new(self.task_canceller(TaskSourceName::DOMManipulation).wrap_task(task)), - self.pipeline_id(), - TaskSourceName::DOMManipulation, - )); - doc.set_url(url.clone()); - return - } + // FIXME(nox): Why are errors silenced here? + let _ = self.script_chan.send(CommonScriptMsg::Task( + ScriptThreadEventCategory::DomEvent, + Box::new( + self.task_canceller(TaskSourceName::DOMManipulation) + .wrap_task(task), + ), + self.pipeline_id(), + TaskSourceName::DOMManipulation, + )); + doc.set_url(url.clone()); + return; + } } let pipeline_id = self.upcast::<GlobalScope>().pipeline_id(); @@ -1696,11 +1833,13 @@ impl Window { // Step 7 if doc.prompt_to_unload(false) { - self.main_thread_script_chan().send( - MainThreadScriptMsg::Navigate(pipeline_id, - LoadData::new(url, Some(pipeline_id), referrer_policy, Some(doc.url())), replace)).unwrap(); + self.main_thread_script_chan() + .send(MainThreadScriptMsg::Navigate( + pipeline_id, + LoadData::new(url, Some(pipeline_id), referrer_policy, Some(doc.url())), + replace, + )).unwrap(); }; - } pub fn handle_fire_timer(&self, timer_id: TimerEventId) { @@ -1733,7 +1872,8 @@ impl Window { } pub fn add_pending_reflow(&self) { - self.pending_reflow_count.set(self.pending_reflow_count.get() + 1); + self.pending_reflow_count + .set(self.pending_reflow_count.get() + 1); } pub fn set_resize_event(&self, event: WindowSizeData, event_type: WindowSizeType) { @@ -1753,9 +1893,10 @@ impl Window { // so that we don't collect display list items for areas too far outside the viewport, // but also don't trigger reflows every time the viewport changes. static VIEWPORT_EXPANSION: f32 = 2.0; // 2 lengths on each side plus original length is 5 total. - let proposed_clip_rect = f32_rect_to_au_rect( - viewport.inflate(viewport.size.width * VIEWPORT_EXPANSION, - viewport.size.height * VIEWPORT_EXPANSION)); + let proposed_clip_rect = f32_rect_to_au_rect(viewport.inflate( + viewport.size.width * VIEWPORT_EXPANSION, + viewport.size.height * VIEWPORT_EXPANSION, + )); let clip_rect = self.page_clip_rect.get(); if proposed_clip_rect == clip_rect { return false; @@ -1812,11 +1953,15 @@ impl Window { sender.send(Some(marker)).unwrap(); } - pub fn set_devtools_timeline_markers(&self, - markers: Vec<TimelineMarkerType>, - reply: IpcSender<Option<TimelineMarker>>) { + pub fn set_devtools_timeline_markers( + &self, + markers: Vec<TimelineMarkerType>, + reply: IpcSender<Option<TimelineMarker>>, + ) { *self.devtools_marker_sender.borrow_mut() = Some(reply); - self.devtools_markers.borrow_mut().extend(markers.into_iter()); + self.devtools_markers + .borrow_mut() + .extend(markers.into_iter()); } pub fn drop_devtools_timeline_markers(&self, markers: Vec<TimelineMarkerType>) { @@ -1854,11 +1999,14 @@ impl Window { }); // Sending change events for all changed Media Queries for mql in mql_list.iter() { - let event = MediaQueryListEvent::new(&mql.global(), - atom!("change"), - false, false, - mql.Media(), - mql.Matches()); + let event = MediaQueryListEvent::new( + &mql.global(), + atom!("change"), + false, + false, + mql.Media(), + mql.Matches(), + ); event.upcast::<Event>().fire(mql.upcast::<EventTarget>()); } self.Document().react_to_environment_changes(); @@ -2015,9 +2163,7 @@ impl Window { exists_mut_observer: Cell::new(false), }); - unsafe { - WindowBinding::Wrap(runtime.cx(), win) - } + unsafe { WindowBinding::Wrap(runtime.cx(), win) } } pub fn pipeline_id(&self) -> Option<PipelineId> { @@ -2026,10 +2172,16 @@ impl Window { } fn should_move_clip_rect(clip_rect: Rect<Au>, new_viewport: Rect<f32>) -> bool { - let clip_rect = Rect::new(Point2D::new(clip_rect.origin.x.to_f32_px(), - clip_rect.origin.y.to_f32_px()), - Size2D::new(clip_rect.size.width.to_f32_px(), - clip_rect.size.height.to_f32_px())); + let clip_rect = Rect::new( + Point2D::new( + clip_rect.origin.x.to_f32_px(), + clip_rect.origin.y.to_f32_px(), + ), + Size2D::new( + clip_rect.size.width.to_f32_px(), + clip_rect.size.height.to_f32_px(), + ), + ); // We only need to move the clip rect if the viewport is getting near the edge of // our preexisting clip rect. We use half of the size of the viewport as a heuristic @@ -2038,9 +2190,9 @@ fn should_move_clip_rect(clip_rect: Rect<Au>, new_viewport: Rect<f32>) -> bool { let viewport_scroll_margin = new_viewport.size * VIEWPORT_SCROLL_MARGIN_SIZE; (clip_rect.origin.x - new_viewport.origin.x).abs() <= viewport_scroll_margin.width || - (clip_rect.max_x() - new_viewport.max_x()).abs() <= viewport_scroll_margin.width || - (clip_rect.origin.y - new_viewport.origin.y).abs() <= viewport_scroll_margin.height || - (clip_rect.max_y() - new_viewport.max_y()).abs() <= viewport_scroll_margin.height + (clip_rect.max_x() - new_viewport.max_x()).abs() <= viewport_scroll_margin.width || + (clip_rect.origin.y - new_viewport.origin.y).abs() <= viewport_scroll_margin.height || + (clip_rect.max_y() - new_viewport.max_y()).abs() <= viewport_scroll_margin.height } fn debug_reflow_events(id: PipelineId, reflow_goal: &ReflowGoal, reason: &ReflowReason) { @@ -2134,7 +2286,10 @@ impl Window { // TODO: When switching to the right task source, update the task_canceller call too. let _ = self.script_chan.send(CommonScriptMsg::Task( ScriptThreadEventCategory::DomEvent, - Box::new(self.task_canceller(TaskSourceName::DOMManipulation).wrap_task(task)), + Box::new( + self.task_canceller(TaskSourceName::DOMManipulation) + .wrap_task(task), + ), self.pipeline_id(), TaskSourceName::DOMManipulation, )); diff --git a/components/script/dom/windowproxy.rs b/components/script/dom/windowproxy.rs index f7d677b37fc..d1b5c185565 100644 --- a/components/script/dom/windowproxy.rs +++ b/components/script/dom/windowproxy.rs @@ -97,15 +97,17 @@ pub struct WindowProxy { } impl WindowProxy { - pub fn new_inherited(browsing_context_id: BrowsingContextId, - top_level_browsing_context_id: TopLevelBrowsingContextId, - currently_active: Option<PipelineId>, - frame_element: Option<&Element>, - parent: Option<&WindowProxy>, - opener: Option<BrowsingContextId>) - -> WindowProxy - { - let name = frame_element.map_or(DOMString::new(), |e| e.get_string_attribute(&local_name!("name"))); + pub fn new_inherited( + browsing_context_id: BrowsingContextId, + top_level_browsing_context_id: TopLevelBrowsingContextId, + currently_active: Option<PipelineId>, + frame_element: Option<&Element>, + parent: Option<&WindowProxy>, + opener: Option<BrowsingContextId>, + ) -> WindowProxy { + let name = frame_element.map_or(DOMString::new(), |e| { + e.get_string_attribute(&local_name!("name")) + }); WindowProxy { reflector: Reflector::new(), browsing_context_id: browsing_context_id, @@ -121,14 +123,14 @@ impl WindowProxy { } #[allow(unsafe_code)] - pub fn new(window: &Window, - browsing_context_id: BrowsingContextId, - top_level_browsing_context_id: TopLevelBrowsingContextId, - frame_element: Option<&Element>, - parent: Option<&WindowProxy>, - opener: Option<BrowsingContextId>) - -> DomRoot<WindowProxy> - { + pub fn new( + window: &Window, + browsing_context_id: BrowsingContextId, + top_level_browsing_context_id: TopLevelBrowsingContextId, + frame_element: Option<&Element>, + parent: Option<&WindowProxy>, + opener: Option<BrowsingContextId>, + ) -> DomRoot<WindowProxy> { unsafe { let WindowProxyHandler(handler) = window.windowproxy_handler(); assert!(!handler.is_null()); @@ -136,7 +138,10 @@ impl WindowProxy { let cx = window.get_cx(); let window_jsobject = window.reflector().get_jsobject(); assert!(!window_jsobject.get().is_null()); - assert_ne!(((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL), 0); + assert_ne!( + ((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL), + 0 + ); let _ac = JSAutoCompartment::new(cx, window_jsobject.get()); // Create a new window proxy. @@ -156,26 +161,34 @@ impl WindowProxy { // The window proxy owns the browsing context. // When we finalize the window proxy, it drops the browsing context it owns. - SetProxyReservedSlot(js_proxy.get(), 0, &PrivateValue((&*window_proxy).as_void_ptr())); + SetProxyReservedSlot( + js_proxy.get(), + 0, + &PrivateValue((&*window_proxy).as_void_ptr()), + ); // Notify the JS engine about the new window proxy binding. SetWindowProxy(cx, window_jsobject, js_proxy.handle()); // Set the reflector. - debug!("Initializing reflector of {:p} to {:p}.", window_proxy, js_proxy.get()); + debug!( + "Initializing reflector of {:p} to {:p}.", + window_proxy, + js_proxy.get() + ); window_proxy.reflector.set_jsobject(js_proxy.get()); DomRoot::from_ref(&*Box::into_raw(window_proxy)) } } #[allow(unsafe_code)] - pub fn new_dissimilar_origin(global_to_clone_from: &GlobalScope, - browsing_context_id: BrowsingContextId, - top_level_browsing_context_id: TopLevelBrowsingContextId, - parent: Option<&WindowProxy>, - opener: Option<BrowsingContextId>) - -> DomRoot<WindowProxy> - { + pub fn new_dissimilar_origin( + global_to_clone_from: &GlobalScope, + browsing_context_id: BrowsingContextId, + top_level_browsing_context_id: TopLevelBrowsingContextId, + parent: Option<&WindowProxy>, + opener: Option<BrowsingContextId>, + ) -> DomRoot<WindowProxy> { unsafe { let handler = CreateWrapperProxyHandler(&XORIGIN_PROXY_HANDLER); assert!(!handler.is_null()); @@ -189,14 +202,17 @@ impl WindowProxy { None, None, parent, - opener + opener, )); // Create a new dissimilar-origin window. let window = DissimilarOriginWindow::new(global_to_clone_from, &*window_proxy); let window_jsobject = window.reflector().get_jsobject(); assert!(!window_jsobject.get().is_null()); - assert_ne!(((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL), 0); + assert_ne!( + ((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL), + 0 + ); let _ac = JSAutoCompartment::new(cx, window_jsobject.get()); // Create a new window proxy. @@ -205,30 +221,45 @@ impl WindowProxy { // The window proxy owns the browsing context. // When we finalize the window proxy, it drops the browsing context it owns. - SetProxyReservedSlot(js_proxy.get(), 0, &PrivateValue((&*window_proxy).as_void_ptr())); + SetProxyReservedSlot( + js_proxy.get(), + 0, + &PrivateValue((&*window_proxy).as_void_ptr()), + ); // Notify the JS engine about the new window proxy binding. SetWindowProxy(cx, window_jsobject, js_proxy.handle()); // Set the reflector. - debug!("Initializing reflector of {:p} to {:p}.", window_proxy, js_proxy.get()); + debug!( + "Initializing reflector of {:p} to {:p}.", + window_proxy, + js_proxy.get() + ); window_proxy.reflector.set_jsobject(js_proxy.get()); DomRoot::from_ref(&*Box::into_raw(window_proxy)) } } // https://html.spec.whatwg.org/multipage/#auxiliary-browsing-context - fn create_auxiliary_browsing_context(&self, name: DOMString, noopener: bool) -> Option<DomRoot<WindowProxy>> { + fn create_auxiliary_browsing_context( + &self, + name: DOMString, + noopener: bool, + ) -> Option<DomRoot<WindowProxy>> { let (chan, port) = ipc::channel().unwrap(); - let window = self.currently_active.get() - .and_then(|id| ScriptThread::find_document(id)) - .and_then(|doc| Some(DomRoot::from_ref(doc.window()))) - .unwrap(); + let window = self + .currently_active + .get() + .and_then(|id| ScriptThread::find_document(id)) + .and_then(|doc| Some(DomRoot::from_ref(doc.window()))) + .unwrap(); let msg = EmbedderMsg::AllowOpeningBrowser(chan); window.send_to_embedder(msg); if port.recv().unwrap() { let new_top_level_browsing_context_id = TopLevelBrowsingContextId::new(); - let new_browsing_context_id = BrowsingContextId::from(new_top_level_browsing_context_id); + let new_browsing_context_id = + BrowsingContextId::from(new_top_level_browsing_context_id); let new_pipeline_id = PipelineId::new(); let load_info = AuxiliaryBrowsingContextLoadInfo { opener_pipeline_id: self.currently_active.get().unwrap(), @@ -236,14 +267,18 @@ impl WindowProxy { new_top_level_browsing_context_id: new_top_level_browsing_context_id, new_pipeline_id: new_pipeline_id, }; - let document = self.currently_active.get() + let document = self + .currently_active + .get() .and_then(|id| ScriptThread::find_document(id)) .unwrap(); let blank_url = ServoUrl::parse("about:blank").ok().unwrap(); - let load_data = LoadData::new(blank_url, - None, - document.get_referrer_policy(), - Some(document.url().clone())); + let load_data = LoadData::new( + blank_url, + None, + document.get_referrer_policy(), + Some(document.url().clone()), + ); let (pipeline_sender, pipeline_receiver) = ipc::channel().unwrap(); let new_layout_info = NewLayoutInfo { parent_info: None, @@ -264,7 +299,8 @@ impl WindowProxy { window.send_to_embedder(msg); // TODO: if noopener is false, copy the sessionStorage storage area of the creator origin. // See step 14 of https://html.spec.whatwg.org/multipage/#creating-a-new-browsing-context - let auxiliary = ScriptThread::find_document(new_pipeline_id).and_then(|doc| doc.browsing_context()); + let auxiliary = + ScriptThread::find_document(new_pipeline_id).and_then(|doc| doc.browsing_context()); if let Some(proxy) = auxiliary { if name.to_lowercase() != "_blank" { proxy.set_name(name); @@ -272,7 +308,7 @@ impl WindowProxy { if noopener { proxy.disown(); } - return Some(proxy) + return Some(proxy); } } None @@ -287,17 +323,20 @@ impl WindowProxy { // https://html.spec.whatwg.org/multipage/#dom-opener pub unsafe fn opener(&self, cx: *mut JSContext) -> JSVal { if self.disowned.get() { - return NullValue() + return NullValue(); } let opener_id = match self.opener { Some(opener_browsing_context_id) => opener_browsing_context_id, - None => return NullValue() + None => return NullValue(), }; let opener_proxy = match ScriptThread::find_window_proxy(opener_id) { Some(window_proxy) => window_proxy, None => { let sender_pipeline_id = self.currently_active().unwrap(); - match ScriptThread::get_top_level_for_browsing_context(sender_pipeline_id, opener_id) { + match ScriptThread::get_top_level_for_browsing_context( + sender_pipeline_id, + opener_id, + ) { Some(opener_top_id) => { let global_to_clone_from = GlobalScope::from_context(cx); WindowProxy::new_dissimilar_origin( @@ -305,31 +344,32 @@ impl WindowProxy { opener_id, opener_top_id, None, - None + None, ) }, - None => return NullValue() + None => return NullValue(), } - } + }, }; if opener_proxy.is_browsing_context_discarded() { - return NullValue() + return NullValue(); } rooted!(in(cx) let mut val = UndefinedValue()); opener_proxy.to_jsval(cx, val.handle_mut()); - return val.get() + return val.get(); } // https://html.spec.whatwg.org/multipage/#window-open-steps - pub fn open(&self, - url: DOMString, - target: DOMString, - features: DOMString) - -> Option<DomRoot<WindowProxy>> { + pub fn open( + &self, + url: DOMString, + target: DOMString, + features: DOMString, + ) -> Option<DomRoot<WindowProxy>> { // Step 3. let non_empty_target = match target.as_ref() { "" => DOMString::from("_blank"), - _ => target + _ => target, }; // TODO Step 4, properly tokenize features. // Step 5 @@ -337,19 +377,22 @@ impl WindowProxy { // Step 6, 7 let (chosen, new) = match self.choose_browsing_context(non_empty_target, noopener) { (Some(chosen), new) => (chosen, new), - (None, _) => return None + (None, _) => return None, }; // TODO Step 8, set up browsing context features. let target_document = match chosen.document() { Some(target_document) => target_document, - None => return None + None => return None, }; let target_window = target_document.window(); // Step 9, and 10.2, will have happened elsewhere, // since we've created a new browsing context and loaded it with about:blank. if !url.is_empty() { - let existing_document = self.currently_active.get() - .and_then(|id| ScriptThread::find_document(id)).unwrap(); + let existing_document = self + .currently_active + .get() + .and_then(|id| ScriptThread::find_document(id)) + .unwrap(); // Step 10.1 let url = match existing_document.url().join(&url) { Ok(url) => url, @@ -360,14 +403,18 @@ impl WindowProxy { } if noopener { // Step 11 (Dis-owning has been done in create_auxiliary_browsing_context). - return None + return None; } // Step 12. - return target_document.browsing_context() + return target_document.browsing_context(); } // https://html.spec.whatwg.org/multipage/#the-rules-for-choosing-a-browsing-context-given-a-browsing-context-name - pub fn choose_browsing_context(&self, name: DOMString, noopener: bool) -> (Option<DomRoot<WindowProxy>>, bool) { + pub fn choose_browsing_context( + &self, + name: DOMString, + noopener: bool, + ) -> (Option<DomRoot<WindowProxy>>, bool) { match name.to_lowercase().as_ref() { "" | "_self" => { // Step 3. @@ -376,18 +423,15 @@ impl WindowProxy { "_parent" => { // Step 4 if let Some(parent) = self.parent() { - return (Some(DomRoot::from_ref(parent)), false) + return (Some(DomRoot::from_ref(parent)), false); } (None, false) - }, "_top" => { // Step 5 (Some(DomRoot::from_ref(self.top())), false) }, - "_blank" => { - (self.create_auxiliary_browsing_context(name, noopener), true) - }, + "_blank" => (self.create_auxiliary_browsing_context(name, noopener), true), _ => { // Step 6. // TODO: expand the search to all 'familiar' bc, @@ -395,9 +439,9 @@ impl WindowProxy { // See https://html.spec.whatwg.org/multipage/#familiar-with match ScriptThread::find_window_proxy_by_name(&name) { Some(proxy) => (Some(proxy), false), - None => (self.create_auxiliary_browsing_context(name, noopener), true) + None => (self.create_auxiliary_browsing_context(name, noopener), true), } - } + }, } } @@ -426,7 +470,8 @@ impl WindowProxy { } pub fn document(&self) -> Option<DomRoot<Document>> { - self.currently_active.get() + self.currently_active + .get() .and_then(|id| ScriptThread::find_document(id)) } @@ -456,7 +501,10 @@ impl WindowProxy { let window_jsobject = window.reflector().get_jsobject(); let old_js_proxy = self.reflector.get_jsobject(); assert!(!window_jsobject.get().is_null()); - assert_ne!(((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL), 0); + assert_ne!( + ((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL), + 0 + ); let _ac = JSAutoCompartment::new(cx, window_jsobject.get()); // The old window proxy no longer owns this browsing context. @@ -470,7 +518,11 @@ impl WindowProxy { // making the old window proxy a cross-compartment wrapper // pointing to the new window proxy. rooted!(in(cx) let new_js_proxy = NewWindowProxy(cx, window_jsobject, handler)); - debug!("Transplanting proxy from {:p} to {:p}.", old_js_proxy.get(), new_js_proxy.get()); + debug!( + "Transplanting proxy from {:p} to {:p}.", + old_js_proxy.get(), + new_js_proxy.get() + ); rooted!(in(cx) let new_js_proxy = JS_TransplantObject(cx, old_js_proxy, new_js_proxy.handle())); debug!("Transplanted proxy is {:p}.", new_js_proxy.get()); @@ -481,7 +533,11 @@ impl WindowProxy { SetWindowProxy(cx, window_jsobject, new_js_proxy.handle()); // Update the reflector. - debug!("Setting reflector of {:p} to {:p}.", self, new_js_proxy.get()); + debug!( + "Setting reflector of {:p} to {:p}.", + self, + new_js_proxy.get() + ); self.reflector.rootable().set(new_js_proxy.get()); } } @@ -519,7 +575,7 @@ impl WindowProxy { unsafe fn GetSubframeWindowProxy( cx: *mut JSContext, proxy: RawHandleObject, - id: RawHandleId + id: RawHandleId, ) -> Option<(DomRoot<WindowProxy>, u32)> { let index = get_array_index_from_id(cx, Handle::from_raw(id)); if let Some(index) = index { @@ -530,14 +586,17 @@ unsafe fn GetSubframeWindowProxy( let browsing_context_id = win.window_proxy().browsing_context_id(); let (result_sender, result_receiver) = ipc::channel().unwrap(); - let _ = win.upcast::<GlobalScope>().script_to_constellation_chan().send( - ScriptMsg::GetChildBrowsingContextId( + let _ = win + .upcast::<GlobalScope>() + .script_to_constellation_chan() + .send(ScriptMsg::GetChildBrowsingContextId( browsing_context_id, index as usize, - result_sender - ) - ); - return result_receiver.recv().ok() + result_sender, + )); + return result_receiver + .recv() + .ok() .and_then(|maybe_bcid| maybe_bcid) .and_then(ScriptThread::find_window_proxy) .map(|proxy| (proxy, (JSPROP_ENUMERATE | JSPROP_READONLY) as u32)); @@ -545,12 +604,16 @@ unsafe fn GetSubframeWindowProxy( let browsing_context_id = win.window_proxy().browsing_context_id(); let (result_sender, result_receiver) = ipc::channel().unwrap(); - let _ = win.global().script_to_constellation_chan().send(ScriptMsg::GetChildBrowsingContextId( - browsing_context_id, - index as usize, - result_sender - )); - return result_receiver.recv().ok() + let _ = win.global().script_to_constellation_chan().send( + ScriptMsg::GetChildBrowsingContextId( + browsing_context_id, + index as usize, + result_sender, + ), + ); + return result_receiver + .recv() + .ok() .and_then(|maybe_bcid| maybe_bcid) .and_then(ScriptThread::find_window_proxy) .map(|proxy| (proxy, JSPROP_READONLY as u32)); @@ -561,11 +624,12 @@ unsafe fn GetSubframeWindowProxy( } #[allow(unsafe_code)] -unsafe extern "C" fn getOwnPropertyDescriptor(cx: *mut JSContext, - proxy: RawHandleObject, - id: RawHandleId, - mut desc: RawMutableHandle<PropertyDescriptor>) - -> bool { +unsafe extern "C" fn getOwnPropertyDescriptor( + cx: *mut JSContext, + proxy: RawHandleObject, + id: RawHandleId, + mut desc: RawMutableHandle<PropertyDescriptor>, +) -> bool { let window = GetSubframeWindowProxy(cx, proxy, id); if let Some((window, attrs)) = window { rooted!(in(cx) let mut val = UndefinedValue()); @@ -592,12 +656,13 @@ unsafe extern "C" fn getOwnPropertyDescriptor(cx: *mut JSContext, } #[allow(unsafe_code)] -unsafe extern "C" fn defineProperty(cx: *mut JSContext, - proxy: RawHandleObject, - id: RawHandleId, - desc: RawHandle<PropertyDescriptor>, - res: *mut ObjectOpResult) - -> bool { +unsafe extern "C" fn defineProperty( + cx: *mut JSContext, + proxy: RawHandleObject, + id: RawHandleId, + desc: RawHandle<PropertyDescriptor>, + res: *mut ObjectOpResult, +) -> bool { if get_array_index_from_id(cx, Handle::from_raw(id)).is_some() { // Spec says to Reject whether this is a supported index or not, // since we have no indexed setter or indexed creator. That means @@ -614,11 +679,12 @@ unsafe extern "C" fn defineProperty(cx: *mut JSContext, } #[allow(unsafe_code)] -unsafe extern "C" fn has(cx: *mut JSContext, - proxy: RawHandleObject, - id: RawHandleId, - bp: *mut bool) - -> bool { +unsafe extern "C" fn has( + cx: *mut JSContext, + proxy: RawHandleObject, + id: RawHandleId, + bp: *mut bool, +) -> bool { let window = GetSubframeWindowProxy(cx, proxy, id); if window.is_some() { *bp = true; @@ -638,12 +704,13 @@ unsafe extern "C" fn has(cx: *mut JSContext, } #[allow(unsafe_code)] -unsafe extern "C" fn get(cx: *mut JSContext, - proxy: RawHandleObject, - receiver: RawHandleValue, - id: RawHandleId, - vp: RawMutableHandleValue) - -> bool { +unsafe extern "C" fn get( + cx: *mut JSContext, + proxy: RawHandleObject, + receiver: RawHandleValue, + id: RawHandleId, + vp: RawMutableHandleValue, +) -> bool { let window = GetSubframeWindowProxy(cx, proxy, id); if let Some((window, _attrs)) = window { window.to_jsval(cx, MutableHandle::from_raw(vp)); @@ -657,13 +724,14 @@ unsafe extern "C" fn get(cx: *mut JSContext, } #[allow(unsafe_code)] -unsafe extern "C" fn set(cx: *mut JSContext, - proxy: RawHandleObject, - id: RawHandleId, - v: RawHandleValue, - receiver: RawHandleValue, - res: *mut ObjectOpResult) - -> bool { +unsafe extern "C" fn set( + cx: *mut JSContext, + proxy: RawHandleObject, + id: RawHandleId, + v: RawHandleValue, + receiver: RawHandleValue, + res: *mut ObjectOpResult, +) -> bool { if get_array_index_from_id(cx, Handle::from_raw(id)).is_some() { // Reject (which means throw if and only if strict) the set. (*res).code_ = JSErrNum::JSMSG_READ_ONLY as ::libc::uintptr_t; @@ -673,20 +741,16 @@ unsafe extern "C" fn set(cx: *mut JSContext, let mut slot = UndefinedValue(); GetProxyPrivate(*proxy.ptr, &mut slot); rooted!(in(cx) let target = slot.to_object()); - JS_ForwardSetPropertyTo(cx, - target.handle().into(), - id, - v, - receiver, - res) + JS_ForwardSetPropertyTo(cx, target.handle().into(), id, v, receiver, res) } #[allow(unsafe_code)] -unsafe extern "C" fn get_prototype_if_ordinary(_: *mut JSContext, - _: RawHandleObject, - is_ordinary: *mut bool, - _: RawMutableHandleObject) - -> bool { +unsafe extern "C" fn get_prototype_if_ordinary( + _: *mut JSContext, + _: RawHandleObject, + is_ordinary: *mut bool, + _: RawMutableHandleObject, +) -> bool { // Window's [[GetPrototypeOf]] trap isn't the ordinary definition: // // https://html.spec.whatwg.org/multipage/#windowproxy-getprototypeof @@ -737,9 +801,7 @@ static PROXY_HANDLER: ProxyTraps = ProxyTraps { #[allow(unsafe_code)] pub fn new_window_proxy_handler() -> WindowProxyHandler { - unsafe { - WindowProxyHandler(CreateWrapperProxyHandler(&PROXY_HANDLER)) - } + unsafe { WindowProxyHandler(CreateWrapperProxyHandler(&PROXY_HANDLER)) } } // The proxy traps for cross-origin windows. @@ -756,12 +818,12 @@ unsafe fn throw_security_error(cx: *mut JSContext) -> bool { } #[allow(unsafe_code)] -unsafe extern "C" fn has_xorigin(cx: *mut JSContext, - proxy: RawHandleObject, - id: RawHandleId, - bp: *mut bool) - -> bool -{ +unsafe extern "C" fn has_xorigin( + cx: *mut JSContext, + proxy: RawHandleObject, + id: RawHandleId, + bp: *mut bool, +) -> bool { let mut slot = UndefinedValue(); GetProxyPrivate(*proxy.ptr, &mut slot); rooted!(in(cx) let target = slot.to_object()); @@ -776,69 +838,69 @@ unsafe extern "C" fn has_xorigin(cx: *mut JSContext, } #[allow(unsafe_code)] -unsafe extern "C" fn get_xorigin(cx: *mut JSContext, - proxy: RawHandleObject, - receiver: RawHandleValue, - id: RawHandleId, - vp: RawMutableHandleValue) - -> bool -{ +unsafe extern "C" fn get_xorigin( + cx: *mut JSContext, + proxy: RawHandleObject, + receiver: RawHandleValue, + id: RawHandleId, + vp: RawMutableHandleValue, +) -> bool { let mut found = false; has_xorigin(cx, proxy, id, &mut found); found && get(cx, proxy, receiver, id, vp) } #[allow(unsafe_code)] -unsafe extern "C" fn set_xorigin(cx: *mut JSContext, - _: RawHandleObject, - _: RawHandleId, - _: RawHandleValue, - _: RawHandleValue, - _: *mut ObjectOpResult) - -> bool -{ +unsafe extern "C" fn set_xorigin( + cx: *mut JSContext, + _: RawHandleObject, + _: RawHandleId, + _: RawHandleValue, + _: RawHandleValue, + _: *mut ObjectOpResult, +) -> bool { throw_security_error(cx) } #[allow(unsafe_code)] -unsafe extern "C" fn delete_xorigin(cx: *mut JSContext, - _: RawHandleObject, - _: RawHandleId, - _: *mut ObjectOpResult) - -> bool -{ +unsafe extern "C" fn delete_xorigin( + cx: *mut JSContext, + _: RawHandleObject, + _: RawHandleId, + _: *mut ObjectOpResult, +) -> bool { throw_security_error(cx) } #[allow(unsafe_code)] -unsafe extern "C" fn getOwnPropertyDescriptor_xorigin(cx: *mut JSContext, - proxy: RawHandleObject, - id: RawHandleId, - desc: RawMutableHandle<PropertyDescriptor>) - -> bool -{ +unsafe extern "C" fn getOwnPropertyDescriptor_xorigin( + cx: *mut JSContext, + proxy: RawHandleObject, + id: RawHandleId, + desc: RawMutableHandle<PropertyDescriptor>, +) -> bool { let mut found = false; has_xorigin(cx, proxy, id, &mut found); found && getOwnPropertyDescriptor(cx, proxy, id, desc) } #[allow(unsafe_code)] -unsafe extern "C" fn defineProperty_xorigin(cx: *mut JSContext, - _: RawHandleObject, - _: RawHandleId, - _: RawHandle<PropertyDescriptor>, - _: *mut ObjectOpResult) - -> bool -{ +unsafe extern "C" fn defineProperty_xorigin( + cx: *mut JSContext, + _: RawHandleObject, + _: RawHandleId, + _: RawHandle<PropertyDescriptor>, + _: *mut ObjectOpResult, +) -> bool { throw_security_error(cx) } #[allow(unsafe_code)] -unsafe extern "C" fn preventExtensions_xorigin(cx: *mut JSContext, - _: RawHandleObject, - _: *mut ObjectOpResult) - -> bool -{ +unsafe extern "C" fn preventExtensions_xorigin( + cx: *mut JSContext, + _: RawHandleObject, + _: *mut ObjectOpResult, +) -> bool { throw_security_error(cx) } @@ -877,7 +939,7 @@ static XORIGIN_PROXY_HANDLER: ProxyTraps = ProxyTraps { // How WindowProxy objects are garbage collected. #[allow(unsafe_code)] -unsafe extern fn finalize(_fop: *mut JSFreeOp, obj: *mut JSObject) { +unsafe extern "C" fn finalize(_fop: *mut JSFreeOp, obj: *mut JSObject) { let mut slot = UndefinedValue(); GetProxyReservedSlot(obj, 0, &mut slot); let this = slot.to_private() as *mut WindowProxy; @@ -886,12 +948,15 @@ unsafe extern fn finalize(_fop: *mut JSFreeOp, obj: *mut JSObject) { return; } let jsobject = (*this).reflector.get_jsobject().get(); - debug!("WindowProxy finalize: {:p}, with reflector {:p} from {:p}.", this, jsobject, obj); + debug!( + "WindowProxy finalize: {:p}, with reflector {:p} from {:p}.", + this, jsobject, obj + ); let _ = Box::from_raw(this); } #[allow(unsafe_code)] -unsafe extern fn trace(trc: *mut JSTracer, obj: *mut JSObject) { +unsafe extern "C" fn trace(trc: *mut JSTracer, obj: *mut JSObject) { let mut slot = UndefinedValue(); GetProxyReservedSlot(obj, 0, &mut slot); let this = slot.to_private() as *const WindowProxy; diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index e5a1bfed223..8b6a96d8489 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -47,8 +47,7 @@ pub struct Worker { } impl Worker { - fn new_inherited(sender: Sender<DedicatedWorkerScriptMsg>, - closing: Arc<AtomicBool>) -> Worker { + fn new_inherited(sender: Sender<DedicatedWorkerScriptMsg>, closing: Arc<AtomicBool>) -> Worker { Worker { eventtarget: EventTarget::new_inherited(), sender: sender, @@ -57,12 +56,16 @@ impl Worker { } } - pub fn new(global: &GlobalScope, - sender: Sender<DedicatedWorkerScriptMsg>, - closing: Arc<AtomicBool>) -> DomRoot<Worker> { - reflect_dom_object(Box::new(Worker::new_inherited(sender, closing)), - global, - WorkerBinding::Wrap) + pub fn new( + global: &GlobalScope, + sender: Sender<DedicatedWorkerScriptMsg>, + closing: Arc<AtomicBool>, + ) -> DomRoot<Worker> { + reflect_dom_object( + Box::new(Worker::new_inherited(sender, closing)), + global, + WorkerBinding::Wrap, + ) } // https://html.spec.whatwg.org/multipage/#dom-worker @@ -90,21 +93,31 @@ impl Worker { let worker_id = global.get_next_worker_id(); if let Some(ref chan) = global.devtools_chan() { let pipeline_id = global.pipeline_id(); - let title = format!("Worker for {}", worker_url); - let page_info = DevtoolsPageInfo { - title: title, - url: worker_url.clone(), - }; - let _ = chan.send(ScriptToDevtoolsControlMsg::NewGlobal((pipeline_id, Some(worker_id)), - devtools_sender.clone(), - page_info)); + let title = format!("Worker for {}", worker_url); + let page_info = DevtoolsPageInfo { + title: title, + url: worker_url.clone(), + }; + let _ = chan.send(ScriptToDevtoolsControlMsg::NewGlobal( + (pipeline_id, Some(worker_id)), + devtools_sender.clone(), + page_info, + )); } let init = prepare_workerscope_init(global, Some(devtools_sender)); DedicatedWorkerGlobalScope::run_worker_scope( - init, worker_url, devtools_receiver, worker_ref, - global.script_chan(), sender, receiver, worker_load_origin, closing); + init, + worker_url, + devtools_receiver, + worker_ref, + global.script_chan(), + sender, + receiver, + worker_load_origin, + closing, + ); Ok(worker) } @@ -117,8 +130,7 @@ impl Worker { self.terminated.get() } - pub fn handle_message(address: TrustedWorkerAddress, - data: StructuredCloneData) { + pub fn handle_message(address: TrustedWorkerAddress, data: StructuredCloneData) { let worker = address.root(); if worker.is_terminated() { @@ -148,7 +160,10 @@ impl WorkerMethods for Worker { // NOTE: step 9 of https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage // indicates that a nonexistent communication channel should result in a silent error. - let _ = self.sender.send(DedicatedWorkerScriptMsg::CommonWorker(address, WorkerScriptMsg::DOMMessage(data))); + let _ = self.sender.send(DedicatedWorkerScriptMsg::CommonWorker( + address, + WorkerScriptMsg::DOMMessage(data), + )); Ok(()) } diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index da1f0ba7d36..fa2d0a449cf 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -51,20 +51,22 @@ use task_source::websocket::WebsocketTaskSource; use time::precise_time_ns; use timers::{IsInterval, TimerCallback}; -pub fn prepare_workerscope_init(global: &GlobalScope, - devtools_sender: Option<IpcSender<DevtoolScriptControlMsg>>) -> WorkerGlobalScopeInit { +pub fn prepare_workerscope_init( + global: &GlobalScope, + devtools_sender: Option<IpcSender<DevtoolScriptControlMsg>>, +) -> WorkerGlobalScopeInit { let init = WorkerGlobalScopeInit { - resource_threads: global.resource_threads().clone(), - mem_profiler_chan: global.mem_profiler_chan().clone(), - to_devtools_sender: global.devtools_chan().cloned(), - time_profiler_chan: global.time_profiler_chan().clone(), - from_devtools_sender: devtools_sender, - script_to_constellation_chan: global.script_to_constellation_chan().clone(), - scheduler_chan: global.scheduler_chan().clone(), - worker_id: global.get_next_worker_id(), - pipeline_id: global.pipeline_id(), - origin: global.origin().immutable().clone(), - }; + resource_threads: global.resource_threads().clone(), + mem_profiler_chan: global.mem_profiler_chan().clone(), + to_devtools_sender: global.devtools_chan().cloned(), + time_profiler_chan: global.time_profiler_chan().clone(), + from_devtools_sender: devtools_sender, + script_to_constellation_chan: global.script_to_constellation_chan().clone(), + scheduler_chan: global.scheduler_chan().clone(), + worker_id: global.get_next_worker_id(), + pipeline_id: global.pipeline_id(), + origin: global.origin().immutable().clone(), + }; init } @@ -179,9 +181,8 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { // https://html.spec.whatwg.org/multipage/#dom-workerglobalscope-location fn Location(&self) -> DomRoot<WorkerLocation> { - self.location.or_init(|| { - WorkerLocation::new(self, self.worker_url.clone()) - }) + self.location + .or_init(|| WorkerLocation::new(self, self.worker_url.clone())) } // https://html.spec.whatwg.org/multipage/#handler-workerglobalscope-onerror @@ -210,18 +211,23 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { pipeline_id: Some(self.upcast::<GlobalScope>().pipeline_id()), referrer_url: None, referrer_policy: None, - .. NetRequestInit::default() - }; - let (url, source) = match load_whole_resource(request, - &global_scope.resource_threads().sender()) { - Err(_) => return Err(Error::Network), - Ok((metadata, bytes)) => { - (metadata.final_url, String::from_utf8(bytes).unwrap()) - } + ..NetRequestInit::default() }; + let (url, source) = + match load_whole_resource(request, &global_scope.resource_threads().sender()) { + Err(_) => return Err(Error::Network), + Ok((metadata, bytes)) => { + (metadata.final_url, String::from_utf8(bytes).unwrap()) + }, + }; let result = self.runtime.evaluate_script( - self.reflector().get_jsobject(), &source, url.as_str(), 1, rval.handle_mut()); + self.reflector().get_jsobject(), + &source, + url.as_str(), + 1, + rval.handle_mut(), + ); maybe_resume_unwind(); @@ -230,7 +236,7 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { Err(_) => { println!("evaluate_script failed"); return Err(Error::JSFailed); - } + }, } } @@ -259,51 +265,76 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout - unsafe fn SetTimeout(&self, _cx: *mut JSContext, callback: Rc<Function>, - timeout: i32, args: Vec<HandleValue>) -> i32 { + unsafe fn SetTimeout( + &self, + _cx: *mut JSContext, + callback: Rc<Function>, + timeout: i32, + args: Vec<HandleValue>, + ) -> i32 { self.upcast::<GlobalScope>().set_timeout_or_interval( TimerCallback::FunctionTimerCallback(callback), args, timeout, - IsInterval::NonInterval) + IsInterval::NonInterval, + ) } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout - unsafe fn SetTimeout_(&self, _cx: *mut JSContext, callback: DOMString, - timeout: i32, args: Vec<HandleValue>) -> i32 { + unsafe fn SetTimeout_( + &self, + _cx: *mut JSContext, + callback: DOMString, + timeout: i32, + args: Vec<HandleValue>, + ) -> i32 { self.upcast::<GlobalScope>().set_timeout_or_interval( TimerCallback::StringTimerCallback(callback), args, timeout, - IsInterval::NonInterval) + IsInterval::NonInterval, + ) } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-cleartimeout fn ClearTimeout(&self, handle: i32) { - self.upcast::<GlobalScope>().clear_timeout_or_interval(handle); + self.upcast::<GlobalScope>() + .clear_timeout_or_interval(handle); } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - unsafe fn SetInterval(&self, _cx: *mut JSContext, callback: Rc<Function>, - timeout: i32, args: Vec<HandleValue>) -> i32 { + unsafe fn SetInterval( + &self, + _cx: *mut JSContext, + callback: Rc<Function>, + timeout: i32, + args: Vec<HandleValue>, + ) -> i32 { self.upcast::<GlobalScope>().set_timeout_or_interval( TimerCallback::FunctionTimerCallback(callback), args, timeout, - IsInterval::Interval) + IsInterval::Interval, + ) } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - unsafe fn SetInterval_(&self, _cx: *mut JSContext, callback: DOMString, - timeout: i32, args: Vec<HandleValue>) -> i32 { + unsafe fn SetInterval_( + &self, + _cx: *mut JSContext, + callback: DOMString, + timeout: i32, + args: Vec<HandleValue>, + ) -> i32 { self.upcast::<GlobalScope>().set_timeout_or_interval( TimerCallback::StringTimerCallback(callback), args, timeout, - IsInterval::Interval) + IsInterval::Interval, + ) } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-clearinterval @@ -313,7 +344,11 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#fetch-method - fn Fetch(&self, input: RequestOrUSVString, init: RootedTraceableBox<RequestInit>) -> Rc<Promise> { + fn Fetch( + &self, + input: RequestOrUSVString, + init: RootedTraceableBox<RequestInit>, + ) -> Rc<Promise> { fetch::Fetch(self.upcast(), input, init) } @@ -321,26 +356,37 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { fn Performance(&self) -> DomRoot<Performance> { self.performance.or_init(|| { let global_scope = self.upcast::<GlobalScope>(); - Performance::new(global_scope, - 0 /* navigation start is not used in workers */, - self.navigation_start_precise) + Performance::new( + global_scope, + 0, /* navigation start is not used in workers */ + self.navigation_start_precise, + ) }) } // https://html.spec.whatwg.org/multipage/#dom-origin fn Origin(&self) -> USVString { - USVString(self.upcast::<GlobalScope>().origin().immutable().ascii_serialization()) + USVString( + self.upcast::<GlobalScope>() + .origin() + .immutable() + .ascii_serialization(), + ) } } - impl WorkerGlobalScope { #[allow(unsafe_code)] pub fn execute_script(&self, source: DOMString) { let _aes = AutoEntryScript::new(self.upcast()); rooted!(in(self.runtime.cx()) let mut rval = UndefinedValue()); match self.runtime.evaluate_script( - self.reflector().get_jsobject(), &source, self.worker_url.as_str(), 1, rval.handle_mut()) { + self.reflector().get_jsobject(), + &source, + self.worker_url.as_str(), + 1, + rval.handle_mut(), + ) { Ok(_) => (), Err(_) => { if self.is_closing() { @@ -350,12 +396,14 @@ impl WorkerGlobalScope { // https://github.com/servo/servo/issues/6422 println!("evaluate_script failed"); unsafe { - let _ac = JSAutoCompartment::new(self.runtime.cx(), - self.reflector().get_jsobject().get()); + let _ac = JSAutoCompartment::new( + self.runtime.cx(), + self.reflector().get_jsobject().get(), + ); report_pending_exception(self.runtime.cx(), true); } } - } + }, } } @@ -402,9 +450,7 @@ impl WorkerGlobalScope { pub fn process_event(&self, msg: CommonScriptMsg) { match msg { - CommonScriptMsg::Task(_, task, _, _) => { - task.run_box() - }, + CommonScriptMsg::Task(_, task, _, _) => task.run_box(), CommonScriptMsg::CollectReports(reports_chan) => { let cx = self.get_cx(); let path_seg = format!("url({})", self.get_url()); diff --git a/components/script/dom/workerlocation.rs b/components/script/dom/workerlocation.rs index 0a20874c577..1227982d1c0 100644 --- a/components/script/dom/workerlocation.rs +++ b/components/script/dom/workerlocation.rs @@ -28,9 +28,11 @@ impl WorkerLocation { } pub fn new(global: &WorkerGlobalScope, url: ServoUrl) -> DomRoot<WorkerLocation> { - reflect_dom_object(Box::new(WorkerLocation::new_inherited(url)), - global, - WorkerLocationBinding::Wrap) + reflect_dom_object( + Box::new(WorkerLocation::new_inherited(url)), + global, + WorkerLocationBinding::Wrap, + ) } } diff --git a/components/script/dom/workernavigator.rs b/components/script/dom/workernavigator.rs index 47c48df9226..d4b2eef4b17 100644 --- a/components/script/dom/workernavigator.rs +++ b/components/script/dom/workernavigator.rs @@ -28,9 +28,11 @@ impl WorkerNavigator { } pub fn new(global: &WorkerGlobalScope) -> DomRoot<WorkerNavigator> { - reflect_dom_object(Box::new(WorkerNavigator::new_inherited()), - global, - WorkerNavigatorBinding::Wrap) + reflect_dom_object( + Box::new(WorkerNavigator::new_inherited()), + global, + WorkerNavigatorBinding::Wrap, + ) } } @@ -77,6 +79,7 @@ impl WorkerNavigatorMethods for WorkerNavigator { // https://w3c.github.io/permissions/#navigator-and-workernavigator-extension fn Permissions(&self) -> DomRoot<Permissions> { - self.permissions.or_init(|| Permissions::new(&self.global())) + self.permissions + .or_init(|| Permissions::new(&self.global())) } } diff --git a/components/script/dom/worklet.rs b/components/script/dom/worklet.rs index 498cce10680..84a2b6f696b 100644 --- a/components/script/dom/worklet.rs +++ b/components/script/dom/worklet.rs @@ -92,7 +92,11 @@ impl Worklet { pub fn new(window: &Window, global_type: WorkletGlobalScopeType) -> DomRoot<Worklet> { debug!("Creating worklet {:?}.", global_type); - reflect_dom_object(Box::new(Worklet::new_inherited(window, global_type)), window, Wrap) + reflect_dom_object( + Box::new(Worklet::new_inherited(window, global_type)), + window, + Wrap, + ) } pub fn worklet_id(&self) -> WorkletId { @@ -120,7 +124,7 @@ impl WorkletMethods for Worklet { debug!("URL {:?} parse error {:?}.", module_url.0, err); promise.reject_error(Error::Syntax); return promise; - } + }, }; debug!("Adding Worklet module {}.", module_url_record); @@ -129,15 +133,17 @@ impl WorkletMethods for Worklet { let global = self.window.upcast::<GlobalScope>(); let pool = ScriptThread::worklet_thread_pool(); - pool.fetch_and_invoke_a_worklet_script(global.pipeline_id(), - self.worklet_id, - self.global_type, - self.window.origin().immutable().clone(), - global.api_base_url(), - module_url_record, - options.credentials.clone(), - pending_tasks_struct, - &promise); + pool.fetch_and_invoke_a_worklet_script( + global.pipeline_id(), + self.worklet_id, + self.global_type, + self.window.origin().immutable().clone(), + global.api_base_url(), + module_url_record, + options.credentials.clone(), + pending_tasks_struct, + &promise, + ); // Step 5. debug!("Returning promise."); @@ -163,7 +169,9 @@ struct PendingTasksStruct(Arc<AtomicIsize>); impl PendingTasksStruct { fn new() -> PendingTasksStruct { - PendingTasksStruct(Arc::new(AtomicIsize::new(WORKLET_THREAD_POOL_SIZE as isize))) + PendingTasksStruct(Arc::new(AtomicIsize::new( + WORKLET_THREAD_POOL_SIZE as isize, + ))) } fn set_counter_to(&self, value: isize) -> isize { @@ -274,19 +282,24 @@ impl WorkletThreadPool { /// If all of the threads load successfully, the promise is resolved. /// If any of the threads fails to load, the promise is rejected. /// <https://drafts.css-houdini.org/worklets/#fetch-and-invoke-a-worklet-script> - fn fetch_and_invoke_a_worklet_script(&self, - pipeline_id: PipelineId, - worklet_id: WorkletId, - global_type: WorkletGlobalScopeType, - origin: ImmutableOrigin, - base_url: ServoUrl, - script_url: ServoUrl, - credentials: RequestCredentials, - pending_tasks_struct: PendingTasksStruct, - promise: &Rc<Promise>) - { + fn fetch_and_invoke_a_worklet_script( + &self, + pipeline_id: PipelineId, + worklet_id: WorkletId, + global_type: WorkletGlobalScopeType, + origin: ImmutableOrigin, + base_url: ServoUrl, + script_url: ServoUrl, + credentials: RequestCredentials, + pending_tasks_struct: PendingTasksStruct, + promise: &Rc<Promise>, + ) { // Send each thread a control message asking it to load the script. - for sender in &[&self.control_sender_0, &self.control_sender_1, &self.control_sender_2] { + for sender in &[ + &self.control_sender_0, + &self.control_sender_1, + &self.control_sender_2, + ] { let _ = sender.send(WorkletControl::FetchAndInvokeAWorkletScript { pipeline_id: pipeline_id, worklet_id: worklet_id, @@ -454,7 +467,7 @@ impl WorkletThread { // The whole point of this thread pool is to perform tasks! WorkletData::Task(id, task) => { self.perform_a_worklet_task(id, task); - } + }, // To start swapping roles, get ready to perform an atomic swap, // and block waiting for the other end to finish it. // NOTE: the cold backup can block on the primary or the hot backup; @@ -463,21 +476,22 @@ impl WorkletThread { // this total ordering on thread roles is what guarantees deadlock-freedom. WorkletData::StartSwapRoles(sender) => { let (our_swapper, their_swapper) = swapper(); - sender.send(WorkletData::FinishSwapRoles(their_swapper)).unwrap(); + sender + .send(WorkletData::FinishSwapRoles(their_swapper)) + .unwrap(); let _ = our_swapper.swap(&mut self.role); - } + }, // To finish swapping roles, perform the atomic swap. // The other end should have already started the swap, so this shouldn't block. WorkletData::FinishSwapRoles(swapper) => { let _ = swapper.swap(&mut self.role); - } + }, // Wake up! There may be control messages to process. - WorkletData::WakeUp => { - } + WorkletData::WakeUp => {}, // Quit! WorkletData::Quit => { return; - } + }, } // Only process control messages if we're the cold backup, // otherwise if there are outstanding control messages, @@ -522,27 +536,41 @@ impl WorkletThread { /// Perform a GC. #[allow(unsafe_code)] fn gc(&mut self) { - debug!("BEGIN GC (usage = {}, threshold = {}).", self.current_memory_usage(), self.gc_threshold); + debug!( + "BEGIN GC (usage = {}, threshold = {}).", + self.current_memory_usage(), + self.gc_threshold + ); unsafe { JS_GC(self.runtime.cx()) }; self.gc_threshold = max(MIN_GC_THRESHOLD, self.current_memory_usage() * 2); - debug!("END GC (usage = {}, threshold = {}).", self.current_memory_usage(), self.gc_threshold); + debug!( + "END GC (usage = {}, threshold = {}).", + self.current_memory_usage(), + self.gc_threshold + ); } /// Get the worklet global scope for a given worklet. /// Creates the worklet global scope if it doesn't exist. - fn get_worklet_global_scope(&mut self, - pipeline_id: PipelineId, - worklet_id: WorkletId, - global_type: WorkletGlobalScopeType, - base_url: ServoUrl) - -> DomRoot<WorkletGlobalScope> - { + fn get_worklet_global_scope( + &mut self, + pipeline_id: PipelineId, + worklet_id: WorkletId, + global_type: WorkletGlobalScopeType, + base_url: ServoUrl, + ) -> DomRoot<WorkletGlobalScope> { match self.global_scopes.entry(worklet_id) { hash_map::Entry::Occupied(entry) => DomRoot::from_ref(entry.get()), hash_map::Entry::Vacant(entry) => { debug!("Creating new worklet global scope."); let executor = WorkletExecutor::new(worklet_id, self.primary_sender.clone()); - let result = global_type.new(&self.runtime, pipeline_id, base_url, executor, &self.global_init); + let result = global_type.new( + &self.runtime, + pipeline_id, + base_url, + executor, + &self.global_init, + ); entry.insert(Dom::from_ref(&*result)); result }, @@ -551,15 +579,16 @@ impl WorkletThread { /// Fetch and invoke a worklet script. /// <https://drafts.css-houdini.org/worklets/#fetch-and-invoke-a-worklet-script> - fn fetch_and_invoke_a_worklet_script(&self, - global_scope: &WorkletGlobalScope, - pipeline_id: PipelineId, - origin: ImmutableOrigin, - script_url: ServoUrl, - credentials: RequestCredentials, - pending_tasks_struct: PendingTasksStruct, - promise: TrustedPromise) - { + fn fetch_and_invoke_a_worklet_script( + &self, + global_scope: &WorkletGlobalScope, + pipeline_id: PipelineId, + origin: ImmutableOrigin, + script_url: ServoUrl, + credentials: RequestCredentials, + pending_tasks_struct: PendingTasksStruct, + promise: TrustedPromise, + ) { debug!("Fetching from {}.", script_url); // Step 1. // TODO: Settings object? @@ -575,9 +604,10 @@ impl WorkletThread { mode: RequestMode::CorsMode, credentials_mode: credentials.into(), origin, - .. RequestInit::default() + ..RequestInit::default() }; - let script = load_whole_resource(request, &resource_fetcher).ok() + let script = load_whole_resource(request, &resource_fetcher) + .ok() .and_then(|(_, bytes)| String::from_utf8(bytes).ok()); // Step 4. @@ -586,7 +616,9 @@ impl WorkletThread { // Also, the spec currently doesn't allow exceptions to be propagated // to the main script thread. // https://github.com/w3c/css-houdini-drafts/issues/407 - let ok = script.map(|script| global_scope.evaluate_js(&*script)).unwrap_or(false); + let ok = script + .map(|script| global_scope.evaluate_js(&*script)) + .unwrap_or(false); if !ok { // Step 3. @@ -602,7 +634,10 @@ impl WorkletThread { if old_counter == 1 { debug!("Resolving promise."); let msg = MainThreadScriptMsg::WorkletLoaded(pipeline_id); - self.global_init.to_script_thread_sender.send(msg).expect("Worklet thread outlived script thread."); + self.global_init + .to_script_thread_sender + .send(msg) + .expect("Worklet thread outlived script thread."); self.run_in_script_thread(promise.resolve_task(())); } } @@ -620,21 +655,28 @@ impl WorkletThread { fn process_control(&mut self, control: WorkletControl) { match control { WorkletControl::FetchAndInvokeAWorkletScript { - pipeline_id, worklet_id, global_type, origin, base_url, - script_url, credentials, pending_tasks_struct, promise, + pipeline_id, + worklet_id, + global_type, + origin, + base_url, + script_url, + credentials, + pending_tasks_struct, + promise, } => { - let global = self.get_worklet_global_scope(pipeline_id, - worklet_id, - global_type, - base_url); - self.fetch_and_invoke_a_worklet_script(&*global, - pipeline_id, - origin, - script_url, - credentials, - pending_tasks_struct, - promise) - } + let global = + self.get_worklet_global_scope(pipeline_id, worklet_id, global_type, base_url); + self.fetch_and_invoke_a_worklet_script( + &*global, + pipeline_id, + origin, + script_url, + credentials, + pending_tasks_struct, + promise, + ) + }, } } @@ -652,7 +694,10 @@ impl WorkletThread { TaskSourceName::DOMManipulation, ); let msg = MainThreadScriptMsg::Common(msg); - self.global_init.to_script_thread_sender.send(msg).expect("Worklet thread outlived script thread."); + self.global_init + .to_script_thread_sender + .send(msg) + .expect("Worklet thread outlived script thread."); } } @@ -674,6 +719,8 @@ impl WorkletExecutor { /// Schedule a worklet task to be peformed by the worklet thread pool. pub fn schedule_a_worklet_task(&self, task: WorkletTask) { - let _ = self.primary_sender.send(WorkletData::Task(self.worklet_id, task)); + let _ = self + .primary_sender + .send(WorkletData::Task(self.worklet_id, task)); } } diff --git a/components/script/dom/workletglobalscope.rs b/components/script/dom/workletglobalscope.rs index 6a3dc033aad..4a352535893 100644 --- a/components/script/dom/workletglobalscope.rs +++ b/components/script/dom/workletglobalscope.rs @@ -88,24 +88,19 @@ impl WorkletGlobalScope { pub fn evaluate_js(&self, script: &str) -> bool { debug!("Evaluating Dom."); rooted!(in (self.globalscope.get_cx()) let mut rval = UndefinedValue()); - self.globalscope.evaluate_js_on_global_with_result(&*script, rval.handle_mut()) + self.globalscope + .evaluate_js_on_global_with_result(&*script, rval.handle_mut()) } /// Register a paint worklet to the script thread. - pub fn register_paint_worklet( - &self, - name: Atom, - properties: Vec<Atom>, - painter: Box<Painter>, - ) { + pub fn register_paint_worklet(&self, name: Atom, properties: Vec<Atom>, painter: Box<Painter>) { self.to_script_thread_sender .send(MainThreadScriptMsg::RegisterPaintWorklet { pipeline_id: self.globalscope.pipeline_id(), name, properties, painter, - }) - .expect("Worklet thread outlived script thread."); + }).expect("Worklet thread outlived script thread."); } /// The base URL of this global. @@ -165,19 +160,29 @@ pub enum WorkletGlobalScopeType { impl WorkletGlobalScopeType { /// Create a new heap-allocated `WorkletGlobalScope`. - pub fn new(&self, - runtime: &Runtime, - pipeline_id: PipelineId, - base_url: ServoUrl, - executor: WorkletExecutor, - init: &WorkletGlobalScopeInit) - -> DomRoot<WorkletGlobalScope> - { + pub fn new( + &self, + runtime: &Runtime, + pipeline_id: PipelineId, + base_url: ServoUrl, + executor: WorkletExecutor, + init: &WorkletGlobalScopeInit, + ) -> DomRoot<WorkletGlobalScope> { match *self { - WorkletGlobalScopeType::Test => - DomRoot::upcast(TestWorkletGlobalScope::new(runtime, pipeline_id, base_url, executor, init)), - WorkletGlobalScopeType::Paint => - DomRoot::upcast(PaintWorkletGlobalScope::new(runtime, pipeline_id, base_url, executor, init)), + WorkletGlobalScopeType::Test => DomRoot::upcast(TestWorkletGlobalScope::new( + runtime, + pipeline_id, + base_url, + executor, + init, + )), + WorkletGlobalScopeType::Paint => DomRoot::upcast(PaintWorkletGlobalScope::new( + runtime, + pipeline_id, + base_url, + executor, + init, + )), } } } diff --git a/components/script/dom/xmldocument.rs b/components/script/dom/xmldocument.rs index abd5ed64635..9854d503ed4 100644 --- a/components/script/dom/xmldocument.rs +++ b/components/script/dom/xmldocument.rs @@ -28,44 +28,49 @@ pub struct XMLDocument { } impl XMLDocument { - fn new_inherited(window: &Window, - has_browsing_context: HasBrowsingContext, - url: Option<ServoUrl>, - origin: MutableOrigin, - is_html_document: IsHTMLDocument, - content_type: Option<Mime>, - last_modified: Option<String>, - activity: DocumentActivity, - source: DocumentSource, - doc_loader: DocumentLoader) -> XMLDocument { + fn new_inherited( + window: &Window, + has_browsing_context: HasBrowsingContext, + url: Option<ServoUrl>, + origin: MutableOrigin, + is_html_document: IsHTMLDocument, + content_type: Option<Mime>, + last_modified: Option<String>, + activity: DocumentActivity, + source: DocumentSource, + doc_loader: DocumentLoader, + ) -> XMLDocument { XMLDocument { - document: Document::new_inherited(window, - has_browsing_context, - url, - origin, - is_html_document, - content_type, - last_modified, - activity, - source, - doc_loader, - None, - None, - Default::default()), + document: Document::new_inherited( + window, + has_browsing_context, + url, + origin, + is_html_document, + content_type, + last_modified, + activity, + source, + doc_loader, + None, + None, + Default::default(), + ), } } - pub fn new(window: &Window, - has_browsing_context: HasBrowsingContext, - url: Option<ServoUrl>, - origin: MutableOrigin, - doctype: IsHTMLDocument, - content_type: Option<Mime>, - last_modified: Option<String>, - activity: DocumentActivity, - source: DocumentSource, - doc_loader: DocumentLoader) - -> DomRoot<XMLDocument> { + pub fn new( + window: &Window, + has_browsing_context: HasBrowsingContext, + url: Option<ServoUrl>, + origin: MutableOrigin, + doctype: IsHTMLDocument, + content_type: Option<Mime>, + last_modified: Option<String>, + activity: DocumentActivity, + source: DocumentSource, + doc_loader: DocumentLoader, + ) -> DomRoot<XMLDocument> { let doc = reflect_dom_object( Box::new(XMLDocument::new_inherited( window, @@ -77,10 +82,10 @@ impl XMLDocument { last_modified, activity, source, - doc_loader + doc_loader, )), window, - XMLDocumentBinding::Wrap + XMLDocumentBinding::Wrap, ); { let node = doc.upcast::<Node>(); @@ -103,7 +108,11 @@ impl XMLDocumentMethods for XMLDocument { #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter - unsafe fn NamedGetter(&self, _cx: *mut JSContext, name: DOMString) -> Option<NonNull<JSObject>> { + unsafe fn NamedGetter( + &self, + _cx: *mut JSContext, + name: DOMString, + ) -> Option<NonNull<JSObject>> { self.upcast::<Document>().NamedGetter(_cx, name) } } diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index 3dee1e18fe6..38d206b3a1b 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -115,7 +115,7 @@ impl XHRProgress { XHRProgress::HeadersReceived(id, _, _) | XHRProgress::Loading(id, _) | XHRProgress::Done(id) | - XHRProgress::Errored(id, _) => id + XHRProgress::Errored(id, _) => id, } } } @@ -181,8 +181,8 @@ impl XMLHttpRequest { upload: Dom::from_ref(&*XMLHttpRequestUpload::new(global)), response_url: DomRefCell::new(String::new()), status: Cell::new(0), - status_text: DomRefCell::new(ByteString::new(vec!())), - response: DomRefCell::new(ByteString::new(vec!())), + status_text: DomRefCell::new(ByteString::new(vec![])), + response: DomRefCell::new(ByteString::new(vec![])), response_type: Cell::new(XMLHttpRequestResponseType::_empty), response_xml: Default::default(), response_blob: Default::default(), @@ -210,9 +210,11 @@ impl XMLHttpRequest { } } pub fn new(global: &GlobalScope) -> DomRoot<XMLHttpRequest> { - reflect_dom_object(Box::new(XMLHttpRequest::new_inherited(global)), - global, - XMLHttpRequestBinding::Wrap) + reflect_dom_object( + Box::new(XMLHttpRequest::new_inherited(global)), + global, + XMLHttpRequestBinding::Wrap, + ) } // https://xhr.spec.whatwg.org/#constructors @@ -224,11 +226,13 @@ impl XMLHttpRequest { self.sync.get() && self.global().is::<Window>() } - fn initiate_async_xhr(context: Arc<Mutex<XHRContext>>, - task_source: NetworkingTaskSource, - global: &GlobalScope, - init: RequestInit, - cancellation_chan: ipc::IpcReceiver<()>) { + fn initiate_async_xhr( + context: Arc<Mutex<XHRContext>>, + task_source: NetworkingTaskSource, + global: &GlobalScope, + init: RequestInit, + cancellation_chan: ipc::IpcReceiver<()>, + ) { impl FetchResponseListener for XHRContext { fn process_request_body(&mut self) { // todo @@ -238,8 +242,7 @@ impl XMLHttpRequest { // todo } - fn process_response(&mut self, - metadata: Result<FetchMetadata, NetworkError>) { + fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) { let xhr = self.xhr.root(); let rv = xhr.process_headers_available(self.gen_id, metadata); if rv.is_err() { @@ -249,11 +252,16 @@ impl XMLHttpRequest { fn process_response_chunk(&mut self, mut chunk: Vec<u8>) { self.buf.borrow_mut().append(&mut chunk); - self.xhr.root().process_data_available(self.gen_id, self.buf.borrow().clone()); + self.xhr + .root() + .process_data_available(self.gen_id, self.buf.borrow().clone()); } fn process_response_eof(&mut self, response: Result<(), NetworkError>) { - let rv = self.xhr.root().process_response_complete(self.gen_id, response); + let rv = self + .xhr + .root() + .process_response_complete(self.gen_id, response); *self.sync_status.borrow_mut() = Some(rv); } } @@ -269,19 +277,30 @@ impl XMLHttpRequest { let listener = NetworkListener { context: context, task_source: task_source, - canceller: Some(global.task_canceller(TaskSourceName::Networking)) + canceller: Some(global.task_canceller(TaskSourceName::Networking)), }; - ROUTER.add_route(action_receiver.to_opaque(), Box::new(move |message| { - listener.notify_fetch(message.to().unwrap()); - })); - global.core_resource_thread().send( - Fetch(init, FetchChannels::ResponseMsg(action_sender, Some(cancellation_chan)))).unwrap(); + ROUTER.add_route( + action_receiver.to_opaque(), + Box::new(move |message| { + listener.notify_fetch(message.to().unwrap()); + }), + ); + global + .core_resource_thread() + .send(Fetch( + init, + FetchChannels::ResponseMsg(action_sender, Some(cancellation_chan)), + )).unwrap(); } } impl XMLHttpRequestMethods for XMLHttpRequest { // https://xhr.spec.whatwg.org/#handler-xhr-onreadystatechange - event_handler!(readystatechange, GetOnreadystatechange, SetOnreadystatechange); + event_handler!( + readystatechange, + GetOnreadystatechange, + SetOnreadystatechange + ); // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate fn ReadyState(&self) -> u16 { @@ -295,8 +314,14 @@ impl XMLHttpRequestMethods for XMLHttpRequest { } // https://xhr.spec.whatwg.org/#the-open()-method - fn Open_(&self, method: ByteString, url: USVString, async: bool, - username: Option<USVString>, password: Option<USVString>) -> ErrorResult { + fn Open_( + &self, + method: ByteString, + url: USVString, + async: bool, + username: Option<USVString>, + password: Option<USVString>, + ) -> ErrorResult { // Step 1 if let Some(window) = DomRoot::downcast::<Window>(self.global()) { if !window.Document().is_fully_active() { @@ -314,10 +339,9 @@ impl XMLHttpRequestMethods for XMLHttpRequest { // despite the there being a rust-http method variant for them let upper = s.to_ascii_uppercase(); match &*upper { - "DELETE" | "GET" | "HEAD" | "OPTIONS" | - "POST" | "PUT" | "CONNECT" | "TRACE" | + "DELETE" | "GET" | "HEAD" | "OPTIONS" | "POST" | "PUT" | "CONNECT" | "TRACE" | "TRACK" => upper.parse().ok(), - _ => s.parse().ok() + _ => s.parse().ok(), } }); @@ -328,7 +352,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { Some(parsed_method) => { // Step 3 if !is_token(&method) { - return Err(Error::Syntax) + return Err(Error::Syntax); } // Step 2 @@ -337,7 +361,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { let mut parsed_url = match base.join(&url.0) { Ok(parsed) => parsed, // Step 7 - Err(_) => return Err(Error::Syntax) + Err(_) => return Err(Error::Syntax), }; // Step 9 @@ -352,8 +376,10 @@ impl XMLHttpRequestMethods for XMLHttpRequest { // Step 10 if !async { // FIXME: This should only happen if the global environment is a document environment - if self.timeout.get() != 0 || self.response_type.get() != XMLHttpRequestResponseType::_empty { - return Err(Error::InvalidAccess) + if self.timeout.get() != 0 || + self.response_type.get() != XMLHttpRequestResponseType::_empty + { + return Err(Error::InvalidAccess); } } // Step 11 - abort existing requests @@ -371,7 +397,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { self.sync.set(!async); *self.request_headers.borrow_mut() = Headers::new(); self.send_flag.set(false); - *self.status_text.borrow_mut() = ByteString::new(vec!()); + *self.status_text.borrow_mut() = ByteString::new(vec![]); self.status.set(0); // Step 13 @@ -383,7 +409,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { // Step 3 // This includes cases where as_str() returns None, and when is_token() returns false, // both of which indicate invalid extension method names - _ => Err(Error::Syntax) + _ => Err(Error::Syntax), } } @@ -413,13 +439,16 @@ impl XMLHttpRequestMethods for XMLHttpRequest { s } }, - None => unreachable!() + None => unreachable!(), }; - debug!("SetRequestHeader: name={:?}, value={:?}", name.as_str(), str::from_utf8(value).ok()); + debug!( + "SetRequestHeader: name={:?}, value={:?}", + name.as_str(), + str::from_utf8(value).ok() + ); let mut headers = self.request_headers.borrow_mut(); - // Step 6 let value = match headers.get_raw(name_str) { Some(raw) => { @@ -485,7 +514,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { _ => { self.with_credentials.set(with_credentials); Ok(()) - } + }, } } @@ -504,7 +533,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { // Step 3 let data = match *self.request_method.borrow() { Method::Get | Method::Head => None, - _ => data + _ => data, }; // Step 4 (first half) let extracted_or_serialized = match data { @@ -521,12 +550,17 @@ impl XMLHttpRequestMethods for XMLHttpRequest { Some(DocumentOrBodyInit::FormData(ref formdata)) => Some(formdata.extract()), Some(DocumentOrBodyInit::String(ref str)) => Some(str.extract()), Some(DocumentOrBodyInit::URLSearchParams(ref urlsp)) => Some(urlsp.extract()), - Some(DocumentOrBodyInit::ArrayBuffer(ref typedarray)) => Some((typedarray.to_vec(), None)), - Some(DocumentOrBodyInit::ArrayBufferView(ref typedarray)) => Some((typedarray.to_vec(), None)), + Some(DocumentOrBodyInit::ArrayBuffer(ref typedarray)) => { + Some((typedarray.to_vec(), None)) + }, + Some(DocumentOrBodyInit::ArrayBufferView(ref typedarray)) => { + Some((typedarray.to_vec(), None)) + }, None => None, }; - self.request_body_len.set(extracted_or_serialized.as_ref().map_or(0, |e| e.0.len())); + self.request_body_len + .set(extracted_or_serialized.as_ref().map_or(0, |e| e.0.len())); // todo preserved headers? @@ -536,7 +570,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { self.upload_complete.set(match extracted_or_serialized { None => true, Some(ref e) if e.0.is_empty() => true, - _ => false + _ => false, }); // Step 8 self.send_flag.set(true); @@ -558,7 +592,6 @@ impl XMLHttpRequestMethods for XMLHttpRequest { return Ok(()); } } - } // Step 5 @@ -594,7 +627,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { referrer_url: self.referrer_url.clone(), referrer_policy: self.referrer_policy.clone(), pipeline_id: Some(self.global().pipeline_id()), - .. RequestInit::default() + ..RequestInit::default() }; // step 4 (second half) @@ -605,14 +638,18 @@ impl XMLHttpRequestMethods for XMLHttpRequest { // XHR spec differs from http, and says UTF-8 should be in capitals, // instead of "utf-8", which is what Hyper defaults to. So not // using content types provided by Hyper. - Some(MimeValue::Ext("UTF-8".to_string())), + { + Some(MimeValue::Ext("UTF-8".to_string())) + }, _ => None, }; let mut content_type_set = false; if let Some(ref ct) = *content_type { if !request.headers.has::<ContentType>() { - request.headers.set_raw("content-type", vec![ct.bytes().collect()]); + request + .headers + .set_raw("content-type", vec![ct.bytes().collect()]); content_type_set = true; } } @@ -631,8 +668,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { } } } - - } + }, _ => (), } @@ -660,14 +696,15 @@ impl XMLHttpRequestMethods for XMLHttpRequest { // Step 2 let state = self.ready_state.get(); if (state == XMLHttpRequestState::Opened && self.send_flag.get()) || - state == XMLHttpRequestState::HeadersReceived || - state == XMLHttpRequestState::Loading { + state == XMLHttpRequestState::HeadersReceived || + state == XMLHttpRequestState::Loading + { let gen_id = self.generation_id.get(); self.process_partial_response(XHRProgress::Errored(gen_id, Error::Abort)); // If open was called in one of the handlers invoked by the // above call then we should terminate the abort sequence if self.generation_id.get() != gen_id { - return + return; } } // Step 3 @@ -691,11 +728,10 @@ impl XMLHttpRequestMethods for XMLHttpRequest { // https://xhr.spec.whatwg.org/#the-getresponseheader()-method fn GetResponseHeader(&self, name: ByteString) -> Option<ByteString> { - self.filter_response_headers().iter().find(|h| { - name.eq_ignore_case(&h.name().parse().unwrap()) - }).map(|h| { - ByteString::new(h.value_string().into_bytes()) - }) + self.filter_response_headers() + .iter() + .find(|h| name.eq_ignore_case(&h.name().parse().unwrap())) + .map(|h| ByteString::new(h.value_string().into_bytes())) } // https://xhr.spec.whatwg.org/#the-getallresponseheaders()-method @@ -707,7 +743,9 @@ impl XMLHttpRequestMethods for XMLHttpRequest { fn OverrideMimeType(&self, mime: DOMString) -> ErrorResult { // Step 1 match self.ready_state.get() { - XMLHttpRequestState::Loading | XMLHttpRequestState::Done => return Err(Error::InvalidState), + XMLHttpRequestState::Loading | XMLHttpRequestState::Done => { + return Err(Error::InvalidState) + }, _ => {}, } // Step 2 @@ -717,9 +755,8 @@ impl XMLHttpRequestMethods for XMLHttpRequest { *self.override_mime_type.borrow_mut() = Some(mime_no_params); // Step 4 let value = override_mime.get_param(mime::Attr::Charset); - *self.override_charset.borrow_mut() = value.and_then(|value| { - Encoding::for_label(value.as_bytes()) - }); + *self.override_charset.borrow_mut() = + value.and_then(|value| Encoding::for_label(value.as_bytes())); Ok(()) } @@ -731,7 +768,9 @@ impl XMLHttpRequestMethods for XMLHttpRequest { // https://xhr.spec.whatwg.org/#the-responsetype-attribute fn SetResponseType(&self, response_type: XMLHttpRequestResponseType) -> ErrorResult { // Step 1 - if self.global().is::<WorkerGlobalScope>() && response_type == XMLHttpRequestResponseType::Document { + if self.global().is::<WorkerGlobalScope>() && + response_type == XMLHttpRequestResponseType::Document + { return Ok(()); } match self.ready_state.get() { @@ -746,7 +785,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { self.response_type.set(response_type); Ok(()) } - } + }, } } @@ -758,10 +797,12 @@ impl XMLHttpRequestMethods for XMLHttpRequest { XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Text => { let ready_state = self.ready_state.get(); // Step 2 - if ready_state == XMLHttpRequestState::Done || ready_state == XMLHttpRequestState::Loading { + if ready_state == XMLHttpRequestState::Done || + ready_state == XMLHttpRequestState::Loading + { self.text_response().to_jsval(cx, rval.handle_mut()); } else { - // Step 1 + // Step 1 "".to_jsval(cx, rval.handle_mut()); } }, @@ -779,12 +820,10 @@ impl XMLHttpRequestMethods for XMLHttpRequest { XMLHttpRequestResponseType::Blob => { self.blob_response().to_jsval(cx, rval.handle_mut()); }, - XMLHttpRequestResponseType::Arraybuffer => { - match self.arraybuffer_response(cx) { - Some(js_object) => js_object.to_jsval(cx, rval.handle_mut()), - None => return NullValue(), - } - } + XMLHttpRequestResponseType::Arraybuffer => match self.arraybuffer_response(cx) { + Some(js_object) => js_object.to_jsval(cx, rval.handle_mut()), + None => return NullValue(), + }, } rval.get() } @@ -795,13 +834,15 @@ impl XMLHttpRequestMethods for XMLHttpRequest { XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Text => { Ok(USVString(String::from(match self.ready_state.get() { // Step 3 - XMLHttpRequestState::Loading | XMLHttpRequestState::Done => self.text_response(), + XMLHttpRequestState::Loading | XMLHttpRequestState::Done => { + self.text_response() + }, // Step 2 - _ => "".to_owned() + _ => "".to_owned(), }))) }, // Step 1 - _ => Err(Error::InvalidState) + _ => Err(Error::InvalidState), } } @@ -819,34 +860,36 @@ impl XMLHttpRequestMethods for XMLHttpRequest { if let XMLHttpRequestState::Done = self.ready_state.get() { Ok(self.document_response()) } else { - // Step 2 + // Step 2 Ok(None) } - } + }, // Step 1 - _ => { Err(Error::InvalidState) } + _ => Err(Error::InvalidState), } } } pub type TrustedXHRAddress = Trusted<XMLHttpRequest>; - impl XMLHttpRequest { fn change_ready_state(&self, rs: XMLHttpRequestState) { assert_ne!(self.ready_state.get(), rs); self.ready_state.set(rs); - let event = Event::new(&self.global(), - atom!("readystatechange"), - EventBubbles::DoesNotBubble, - EventCancelable::Cancelable); + let event = Event::new( + &self.global(), + atom!("readystatechange"), + EventBubbles::DoesNotBubble, + EventCancelable::Cancelable, + ); event.fire(self.upcast()); } - fn process_headers_available(&self, - gen_id: GenerationId, - metadata: Result<FetchMetadata, NetworkError>) - -> Result<(), Error> { + fn process_headers_available( + &self, + gen_id: GenerationId, + metadata: Result<FetchMetadata, NetworkError>, + ) -> Result<(), Error> { let metadata = match metadata { Ok(meta) => match meta { FetchMetadata::Unfiltered(m) => m, @@ -854,8 +897,8 @@ impl XMLHttpRequest { FilteredMetadata::Basic(m) => m, FilteredMetadata::Cors(m) => m, FilteredMetadata::Opaque => return Err(Error::Network), - FilteredMetadata::OpaqueRedirect => return Err(Error::Network) - } + FilteredMetadata::OpaqueRedirect => return Err(Error::Network), + }, }, Err(_) => { self.process_partial_response(XHRProgress::Errored(gen_id, Error::Network)); @@ -869,7 +912,8 @@ impl XMLHttpRequest { self.process_partial_response(XHRProgress::HeadersReceived( gen_id, metadata.headers.map(Serde::into_inner), - metadata.status)); + metadata.status, + )); Ok(()) } @@ -877,8 +921,11 @@ impl XMLHttpRequest { self.process_partial_response(XHRProgress::Loading(gen_id, ByteString::new(payload))); } - fn process_response_complete(&self, gen_id: GenerationId, status: Result<(), NetworkError>) - -> ErrorResult { + fn process_response_complete( + &self, + gen_id: GenerationId, + status: Result<(), NetworkError>, + ) -> ErrorResult { match status { Ok(()) => { self.process_partial_response(XHRProgress::Done(gen_id)); @@ -887,7 +934,7 @@ impl XMLHttpRequest { Err(_) => { self.process_partial_response(XHRProgress::Errored(gen_id, Error::Network)); Err(Error::Network) - } + }, } } @@ -937,7 +984,9 @@ impl XMLHttpRequest { self.status.set(code); *self.status_text.borrow_mut() = ByteString::new(reason); }); - headers.as_ref().map(|h| *self.response_headers.borrow_mut() = h.clone()); + headers + .as_ref() + .map(|h| *self.response_headers.borrow_mut() = h.clone()); // Substep 3 if !self.sync.get() { @@ -958,16 +1007,19 @@ impl XMLHttpRequest { &self.global(), atom!("readystatechange"), EventBubbles::DoesNotBubble, - EventCancelable::Cancelable); + EventCancelable::Cancelable, + ); event.fire(self.upcast()); return_if_fetch_was_terminated!(); self.dispatch_response_progress_event(atom!("progress")); } }, XHRProgress::Done(_) => { - assert!(self.ready_state.get() == XMLHttpRequestState::HeadersReceived || + assert!( + self.ready_state.get() == XMLHttpRequestState::HeadersReceived || self.ready_state.get() == XMLHttpRequestState::Loading || - self.sync.get()); + self.sync.get() + ); self.cancel_timeout(); self.canceller.borrow_mut().ignore(); @@ -1012,7 +1064,7 @@ impl XMLHttpRequest { self.dispatch_response_progress_event(Atom::from(errormsg)); return_if_fetch_was_terminated!(); self.dispatch_response_progress_event(atom!("loadend")); - } + }, } } @@ -1024,17 +1076,21 @@ impl XMLHttpRequest { } fn dispatch_progress_event(&self, upload: bool, type_: Atom, loaded: u64, total: Option<u64>) { - let (total_length, length_computable) = if self.response_headers.borrow().has::<ContentEncoding>() { - (0, false) - } else { - (total.unwrap_or(0), total.is_some()) - }; - let progressevent = ProgressEvent::new(&self.global(), - type_, - EventBubbles::DoesNotBubble, - EventCancelable::NotCancelable, - length_computable, loaded, - total_length); + let (total_length, length_computable) = + if self.response_headers.borrow().has::<ContentEncoding>() { + (0, false) + } else { + (total.unwrap_or(0), total.is_some()) + }; + let progressevent = ProgressEvent::new( + &self.global(), + type_, + EventBubbles::DoesNotBubble, + EventCancelable::NotCancelable, + length_computable, + loaded, + total_length, + ); let target = if upload { self.upload.upcast() } else { @@ -1052,7 +1108,11 @@ impl XMLHttpRequest { fn dispatch_response_progress_event(&self, type_: Atom) { let len = self.response.borrow().len() as u64; - let total = self.response_headers.borrow().get::<ContentLength>().map(|x| { **x as u64 }); + let total = self + .response_headers + .borrow() + .get::<ContentLength>() + .map(|x| **x as u64); self.dispatch_progress_event(false, type_, len, total); } fn set_timeout(&self, duration_ms: u32) { @@ -1094,7 +1154,11 @@ impl XMLHttpRequest { return response; } // Step 2 - let mime = self.final_mime_type().as_ref().map(Mime::to_string).unwrap_or("".to_owned()); + let mime = self + .final_mime_type() + .as_ref() + .map(Mime::to_string) + .unwrap_or("".to_owned()); // Step 3, 4 let bytes = self.response.borrow().to_vec(); @@ -1109,16 +1173,18 @@ impl XMLHttpRequest { // Step 1 let created = self.response_arraybuffer.get(); if let Some(nonnull) = NonNull::new(created) { - return Some(nonnull) + return Some(nonnull); } // Step 2 let bytes = self.response.borrow(); rooted!(in(cx) let mut array_buffer = ptr::null_mut::<JSObject>()); - ArrayBuffer::create(cx, CreateWith::Slice(&bytes), array_buffer.handle_mut()).ok().and_then(|()| { - self.response_arraybuffer.set(array_buffer.get()); - Some(NonNull::new_unchecked(array_buffer.get())) - }) + ArrayBuffer::create(cx, CreateWith::Slice(&bytes), array_buffer.handle_mut()) + .ok() + .and_then(|()| { + self.response_arraybuffer.set(array_buffer.get()); + Some(NonNull::new_unchecked(array_buffer.get())) + }) } // https://xhr.spec.whatwg.org/#document-response @@ -1157,7 +1223,9 @@ impl XMLHttpRequest { } }, // Step 4 - _ => { return None; } + _ => { + return None; + }, } // Step 9 temp_doc.set_encoding(charset); @@ -1183,17 +1251,15 @@ impl XMLHttpRequest { // Step 4 fn decode_to_utf16_with_bom_removal(bytes: &[u8], encoding: &'static Encoding) -> Vec<u16> { let mut decoder = encoding.new_decoder_with_bom_removal(); - let capacity = decoder.max_utf16_buffer_length(bytes.len()).expect("Overflow"); + let capacity = decoder + .max_utf16_buffer_length(bytes.len()) + .expect("Overflow"); let mut utf16 = Vec::with_capacity(capacity); - let extra = unsafe { - slice::from_raw_parts_mut(utf16.as_mut_ptr(), capacity) - }; + let extra = unsafe { slice::from_raw_parts_mut(utf16.as_mut_ptr(), capacity) }; let last = true; let (_, read, written, _) = decoder.decode_to_utf16(bytes, extra, last); assert_eq!(read, bytes.len()); - unsafe { - utf16.set_len(written) - } + unsafe { utf16.set_len(written) } utf16 } // https://xhr.spec.whatwg.org/#json-response refers to @@ -1205,10 +1271,12 @@ impl XMLHttpRequest { // Step 5 rooted!(in(cx) let mut rval = UndefinedValue()); unsafe { - if !JS_ParseJSON(cx, - json_text.as_ptr(), - json_text.len() as u32, - rval.handle_mut()) { + if !JS_ParseJSON( + cx, + json_text.as_ptr(), + json_text.len() as u32, + rval.handle_mut(), + ) { JS_ClearPendingException(cx); return NullValue(); } @@ -1225,10 +1293,7 @@ impl XMLHttpRequest { let (decoded, _, _) = charset.decode(&response); let document = self.new_doc(IsHTMLDocument::HTMLDocument); // TODO: Disable scripting while parsing - ServoParser::parse_html_document( - &document, - DOMString::from(decoded), - wr.get_url()); + ServoParser::parse_html_document(&document, DOMString::from(decoded), wr.get_url()); document } @@ -1239,10 +1304,7 @@ impl XMLHttpRequest { let (decoded, _, _) = charset.decode(&response); let document = self.new_doc(IsHTMLDocument::NonHTMLDocument); // TODO: Disable scripting while parsing - ServoParser::parse_xml_document( - &document, - DOMString::from(decoded), - wr.get_url()); + ServoParser::parse_xml_document(&document, DOMString::from(decoded), wr.get_url()); document } @@ -1254,22 +1316,24 @@ impl XMLHttpRequest { let base = wr.get_url(); let parsed_url = match base.join(&self.ResponseURL().0) { Ok(parsed) => Some(parsed), - Err(_) => None // Step 7 + Err(_) => None, // Step 7 }; let content_type = self.final_mime_type(); - Document::new(win, - HasBrowsingContext::No, - parsed_url, - doc.origin().clone(), - is_html_document, - content_type, - None, - DocumentActivity::Inactive, - DocumentSource::FromParser, - docloader, - None, - None, - Default::default()) + Document::new( + win, + HasBrowsingContext::No, + parsed_url, + doc.origin().clone(), + is_html_document, + content_type, + None, + DocumentActivity::Inactive, + DocumentSource::FromParser, + docloader, + None, + None, + Default::default(), + ) } fn filter_response_headers(&self) -> Headers { @@ -1308,15 +1372,13 @@ impl XMLHttpRequest { self.response_status.set(Err(())); } - fn fetch(&self, - init: RequestInit, - global: &GlobalScope) -> ErrorResult { + fn fetch(&self, init: RequestInit, global: &GlobalScope) -> ErrorResult { let xhr = Trusted::new(self); let context = Arc::new(Mutex::new(XHRContext { xhr: xhr, gen_id: self.generation_id.get(), - buf: DomRefCell::new(vec!()), + buf: DomRefCell::new(vec![]), sync_status: DomRefCell::new(None), })); @@ -1329,8 +1391,13 @@ impl XMLHttpRequest { let cancel_receiver = self.canceller.borrow_mut().initialize(); - XMLHttpRequest::initiate_async_xhr(context.clone(), task_source, - global, init, cancel_receiver); + XMLHttpRequest::initiate_async_xhr( + context.clone(), + task_source, + global, + init, + cancel_receiver, + ); if let Some(script_port) = script_port { loop { @@ -1352,11 +1419,9 @@ impl XMLHttpRequest { match self.response_headers.borrow().get() { Some(&ContentType(ref mime)) => { let value = mime.get_param(mime::Attr::Charset); - value.and_then(|value|{ - Encoding::for_label(value.as_bytes()) - }) - } - None => { None } + value.and_then(|value| Encoding::for_label(value.as_bytes())) + }, + None => None, } } } @@ -1366,8 +1431,8 @@ impl XMLHttpRequest { self.override_mime_type.borrow().clone() } else { match self.response_headers.borrow().get() { - Some(&ContentType(ref mime)) => { Some(mime.clone()) }, - None => { None } + Some(&ContentType(ref mime)) => Some(mime.clone()), + None => None, } } } @@ -1405,11 +1470,12 @@ impl Extractable for Blob { } } - impl Extractable for DOMString { fn extract(&self) -> (Vec<u8>, Option<DOMString>) { - (self.as_bytes().to_owned(), - Some(DOMString::from("text/plain;charset=UTF-8"))) + ( + self.as_bytes().to_owned(), + Some(DOMString::from("text/plain;charset=UTF-8")), + ) } } @@ -1417,14 +1483,24 @@ impl Extractable for FormData { fn extract(&self) -> (Vec<u8>, Option<DOMString>) { let boundary = generate_boundary(); let bytes = encode_multipart_form_data(&mut self.datums(), boundary.clone(), UTF_8); - (bytes, Some(DOMString::from(format!("multipart/form-data;boundary={}", boundary)))) + ( + bytes, + Some(DOMString::from(format!( + "multipart/form-data;boundary={}", + boundary + ))), + ) } } impl Extractable for URLSearchParams { fn extract(&self) -> (Vec<u8>, Option<DOMString>) { - (self.serialize_utf8().into_bytes(), - Some(DOMString::from("application/x-www-form-urlencoded;charset=UTF-8"))) + ( + self.serialize_utf8().into_bytes(), + Some(DOMString::from( + "application/x-www-form-urlencoded;charset=UTF-8", + )), + ) } } @@ -1465,7 +1541,8 @@ pub fn is_field_value(slice: &[u8]) -> bool { slice.iter().all(|&x| { // http://tools.ietf.org/html/rfc2616#section-2.2 match x { - 13 => { // CR + 13 => { + // CR if prev == PreviousCharacter::Other || prev == PreviousCharacter::SPHT { prev = PreviousCharacter::CR; true @@ -1473,7 +1550,8 @@ pub fn is_field_value(slice: &[u8]) -> bool { false } }, - 10 => { // LF + 10 => { + // LF if prev == PreviousCharacter::CR { prev = PreviousCharacter::LF; true @@ -1481,7 +1559,8 @@ pub fn is_field_value(slice: &[u8]) -> bool { false } }, - 32 => { // SP + 32 => { + // SP if prev == PreviousCharacter::LF || prev == PreviousCharacter::SPHT { prev = PreviousCharacter::SPHT; true @@ -1495,7 +1574,8 @@ pub fn is_field_value(slice: &[u8]) -> bool { false } }, - 9 => { // HT + 9 => { + // HT if prev == PreviousCharacter::LF || prev == PreviousCharacter::SPHT { prev = PreviousCharacter::SPHT; true @@ -1509,7 +1589,7 @@ pub fn is_field_value(slice: &[u8]) -> bool { prev = PreviousCharacter::Other; true }, - _ => false // Previous character was a CR/LF but not part of the [CRLF] (SP|HT) rule + _ => false, // Previous character was a CR/LF but not part of the [CRLF] (SP|HT) rule } }) } diff --git a/components/script/dom/xmlhttprequesteventtarget.rs b/components/script/dom/xmlhttprequesteventtarget.rs index 51ad62fdaf0..2779b62bc09 100644 --- a/components/script/dom/xmlhttprequesteventtarget.rs +++ b/components/script/dom/xmlhttprequesteventtarget.rs @@ -14,7 +14,7 @@ pub struct XMLHttpRequestEventTarget { impl XMLHttpRequestEventTarget { pub fn new_inherited() -> XMLHttpRequestEventTarget { XMLHttpRequestEventTarget { - eventtarget: EventTarget::new_inherited() + eventtarget: EventTarget::new_inherited(), } } } diff --git a/components/script/dom/xmlhttprequestupload.rs b/components/script/dom/xmlhttprequestupload.rs index 83a7f1d0e77..af377aa7eee 100644 --- a/components/script/dom/xmlhttprequestupload.rs +++ b/components/script/dom/xmlhttprequestupload.rs @@ -11,7 +11,7 @@ use dom_struct::dom_struct; #[dom_struct] pub struct XMLHttpRequestUpload { - eventtarget: XMLHttpRequestEventTarget + eventtarget: XMLHttpRequestEventTarget, } impl XMLHttpRequestUpload { @@ -21,8 +21,10 @@ impl XMLHttpRequestUpload { } } pub fn new(global: &GlobalScope) -> DomRoot<XMLHttpRequestUpload> { - reflect_dom_object(Box::new(XMLHttpRequestUpload::new_inherited()), - global, - XMLHttpRequestUploadBinding::Wrap) + reflect_dom_object( + Box::new(XMLHttpRequestUpload::new_inherited()), + global, + XMLHttpRequestUploadBinding::Wrap, + ) } } |