diff --git a/components/canvas/webgl_paint_task.rs b/components/canvas/webgl_paint_task.rs index b434f468711..aad45c916aa 100644 --- a/components/canvas/webgl_paint_task.rs +++ b/components/canvas/webgl_paint_task.rs @@ -112,14 +112,12 @@ impl WebGLPaintTask { gl::enable_vertex_attrib_array(attrib_id), CanvasWebGLMsg::GetAttribLocation(program_id, name, chan) => self.get_attrib_location(program_id, name, chan), - CanvasWebGLMsg::GetShaderInfoLog(shader_id, chan) => - self.get_shader_info_log(shader_id, chan), CanvasWebGLMsg::GetShaderParameter(shader_id, param_id, chan) => self.get_shader_parameter(shader_id, param_id, chan), CanvasWebGLMsg::GetUniformLocation(program_id, name, chan) => self.get_uniform_location(program_id, name, chan), - CanvasWebGLMsg::CompileShader(shader_id) => - self.compile_shader(shader_id), + CanvasWebGLMsg::CompileShader(shader_id, source) => + self.compile_shader(shader_id, source), CanvasWebGLMsg::CreateBuffer(chan) => self.create_buffer(chan), CanvasWebGLMsg::CreateFramebuffer(chan) => @@ -154,8 +152,6 @@ impl WebGLPaintTask { gl::bind_texture(target, id), CanvasWebGLMsg::LinkProgram(program_id) => gl::link_program(program_id), - CanvasWebGLMsg::ShaderSource(shader_id, source) => - gl::shader_source(shader_id, &[source.as_bytes()]), CanvasWebGLMsg::Uniform4fv(uniform_id, data) => gl::uniform_4f(uniform_id, data[0], data[1], data[2], data[3]), CanvasWebGLMsg::UseProgram(program_id) => @@ -303,11 +299,9 @@ impl WebGLPaintTask { gl::bind_framebuffer(target, id); } - // TODO(ecoal95): This is not spec-compliant, we must check - // the version of GLSL used. This functionality should probably - // be in the WebGLShader object #[inline] - fn compile_shader(&self, shader_id: u32) { + fn compile_shader(&self, shader_id: u32, source: String) { + gl::shader_source(shader_id, &[source.as_bytes()]); gl::compile_shader(shader_id); } @@ -323,13 +317,6 @@ impl WebGLPaintTask { chan.send(attrib_location).unwrap(); } - fn get_shader_info_log(&self, shader_id: u32, chan: IpcSender>) { - // TODO(ecoal95): Right now we always return a value, we should - // check for gl errors and return None there - let info = gl::get_shader_info_log(shader_id); - chan.send(Some(info)).unwrap(); - } - fn get_shader_parameter(&self, shader_id: u32, param_id: u32, diff --git a/components/canvas_traits/lib.rs b/components/canvas_traits/lib.rs index 068eada3d9d..6f2924d2171 100644 --- a/components/canvas_traits/lib.rs +++ b/components/canvas_traits/lib.rs @@ -138,7 +138,7 @@ pub enum CanvasWebGLMsg { DepthRange(f64, f64), Enable(u32), Disable(u32), - CompileShader(u32), + CompileShader(u32, String), CreateBuffer(IpcSender>>), CreateFramebuffer(IpcSender>>), CreateRenderbuffer(IpcSender>>), @@ -157,7 +157,6 @@ pub enum CanvasWebGLMsg { BindTexture(u32, u32), DrawArrays(u32, i32, i32), EnableVertexAttribArray(u32), - GetShaderInfoLog(u32, IpcSender>), GetShaderParameter(u32, u32, IpcSender), GetAttribLocation(u32, String, IpcSender>), GetUniformLocation(u32, String, IpcSender>), @@ -166,7 +165,6 @@ pub enum CanvasWebGLMsg { LineWidth(f32), PixelStorei(u32, i32), LinkProgram(u32), - ShaderSource(u32, String), Uniform4fv(i32, Vec), UseProgram(u32), VertexAttribPointer2f(u32, i32, bool, i32, u32), diff --git a/components/compositing/constellation.rs b/components/compositing/constellation.rs index 497dbcbe81f..8d0c2fee4c6 100644 --- a/components/compositing/constellation.rs +++ b/components/compositing/constellation.rs @@ -54,8 +54,8 @@ use style::viewport::ViewportConstraints; use url::Url; use util::cursor::Cursor; use util::geometry::PagePx; -use util::opts; use util::task::spawn_named; +use util::{opts, prefs}; /// Maintains the pipelines and navigation context and grants permission to composite. /// @@ -891,7 +891,7 @@ impl Constellation { containing_pipeline_id: PipelineId, subpage_id: SubpageId, event: MozBrowserEvent) { - assert!(opts::experimental_enabled()); + assert!(prefs::get_pref("dom.mozbrowser.enabled", false)); // Find the script channel for the given parent pipeline, // and pass the event to that script task. @@ -1373,7 +1373,7 @@ impl Constellation { // https://developer.mozilla.org/en-US/docs/Web/Events/mozbrowserlocationchange fn trigger_mozbrowserlocationchange(&self, pipeline_id: PipelineId) { - if opts::experimental_enabled() { + if prefs::get_pref("dom.mozbrowser.enabled", false) { // Work around borrow checker let event_info = { let pipeline = self.pipeline(pipeline_id); diff --git a/components/compositing/headless.rs b/components/compositing/headless.rs index d56c50de1d2..d8f952beada 100644 --- a/components/compositing/headless.rs +++ b/components/compositing/headless.rs @@ -7,6 +7,7 @@ use windowing::WindowEvent; use euclid::scale_factor::ScaleFactor; use euclid::size::Size2D; +use msg::constellation_msg::AnimationState; use msg::constellation_msg::Msg as ConstellationMsg; use msg::constellation_msg::{ConstellationChan, WindowSizeData}; use profile_traits::mem; @@ -88,6 +89,18 @@ impl CompositorEventListener for NullCompositor { response_chan.send(()).unwrap(); } + Msg::ChangeRunningAnimationsState(pipeline_id, animation_state) => { + match animation_state { + AnimationState::AnimationsPresent | + AnimationState::NoAnimationsPresent | + AnimationState::NoAnimationCallbacksPresent => {} + AnimationState::AnimationCallbacksPresent => { + let msg = ConstellationMsg::TickAnimation(pipeline_id); + self.constellation_chan.0.send(msg).unwrap() + } + } + } + // Explicitly list ignored messages so that when we add a new one, // we'll notice and think about whether it needs a response, like // SetFrameTree. @@ -95,7 +108,6 @@ impl CompositorEventListener for NullCompositor { Msg::InitializeLayersForPipeline(..) | Msg::SetLayerRect(..) | Msg::AssignPaintedBuffers(..) | - Msg::ChangeRunningAnimationsState(..) | Msg::ScrollFragmentPoint(..) | Msg::Status(..) | Msg::LoadStart(..) | diff --git a/components/compositing/lib.rs b/components/compositing/lib.rs index 95eba39c8e7..92a633674b4 100644 --- a/components/compositing/lib.rs +++ b/components/compositing/lib.rs @@ -39,9 +39,9 @@ extern crate clipboard; extern crate time; extern crate url; -#[cfg(target_os="macos")] +#[cfg(target_os = "macos")] extern crate core_graphics; -#[cfg(target_os="macos")] +#[cfg(target_os = "macos")] extern crate core_text; pub use compositor_task::{CompositorEventListener, CompositorProxy, CompositorTask}; diff --git a/components/compositing/pipeline.rs b/components/compositing/pipeline.rs index fe707d5ad3d..59b9b32473d 100644 --- a/components/compositing/pipeline.rs +++ b/components/compositing/pipeline.rs @@ -31,7 +31,7 @@ use url::Url; use util; use util::geometry::{PagePx, ViewportPx}; use util::ipc::OptionalIpcSender; -use util::opts; +use util::prefs; /// A uniquely-identifiable pipeline of script task, layout task, and paint task. pub struct Pipeline { @@ -269,7 +269,7 @@ impl Pipeline { pub fn trigger_mozbrowser_event(&self, subpage_id: SubpageId, event: MozBrowserEvent) { - assert!(opts::experimental_enabled()); + assert!(prefs::get_pref("dom.mozbrowser.enabled", false)); let event = ConstellationControlMsg::MozBrowserEvent(self.id, subpage_id, diff --git a/components/devtools/actor.rs b/components/devtools/actor.rs index c640822d732..ca09e831dbb 100644 --- a/components/devtools/actor.rs +++ b/components/devtools/actor.rs @@ -6,13 +6,11 @@ use devtools_traits::PreciseTime; use rustc_serialize::json; -use std::any::{Any, TypeId}; +use std::any::Any; use std::cell::{Cell, RefCell}; use std::collections::HashMap; -use std::marker::Reflect; -use std::mem::{replace, transmute}; +use std::mem::replace; use std::net::TcpStream; -use std::raw::TraitObject; use std::sync::{Arc, Mutex}; #[derive(PartialEq)] @@ -24,7 +22,7 @@ pub enum ActorMessageStatus { /// A common trait for all devtools actors that encompasses an immutable name /// and the ability to process messages that are directed to particular actors. /// TODO: ensure the name is immutable -pub trait Actor: Any { +pub trait Actor: Any + ActorAsAny { fn handle_message(&self, registry: &ActorRegistry, msg_type: &str, @@ -33,55 +31,14 @@ pub trait Actor: Any { fn name(&self) -> String; } -impl Actor + Send { - /// Returns true if the boxed type is the same as `T` - #[inline] - pub fn is(&self) -> bool { - // Get TypeId of the type this function is instantiated with - let t = TypeId::of::(); +trait ActorAsAny { + fn actor_as_any(&self) -> &Any; + fn actor_as_any_mut(&mut self) -> &mut Any; +} - // Get TypeId of the type in the trait object - let boxed = self.get_type_id(); - - // Compare both TypeIds on equality - t == boxed - } - - /// Returns some reference to the boxed value if it is of type `T`, or - /// `None` if it isn't. - #[inline] - #[allow(unsafe_code)] - pub fn downcast_ref(&self) -> Option<&T> { - if self.is::() { - unsafe { - // Get the raw representation of the trait object - let to: TraitObject = transmute(self); - - // Extract the data pointer - Some(transmute(to.data)) - } - } else { - None - } - } - - /// Returns some mutable reference to the boxed value if it is of type `T`, or - /// `None` if it isn't. - #[inline] - #[allow(unsafe_code)] - pub fn downcast_mut(&mut self) -> Option<&mut T> { - if self.is::() { - unsafe { - // Get the raw representation of the trait object - let to: TraitObject = transmute(self); - - // Extract the data pointer - Some(transmute(to.data)) - } - } else { - None - } - } +impl ActorAsAny for T { + fn actor_as_any(&self) -> &Any { self } + fn actor_as_any_mut(&mut self) -> &mut Any { self } } /// A list of known, owned actors. @@ -179,15 +136,15 @@ impl ActorRegistry { } /// Find an actor by registered name - pub fn find<'a, T: Reflect + 'static>(&'a self, name: &str) -> &'a T { + pub fn find<'a, T: Any>(&'a self, name: &str) -> &'a T { let actor = self.actors.get(&name.to_string()).unwrap(); - actor.downcast_ref::().unwrap() + actor.actor_as_any().downcast_ref::().unwrap() } /// Find an actor by registered name - pub fn find_mut<'a, T: Reflect + 'static>(&'a mut self, name: &str) -> &'a mut T { + pub fn find_mut<'a, T: Any>(&'a mut self, name: &str) -> &'a mut T { let actor = self.actors.get_mut(&name.to_string()).unwrap(); - actor.downcast_mut::().unwrap() + actor.actor_as_any_mut().downcast_mut::().unwrap() } /// Attempt to process a message as directed by its `to` property. If the actor is not diff --git a/components/devtools/actors/console.rs b/components/devtools/actors/console.rs index 7c859369274..30c0b98d77a 100644 --- a/components/devtools/actors/console.rs +++ b/components/devtools/actors/console.rs @@ -17,9 +17,9 @@ use devtools_traits::EvaluateJSReply::{StringValue, BooleanValue, ActorValue}; use devtools_traits::{CachedConsoleMessageTypes, DevtoolScriptControlMsg, PAGE_ERROR, CONSOLE_API}; use msg::constellation_msg::PipelineId; -use core::cell::RefCell; use ipc_channel::ipc::{self, IpcSender}; use rustc_serialize::json::{self, Json, ToJson}; +use std::cell::RefCell; use std::collections::BTreeMap; use std::net::TcpStream; use std::sync::mpsc::channel; diff --git a/components/devtools/actors/timeline.rs b/components/devtools/actors/timeline.rs index 17327b1043e..b38b85a97b5 100644 --- a/components/devtools/actors/timeline.rs +++ b/components/devtools/actors/timeline.rs @@ -6,7 +6,6 @@ use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use msg::constellation_msg::PipelineId; use rustc_serialize::{json, Encoder, Encodable}; use std::cell::RefCell; -use std::collections::{HashMap, VecDeque}; use std::net::TcpStream; use std::sync::mpsc::channel; use std::sync::{Arc, Mutex}; @@ -17,7 +16,7 @@ use actors::framerate::FramerateActor; use actors::memory::{MemoryActor, TimelineMemoryReply}; use devtools_traits::DevtoolScriptControlMsg; use devtools_traits::DevtoolScriptControlMsg::{SetTimelineMarkers, DropTimelineMarkers}; -use devtools_traits::{PreciseTime, TimelineMarker, TracingMetadata, TimelineMarkerType}; +use devtools_traits::{PreciseTime, TimelineMarker, TimelineMarkerType}; use protocol::JsonPacketStream; use util::task; @@ -148,72 +147,15 @@ impl TimelineActor { return; } - /// Select root(with depth 0) TimelineMarker pair (IntervalStart + IntervalEnd) - /// from queue and add marker to emitter - /// Return true if closed (IntervalStart + IntervalEnd) pair was founded - fn group(queue: &mut VecDeque, depth: usize, - start_payload: Option, emitter: &Emitter, - markers: &mut Vec) -> bool { - - if let Some(start_payload) = start_payload { - if start_payload.metadata != TracingMetadata::IntervalStart { - panic!("Start payload doesn't have metadata IntervalStart"); - } - - if let Some(end_payload) = queue.pop_front() { - match end_payload.metadata { - TracingMetadata::IntervalEnd => { - if depth == 0 { - // Emit TimelineMarkerReply, pair was found - markers.push(emitter.marker(start_payload, end_payload)); - } - return true; - } - TracingMetadata::IntervalStart => { - if group(queue, depth + 1, Some(end_payload), emitter, markers) { - return group(queue, depth, Some(start_payload), emitter, markers); - } else { - queue.push_front(start_payload); - } - } - _ => panic!("Unknown tracingMetadata") - } - } else { - queue.push_front(start_payload); - } - } - - false - } - task::spawn_named("PullTimelineMarkers".to_string(), move || { - let mut queues = HashMap::new(); - queues.insert("Reflow".to_string(), VecDeque::new()); - queues.insert("DOMEvent".to_string(), VecDeque::new()); - loop { if !*is_recording.lock().unwrap() { break; } - // Creating queues by marker.name - loop { - match receiver.try_recv() { - Ok(marker) => { - if let Some(list) = queues.get_mut(&marker.name) { - list.push_back(marker); - } - } - - Err(_) => break - } - } - - // Emit all markers let mut markers = vec![]; - for (_, queue) in &mut queues { - let start_payload = queue.pop_front(); - group(queue, 0, start_payload, &emitter, &mut markers); + while let Ok(marker) = receiver.try_recv() { + markers.push(emitter.marker(marker)); } emitter.send(markers); @@ -336,14 +278,13 @@ impl Emitter { } } - fn marker(&self, start_payload: TimelineMarker, end_payload: TimelineMarker) - -> TimelineMarkerReply { + fn marker(&self, payload: TimelineMarker) -> TimelineMarkerReply { TimelineMarkerReply { - name: start_payload.name, - start: HighResolutionStamp::new(self.start_stamp, start_payload.time), - end: HighResolutionStamp::new(self.start_stamp, end_payload.time), - stack: start_payload.stack, - endStack: end_payload.stack, + name: payload.name, + start: HighResolutionStamp::new(self.start_stamp, payload.start_time), + end: HighResolutionStamp::new(self.start_stamp, payload.end_time), + stack: payload.start_stack, + endStack: payload.end_stack, } } diff --git a/components/devtools/lib.rs b/components/devtools/lib.rs index 07a3889d699..4be05c919d1 100644 --- a/components/devtools/lib.rs +++ b/components/devtools/lib.rs @@ -11,12 +11,8 @@ #![crate_type = "rlib"] #![feature(box_syntax)] -#![feature(core)] #![feature(custom_derive)] -#![feature(get_type_id)] #![feature(plugin)] -#![feature(raw)] -#![feature(reflect_marker)] #![plugin(serde_macros)] #![allow(non_snake_case)] @@ -25,7 +21,6 @@ #[macro_use] extern crate log; -extern crate core; extern crate devtools_traits; extern crate rustc_serialize; extern crate ipc_channel; diff --git a/components/devtools_traits/lib.rs b/components/devtools_traits/lib.rs index 8df97634fad..c8889fcd5fb 100644 --- a/components/devtools_traits/lib.rs +++ b/components/devtools_traits/lib.rs @@ -124,21 +124,19 @@ pub struct NodeInfo { pub incompleteValue: bool, } -#[derive(PartialEq, Eq, Deserialize, Serialize)] -pub enum TracingMetadata { - Default, - IntervalStart, - IntervalEnd, - Event, - EventBacktrace, +pub struct StartedTimelineMarker { + name: String, + start_time: PreciseTime, + start_stack: Option>, } #[derive(Deserialize, Serialize)] pub struct TimelineMarker { pub name: String, - pub metadata: TracingMetadata, - pub time: PreciseTime, - pub stack: Option>, + pub start_time: PreciseTime, + pub start_stack: Option>, + pub end_time: PreciseTime, + pub end_stack: Option>, } #[derive(PartialEq, Eq, Hash, Clone, Deserialize, Serialize)] @@ -270,12 +268,23 @@ pub enum NetworkEvent { } impl TimelineMarker { - pub fn new(name: String, metadata: TracingMetadata) -> TimelineMarker { - TimelineMarker { + pub fn start(name: String) -> StartedTimelineMarker { + StartedTimelineMarker { name: name, - metadata: metadata, - time: PreciseTime::now(), - stack: None, + start_time: PreciseTime::now(), + start_stack: None, + } + } +} + +impl StartedTimelineMarker { + pub fn end(self) -> TimelineMarker { + TimelineMarker { + name: self.name, + start_time: self.start_time, + start_stack: self.start_stack, + end_time: PreciseTime::now(), + end_stack: None, } } } diff --git a/components/gfx/font.rs b/components/gfx/font.rs index fd17fa4e467..ba11c2a63cc 100644 --- a/components/gfx/font.rs +++ b/components/gfx/font.rs @@ -101,13 +101,13 @@ pub struct Font { bitflags! { flags ShapingFlags: u8 { - #[doc="Set if the text is entirely whitespace."] + #[doc = "Set if the text is entirely whitespace."] const IS_WHITESPACE_SHAPING_FLAG = 0x01, - #[doc="Set if we are to ignore ligatures."] + #[doc = "Set if we are to ignore ligatures."] const IGNORE_LIGATURES_SHAPING_FLAG = 0x02, - #[doc="Set if we are to disable kerning."] + #[doc = "Set if we are to disable kerning."] const DISABLE_KERNING_SHAPING_FLAG = 0x04, - #[doc="Text direction is right-to-left."] + #[doc = "Text direction is right-to-left."] const RTL_FLAG = 0x08, } } diff --git a/components/gfx/font_context.rs b/components/gfx/font_context.rs index 18ee5e9ff42..640b2b8250c 100644 --- a/components/gfx/font_context.rs +++ b/components/gfx/font_context.rs @@ -31,16 +31,16 @@ use std::sync::Arc; use azure::azure_hl::BackendType; use azure::scaled_font::ScaledFont; -#[cfg(any(target_os="linux", target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] use azure::scaled_font::FontInfo; -#[cfg(any(target_os="linux", target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] fn create_scaled_font(template: &Arc, pt_size: Au) -> ScaledFont { ScaledFont::new(BackendType::Skia, FontInfo::FontData(&template.bytes), pt_size.to_f32_px()) } -#[cfg(target_os="macos")] +#[cfg(target_os = "macos")] fn create_scaled_font(template: &Arc, pt_size: Au) -> ScaledFont { let cgfont = template.ctfont().as_ref().unwrap().copy_to_CGFont(); ScaledFont::new(BackendType::Skia, &cgfont, pt_size.to_f32_px()) diff --git a/components/gfx/lib.rs b/components/gfx/lib.rs index 6ffbe36fb5b..db73b9b200d 100644 --- a/components/gfx/lib.rs +++ b/components/gfx/lib.rs @@ -3,12 +3,12 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(arc_weak)] -#![cfg_attr(any(target_os="linux", target_os = "android"), feature(box_raw))] +#![cfg_attr(any(target_os = "linux", target_os = "android"), feature(box_raw))] #![feature(box_syntax)] #![feature(custom_attribute)] #![feature(custom_derive)] #![feature(hashmap_hasher)] -#![cfg_attr(any(target_os="linux", target_os = "android"), feature(heap_api))] +#![cfg_attr(any(target_os = "linux", target_os = "android"), feature(heap_api))] #![feature(mpsc_select)] #![feature(plugin)] #![feature(str_char)] @@ -55,23 +55,23 @@ extern crate canvas_traits; extern crate harfbuzz; // Linux and Android-specific library dependencies -#[cfg(any(target_os="linux", target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] extern crate fontconfig; -#[cfg(any(target_os="linux", target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] extern crate freetype; // Mac OS-specific library dependencies -#[cfg(target_os="macos")] extern crate core_foundation; -#[cfg(target_os="macos")] extern crate core_graphics; -#[cfg(target_os="macos")] extern crate core_text; +#[cfg(target_os = "macos")] extern crate core_foundation; +#[cfg(target_os = "macos")] extern crate core_graphics; +#[cfg(target_os = "macos")] extern crate core_text; pub use paint_context::PaintContext; // Private painting modules mod paint_context; -#[path="display_list/mod.rs"] +#[path = "display_list/mod.rs"] pub mod display_list; pub mod paint_task; @@ -85,7 +85,7 @@ pub mod font_template; mod filters; // Platform-specific implementations. -#[path="platform/mod.rs"] +#[path = "platform/mod.rs"] pub mod platform; // Text diff --git a/components/gfx/paint_context.rs b/components/gfx/paint_context.rs index a96d413cafc..9ebe86b1f38 100644 --- a/components/gfx/paint_context.rs +++ b/components/gfx/paint_context.rs @@ -72,6 +72,19 @@ enum DashSize { DashedBorder = 3 } +#[derive(Copy, Clone, Debug)] +struct Ellipse { + origin: Point2D, + width: f32, + height: f32, +} + +#[derive(Copy, Clone, Debug)] +struct Line { + start: Point2D, + end: Point2D, +} + impl<'a> PaintContext<'a> { pub fn draw_target(&self) -> &DrawTarget { &self.draw_target @@ -355,6 +368,104 @@ impl<'a> PaintContext<'a> { self.draw_target.push_clip(&path_builder.finish()); } + fn solve_quadratic(a: f32, b: f32, c: f32) -> (Option, Option) { + let discriminant = b * b - 4. * a * c; + if discriminant < 0. { + return (None, None); + } + let x1 = (-b + discriminant.sqrt())/(2. * a); + let x2 = (-b - discriminant.sqrt())/(2. * a); + if discriminant == 0. { + return (Some(x1), None); + } + return (Some(x1), Some(x2)); + } + + fn intersect_ellipse_line(e: Ellipse, l: Line) -> (Option>, Option>) { + debug_assert!(l.end.x - l.start.x > f32::EPSILON, "Error line segment end.x > start.x!!"); + // shift the origin to center of the ellipse. + let line = Line { start: l.start - e.origin, + end: l.end - e.origin }; + + let a = (line.end.y - line.start.y)/(line.end.x - line.start.x); + let b = line.start.y - (a * line.start.x); + // given the equation of a line, + // y = a * x + b, + // and the equation of an ellipse, + // x^2/w^2 + y^2/h^2 = 1, + // substitute y = a * x + b, giving + // x^2/w^2 + (a^2x^2 + 2abx + b^2)/h^2 = 1 + // then simplify to + // (h^2 + w^2a^2)x^2 + 2abw^2x + (b^2w^2 - w^2h^2) = 0 + // finally solve for w using the quadratic equation. + let w = e.width; + let h = e.height; + let quad_a = h * h + w * w * a * a; + let quad_b = 2. * a * b * w * w; + let quad_c = b * b * w * w - w * w * h * h; + let intersections = PaintContext::solve_quadratic(quad_a, quad_b, quad_c); + match intersections { + (Some(x0), Some(x1)) => { + let mut p0 = Point2D::new(x0, a * x0 + b) + e.origin; + let mut p1 = Point2D::new(x1, a * x1 + b) + e.origin; + if x0 > x1 { + mem::swap(&mut p0, &mut p1); + } + (Some(p0), Some(p1)) + }, + (Some(x0), None) => { + let p = Point2D::new(x0, a * x0 + b) + e.origin; + (Some(p), None) + }, + (None, Some(x1)) => { + let p = Point2D::new(x1, a * x1 + b) + e.origin; + (Some(p), None) + }, + (None, None) => (None, None), + } + } + + // Given an ellipse and line segment, the line segment may intersect the + // ellipse at 0, 1, or 2 points. We compute those intersection points. + // For each intersection point the angle of the point on the ellipse relative to + // the top|bottom of the ellipse is computed. + // Examples: + // - intersection at ellipse.center + (0, ellipse.height), the angle is 0 rad. + // - intersection at ellipse.center + (0, -ellipse.height), the angle is 0 rad. + // - intersection at ellipse.center + (+-ellipse.width, 0), the angle is pi/2. + fn ellipse_line_intersection_angles(e: Ellipse, l: Line) + -> (Option<(Point2D, f32)>, Option<(Point2D, f32)>) { + fn point_angle(e: Ellipse, intersect_point: Point2D) -> f32 { + ((intersect_point.y - e.origin.y).abs() / e.height).asin() + } + + let intersection = PaintContext::intersect_ellipse_line(e, l); + match intersection { + (Some(p0), Some(p1)) => (Some((p0, point_angle(e, p0))), Some((p1, point_angle(e, p1)))), + (Some(p0), None) => (Some((p0, point_angle(e, p0))), None), + (None, Some(p1)) => (None, Some((p1, point_angle(e, p1)))), + (None, None) => (None, None), + } + } + + fn ellipse_rightmost_line_intersection_angle(e: Ellipse, l: Line) -> Option { + match PaintContext::ellipse_line_intersection_angles(e, l) { + (Some((p0, angle0)), Some((p1, _))) if p0.x > p1.x => Some(angle0), + (_, Some((_, angle1))) => Some(angle1), + (Some((_, angle0)), None) => Some(angle0), + (None, None) => None, + } + } + + fn ellipse_leftmost_line_intersection_angle(e: Ellipse, l: Line) -> Option { + match PaintContext::ellipse_line_intersection_angles(e, l) { + (Some((p0, angle0)), Some((p1, _))) if p0.x < p1.x => Some(angle0), + (_, Some((_, angle1))) => Some(angle1), + (Some((_, angle0)), None) => Some(angle0), + (None, None) => None, + } + } + // The following comment is wonderful, and stolen from // gecko:gfx/thebes/gfxContext.cpp:RoundedRectangle for reference. // @@ -450,6 +561,11 @@ impl<'a> PaintContext<'a> { let box_BL = box_TL + Point2D::new(0.0, bounds.size.height); let box_BR = box_TL + Point2D::new(bounds.size.width, bounds.size.height); + let inner_TL = box_TL + Point2D::new(border.left, border.top); + let inner_TR = box_TR + Point2D::new(-border.right, border.top); + let inner_BR = box_BR + Point2D::new(-border.right, -border.bottom); + let inner_BL = box_BL + Point2D::new(border.left, -border.bottom); + let rad_R: AzFloat = 0.; let rad_BR = rad_R + f32::consts::FRAC_PI_4; let rad_B = rad_BR + f32::consts::FRAC_PI_4; @@ -457,7 +573,6 @@ impl<'a> PaintContext<'a> { let rad_L = rad_BL + f32::consts::FRAC_PI_4; let rad_TL = rad_L + f32::consts::FRAC_PI_4; let rad_T = rad_TL + f32::consts::FRAC_PI_4; - let rad_TR = rad_T + f32::consts::FRAC_PI_4; fn dx(x: AzFloat) -> Point2D { Point2D::new(x, 0.) @@ -475,12 +590,41 @@ impl<'a> PaintContext<'a> { Point2D::new(0., if cond { dy } else { 0. }) } + fn compatible_borders_corner(border1_width: f32, border2_width: f32) -> bool { + (border1_width - border2_width).abs() <= f32::EPSILON + } + + let distance_to_elbow_TL = + if border.top == border.left { + (radius.top_left - border.top).max(0.) + } else { + 0. + }; + let distance_to_elbow_TR = + if border.top == border.right { + (radius.top_right - border.top).max(0.) + } else { + 0. + }; + let distance_to_elbow_BR = + if border.right == border.bottom { + (radius.bottom_right - border.bottom).max(0.) + } else { + 0. + }; + let distance_to_elbow_BL = + if border.left == border.bottom { + (radius.bottom_left - border.bottom).max(0.) + } else { + 0. + }; + match direction { Direction::Top => { let edge_TL = box_TL + dx(radius.top_left.max(border.left)); let edge_TR = box_TR + dx(-radius.top_right.max(border.right)); - let edge_BR = edge_TR + dy(border.top); - let edge_BL = edge_TL + dy(border.top); + let edge_BR = box_TR + dx(-border.right - distance_to_elbow_TR) + dy(border.top); + let edge_BL = box_TL + dx(border.left + distance_to_elbow_TL) + dy(border.top); let corner_TL = edge_TL + dx_if(radius.top_left == 0., -border.left); let corner_TR = edge_TR + dx_if(radius.top_right == 0., border.right); @@ -497,11 +641,18 @@ impl<'a> PaintContext<'a> { // the origin is the center of the arcs we're about to draw. let origin = edge_TR + Point2D::new((border.right - radius.top_right).max(0.), radius.top_right); - // the elbow is the inside of the border's curve. - let distance_to_elbow = (radius.top_right - border.top).max(0.); + let angle = if compatible_borders_corner(border.top, border.right) { + f32::consts::FRAC_PI_4 + } else { + let line = Line { start: inner_TR, end: box_TR }; + let ellipse = Ellipse { origin: origin, width: radius.top_right, height: radius.top_right }; + PaintContext::ellipse_rightmost_line_intersection_angle(ellipse, line).unwrap() + }; - path_builder.arc(origin, radius.top_right, rad_T, rad_TR, false); - path_builder.arc(origin, distance_to_elbow, rad_TR, rad_T, true); + path_builder.arc(origin, radius.top_right, rad_T, rad_R - angle, false); + if distance_to_elbow_TR != 0. { + path_builder.arc(origin, distance_to_elbow_TR, rad_R - angle, rad_T, true); + } } match mode { @@ -514,18 +665,26 @@ impl<'a> PaintContext<'a> { if radius.top_left != 0. { let origin = edge_TL + Point2D::new(-(border.left - radius.top_left).max(0.), - radius.top_left); - let distance_to_elbow = (radius.top_left - border.top).max(0.); + radius.top_left); + let angle = if compatible_borders_corner(border.top, border.left) { + f32::consts::FRAC_PI_4 + } else { + let line = Line { start: box_TL, end: inner_TL }; + let ellipse = Ellipse { origin: origin, width: radius.top_left, height: radius.top_left }; + PaintContext::ellipse_leftmost_line_intersection_angle(ellipse, line).unwrap() + }; - path_builder.arc(origin, distance_to_elbow, rad_T, rad_TL, true); - path_builder.arc(origin, radius.top_left, rad_TL, rad_T, false); + if distance_to_elbow_TL != 0. { + path_builder.arc(origin, distance_to_elbow_TL, rad_T, rad_L + angle, true); + } + path_builder.arc(origin, radius.top_left, rad_L + angle, rad_T, false); } } Direction::Left => { let edge_TL = box_TL + dy(radius.top_left.max(border.top)); let edge_BL = box_BL + dy(-radius.bottom_left.max(border.bottom)); - let edge_TR = edge_TL + dx(border.left); - let edge_BR = edge_BL + dx(border.left); + let edge_TR = box_TL + dx(border.left) + dy(border.top + distance_to_elbow_TL); + let edge_BR = box_BL + dx(border.left) + dy(-border.bottom - distance_to_elbow_BL); let corner_TL = edge_TL + dy_if(radius.top_left == 0., -border.top); let corner_BL = edge_BL + dy_if(radius.bottom_left == 0., border.bottom); @@ -540,11 +699,20 @@ impl<'a> PaintContext<'a> { if radius.top_left != 0. { let origin = edge_TL + Point2D::new(radius.top_left, - -(border.top - radius.top_left).max(0.)); - let distance_to_elbow = (radius.top_left - border.left).max(0.); + -(border.top - radius.top_left).max(0.)); - path_builder.arc(origin, radius.top_left, rad_L, rad_TL, false); - path_builder.arc(origin, distance_to_elbow, rad_TL, rad_L, true); + let angle = if compatible_borders_corner(border.top, border.left) { + f32::consts::FRAC_PI_4 + } else { + let line = Line { start: box_TL, end: inner_TL }; + let ellipse = Ellipse { origin: origin, width: radius.top_left, height: radius.top_left }; + PaintContext::ellipse_leftmost_line_intersection_angle(ellipse, line).unwrap() + }; + + path_builder.arc(origin, radius.top_left, rad_L, rad_L + angle, false); + if distance_to_elbow_TL != 0. { + path_builder.arc(origin, distance_to_elbow_TL, rad_L + angle, rad_L, true); + } } match mode { @@ -558,18 +726,28 @@ impl<'a> PaintContext<'a> { if radius.bottom_left != 0. { let origin = edge_BL + Point2D::new(radius.bottom_left, - (border.bottom - radius.bottom_left).max(0.)); - let distance_to_elbow = (radius.bottom_left - border.left).max(0.); + (border.bottom - radius.bottom_left).max(0.)); + let angle = if compatible_borders_corner(border.bottom, border.left) { + f32::consts::FRAC_PI_4 + } else { + let line = Line { start: box_BL, end: inner_BL }; + let ellipse = Ellipse { origin: origin, + width: radius.bottom_left, + height: radius.bottom_left }; + PaintContext::ellipse_leftmost_line_intersection_angle(ellipse, line).unwrap() + }; - path_builder.arc(origin, distance_to_elbow, rad_L, rad_BL, true); - path_builder.arc(origin, radius.bottom_left, rad_BL, rad_L, false); + if distance_to_elbow_BL != 0. { + path_builder.arc(origin, distance_to_elbow_BL, rad_L, rad_L - angle, true); + } + path_builder.arc(origin, radius.bottom_left, rad_L - angle, rad_L, false); } } Direction::Right => { let edge_TR = box_TR + dy(radius.top_right.max(border.top)); let edge_BR = box_BR + dy(-radius.bottom_right.max(border.bottom)); - let edge_TL = edge_TR + dx(-border.right); - let edge_BL = edge_BR + dx(-border.right); + let edge_TL = box_TR + dx(-border.right) + dy(border.top + distance_to_elbow_TR); + let edge_BL = box_BR + dx(-border.right) + dy(-border.bottom - distance_to_elbow_BR); let corner_TR = edge_TR + dy_if(radius.top_right == 0., -border.top); let corner_BR = edge_BR + dy_if(radius.bottom_right == 0., border.bottom); @@ -585,10 +763,18 @@ impl<'a> PaintContext<'a> { if radius.top_right != 0. { let origin = edge_TR + Point2D::new(-radius.top_right, -(border.top - radius.top_right).max(0.)); - let distance_to_elbow = (radius.top_right - border.right).max(0.); + let angle = if compatible_borders_corner(border.top, border.right) { + f32::consts::FRAC_PI_4 + } else { + let line = Line { start: inner_TR, end: box_TR }; + let ellipse = Ellipse { origin: origin, width: radius.top_right, height: radius.top_right }; + PaintContext::ellipse_rightmost_line_intersection_angle(ellipse, line).unwrap() + }; - path_builder.arc(origin, distance_to_elbow, rad_R, rad_TR, true); - path_builder.arc(origin, radius.top_right, rad_TR, rad_R, false); + if distance_to_elbow_TR != 0. { + path_builder.arc(origin, distance_to_elbow_TR, rad_R, rad_R - angle, true); + } + path_builder.arc(origin, radius.top_right, rad_R - angle, rad_R, false); } match mode { @@ -602,18 +788,28 @@ impl<'a> PaintContext<'a> { if radius.bottom_right != 0. { let origin = edge_BR + Point2D::new(-radius.bottom_right, - (border.bottom - radius.bottom_right).max(0.)); - let distance_to_elbow = (radius.bottom_right - border.right).max(0.); + (border.bottom - radius.bottom_right).max(0.)); + let angle = if compatible_borders_corner(border.bottom, border.right) { + f32::consts::FRAC_PI_4 + } else { + let line = Line { start: inner_BR, end: box_BR }; + let ellipse = Ellipse { origin: origin, + width: radius.bottom_right, + height: radius.bottom_right }; + PaintContext::ellipse_rightmost_line_intersection_angle(ellipse, line).unwrap() + }; - path_builder.arc(origin, radius.bottom_right, rad_R, rad_BR, false); - path_builder.arc(origin, distance_to_elbow, rad_BR, rad_R, true); + path_builder.arc(origin, radius.bottom_right, rad_R, rad_R + angle, false); + if distance_to_elbow_BR != 0. { + path_builder.arc(origin, distance_to_elbow_BR, rad_R + angle, rad_R, true); + } } } Direction::Bottom => { let edge_BL = box_BL + dx(radius.bottom_left.max(border.left)); let edge_BR = box_BR + dx(-radius.bottom_right.max(border.right)); - let edge_TL = edge_BL + dy(-border.bottom); - let edge_TR = edge_BR + dy(-border.bottom); + let edge_TL = box_BL + dy(-border.bottom) + dx(border.left + distance_to_elbow_BL); + let edge_TR = box_BR + dy(-border.bottom) + dx(-border.right - distance_to_elbow_BR); let corner_BR = edge_BR + dx_if(radius.bottom_right == 0., border.right); let corner_BL = edge_BL + dx_if(radius.bottom_left == 0., -border.left); @@ -629,10 +825,20 @@ impl<'a> PaintContext<'a> { if radius.bottom_right != 0. { let origin = edge_BR + Point2D::new((border.right - radius.bottom_right).max(0.), -radius.bottom_right); - let distance_to_elbow = (radius.bottom_right - border.bottom).max(0.); + let angle = if compatible_borders_corner(border.bottom, border.right) { + f32::consts::FRAC_PI_4 + } else { + let line = Line { start: inner_BR, end: box_BR }; + let ellipse = Ellipse { origin: origin, + width: radius.bottom_right, + height: radius.bottom_right }; + PaintContext::ellipse_rightmost_line_intersection_angle(ellipse, line).unwrap() + }; - path_builder.arc(origin, distance_to_elbow, rad_B, rad_BR, true); - path_builder.arc(origin, radius.bottom_right, rad_BR, rad_B, false); + if distance_to_elbow_BR != 0. { + path_builder.arc(origin, distance_to_elbow_BR, rad_B, rad_R + angle, true); + } + path_builder.arc(origin, radius.bottom_right, rad_R + angle, rad_B, false); } match mode { @@ -645,11 +851,21 @@ impl<'a> PaintContext<'a> { if radius.bottom_left != 0. { let origin = edge_BL - Point2D::new((border.left - radius.bottom_left).max(0.), - radius.bottom_left); - let distance_to_elbow = (radius.bottom_left - border.bottom).max(0.); + radius.bottom_left); + let angle = if compatible_borders_corner(border.bottom, border.left) { + f32::consts::FRAC_PI_4 + } else { + let line = Line { start: box_BL, end: inner_BL }; + let ellipse = Ellipse { origin: origin, + width: radius.bottom_left, + height: radius.bottom_left }; + PaintContext::ellipse_leftmost_line_intersection_angle(ellipse, line).unwrap() + }; - path_builder.arc(origin, radius.bottom_left, rad_B, rad_BL, false); - path_builder.arc(origin, distance_to_elbow, rad_BL, rad_B, true); + path_builder.arc(origin, radius.bottom_left, rad_B, rad_L - angle, false); + if distance_to_elbow_BL != 0. { + path_builder.arc(origin, distance_to_elbow_BL, rad_L - angle, rad_B, true); + } } } } diff --git a/components/gfx/platform/freetype/font_list.rs b/components/gfx/platform/freetype/font_list.rs index f3557d7dd2f..9e0a5177312 100644 --- a/components/gfx/platform/freetype/font_list.rs +++ b/components/gfx/platform/freetype/font_list.rs @@ -139,7 +139,7 @@ pub fn get_system_default_family(generic_name: &str) -> Option { } } -#[cfg(target_os="linux")] +#[cfg(target_os = "linux")] pub fn get_last_resort_font_families() -> Vec { vec!( "Fira Sans".to_owned(), @@ -148,7 +148,7 @@ pub fn get_last_resort_font_families() -> Vec { ) } -#[cfg(target_os="android")] +#[cfg(target_os = "android")] pub fn get_last_resort_font_families() -> Vec { vec!("Roboto".to_owned()) } diff --git a/components/gfx/platform/macos/font.rs b/components/gfx/platform/macos/font.rs index b96f217e0c9..eb33e326230 100644 --- a/components/gfx/platform/macos/font.rs +++ b/components/gfx/platform/macos/font.rs @@ -33,11 +33,6 @@ pub struct FontTable { data: CFData, } -// Noncopyable. -impl Drop for FontTable { - fn drop(&mut self) {} -} - impl FontTable { pub fn wrap(data: CFData) -> FontTable { FontTable { data: data } diff --git a/components/gfx/platform/mod.rs b/components/gfx/platform/mod.rs index f3bc3f6ec08..085da7cc932 100644 --- a/components/gfx/platform/mod.rs +++ b/components/gfx/platform/mod.rs @@ -2,13 +2,13 @@ * 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/. */ -#[cfg(any(target_os="linux", target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] pub use platform::freetype::{font, font_context, font_list, font_template}; -#[cfg(target_os="macos")] +#[cfg(target_os = "macos")] pub use platform::macos::{font, font_context, font_list, font_template}; -#[cfg(any(target_os="linux", target_os = "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] pub mod freetype { pub mod font; pub mod font_context; @@ -16,7 +16,7 @@ pub mod freetype { pub mod font_template; } -#[cfg(target_os="macos")] +#[cfg(target_os = "macos")] pub mod macos { pub mod font; pub mod font_context; diff --git a/components/gfx/text/glyph.rs b/components/gfx/text/glyph.rs index 29918e5d2d9..d27128014b5 100644 --- a/components/gfx/text/glyph.rs +++ b/components/gfx/text/glyph.rs @@ -58,17 +58,7 @@ impl GlyphEntry { starts_ligature, glyph_count); - let mut val = FLAG_NOT_MISSING; - - if !starts_cluster { - val |= FLAG_NOT_CLUSTER_START; - } - if !starts_ligature { - val |= FLAG_NOT_LIGATURE_GROUP_START; - } - val |= (glyph_count as u32) << GLYPH_COUNT_SHIFT; - - GlyphEntry::new(val) + GlyphEntry::new(glyph_count as u32) } /// Create a GlyphEntry for the case where glyphs couldn't be found for the specified @@ -76,55 +66,22 @@ impl GlyphEntry { fn missing(glyph_count: usize) -> GlyphEntry { assert!(glyph_count <= u16::MAX as usize); - GlyphEntry::new((glyph_count as u32) << GLYPH_COUNT_SHIFT) + GlyphEntry::new(glyph_count as u32) } } /// The id of a particular glyph within a font pub type GlyphId = u32; -// TODO: unify with bit flags? -#[derive(PartialEq, Copy, Clone)] -pub enum BreakType { - None, - Normal, - Hyphen, -} - -static BREAK_TYPE_NONE: u8 = 0x0; -static BREAK_TYPE_NORMAL: u8 = 0x1; -static BREAK_TYPE_HYPHEN: u8 = 0x2; - -fn break_flag_to_enum(flag: u8) -> BreakType { - if (flag & BREAK_TYPE_NORMAL) != 0 { - BreakType::Normal - } else if (flag & BREAK_TYPE_HYPHEN) != 0 { - BreakType::Hyphen - } else { - BreakType::None - } -} - -fn break_enum_to_flag(e: BreakType) -> u8 { - match e { - BreakType::None => BREAK_TYPE_NONE, - BreakType::Normal => BREAK_TYPE_NORMAL, - BreakType::Hyphen => BREAK_TYPE_HYPHEN, - } -} - // TODO: make this more type-safe. -static FLAG_CHAR_IS_SPACE: u32 = 0x10000000; -// These two bits store some BREAK_TYPE_* flags -static FLAG_CAN_BREAK_MASK: u32 = 0x60000000; -static FLAG_CAN_BREAK_SHIFT: u32 = 29; -static FLAG_IS_SIMPLE_GLYPH: u32 = 0x80000000; +const FLAG_CHAR_IS_SPACE: u32 = 0x40000000; +const FLAG_IS_SIMPLE_GLYPH: u32 = 0x80000000; // glyph advance; in Au's. -static GLYPH_ADVANCE_MASK: u32 = 0x0FFF0000; -static GLYPH_ADVANCE_SHIFT: u32 = 16; -static GLYPH_ID_MASK: u32 = 0x0000FFFF; +const GLYPH_ADVANCE_MASK: u32 = 0x3FFF0000; +const GLYPH_ADVANCE_SHIFT: u32 = 16; +const GLYPH_ID_MASK: u32 = 0x0000FFFF; // Non-simple glyphs (more than one glyph per char; missing glyph, // newline, tab, large advance, or nonzero x/y offsets) may have one @@ -132,21 +89,8 @@ static GLYPH_ID_MASK: u32 = 0x0000FFFF; // side array so that there is a 1:1 mapping of GlyphEntry to // unicode char. -// The number of detailed glyphs for this char. If the char couldn't -// be mapped to a glyph (!FLAG_NOT_MISSING), then this actually holds -// the UTF8 code point instead. -static GLYPH_COUNT_MASK: u32 = 0x00FFFF00; -static GLYPH_COUNT_SHIFT: u32 = 8; -// N.B. following Gecko, these are all inverted so that a lot of -// missing chars can be memset with zeros in one fell swoop. -static FLAG_NOT_MISSING: u32 = 0x00000001; -static FLAG_NOT_CLUSTER_START: u32 = 0x00000002; -static FLAG_NOT_LIGATURE_GROUP_START: u32 = 0x00000004; - -static FLAG_CHAR_IS_TAB: u32 = 0x00000008; -static FLAG_CHAR_IS_NEWLINE: u32 = 0x00000010; -//static FLAG_CHAR_IS_LOW_SURROGATE: u32 = 0x00000020; -//static CHAR_IDENTITY_FLAGS_MASK: u32 = 0x00000038; +// The number of detailed glyphs for this char. +const GLYPH_COUNT_MASK: u32 = 0x0000FFFF; fn is_simple_glyph_id(id: GlyphId) -> bool { ((id as u32) & GLYPH_ID_MASK) == id @@ -164,7 +108,6 @@ type DetailedGlyphCount = u16; // Getters and setters for GlyphEntry. Setter methods are functional, // because GlyphEntry is immutable and only a u32 in size. impl GlyphEntry { - // getter methods #[inline(always)] fn advance(&self) -> Au { Au(((self.value & GLYPH_ADVANCE_MASK) >> GLYPH_ADVANCE_SHIFT) as i32) @@ -174,62 +117,20 @@ impl GlyphEntry { self.value & GLYPH_ID_MASK } - fn is_ligature_start(&self) -> bool { - self.has_flag(!FLAG_NOT_LIGATURE_GROUP_START) - } - - fn is_cluster_start(&self) -> bool { - self.has_flag(!FLAG_NOT_CLUSTER_START) - } - - // True if original char was normal (U+0020) space. Other chars may - // map to space glyph, but this does not account for them. + /// True if original char was normal (U+0020) space. Other chars may + /// map to space glyph, but this does not account for them. fn char_is_space(&self) -> bool { self.has_flag(FLAG_CHAR_IS_SPACE) } - fn char_is_tab(&self) -> bool { - !self.is_simple() && self.has_flag(FLAG_CHAR_IS_TAB) - } - - fn char_is_newline(&self) -> bool { - !self.is_simple() && self.has_flag(FLAG_CHAR_IS_NEWLINE) - } - - fn can_break_before(&self) -> BreakType { - let flag = ((self.value & FLAG_CAN_BREAK_MASK) >> FLAG_CAN_BREAK_SHIFT) as u8; - break_flag_to_enum(flag) - } - - // setter methods #[inline(always)] fn set_char_is_space(&self) -> GlyphEntry { GlyphEntry::new(self.value | FLAG_CHAR_IS_SPACE) } - #[inline(always)] - fn set_char_is_tab(&self) -> GlyphEntry { - assert!(!self.is_simple()); - GlyphEntry::new(self.value | FLAG_CHAR_IS_TAB) - } - - #[inline(always)] - fn set_char_is_newline(&self) -> GlyphEntry { - assert!(!self.is_simple()); - GlyphEntry::new(self.value | FLAG_CHAR_IS_NEWLINE) - } - - #[inline(always)] - fn set_can_break_before(&self, e: BreakType) -> GlyphEntry { - let flag = (break_enum_to_flag(e) as u32) << FLAG_CAN_BREAK_SHIFT; - GlyphEntry::new(self.value | flag) - } - - // helper methods - fn glyph_count(&self) -> u16 { assert!(!self.is_simple()); - ((self.value & GLYPH_COUNT_MASK) >> GLYPH_COUNT_SHIFT) as u16 + (self.value & GLYPH_COUNT_MASK) as u16 } #[inline(always)] @@ -576,9 +477,6 @@ impl<'a> GlyphStore { } }; - // FIXME(pcwalton): Is this necessary? I think it's a no-op. - entry = entry.adapt_character_flags_of_entry(self.entry_buffer[i.to_usize()]); - if character == Some(' ') { entry = entry.set_char_is_space() } @@ -647,62 +545,11 @@ impl<'a> GlyphStore { .fold(Au(0), |advance, (_, glyph)| advance + glyph.advance()) } - // getter methods pub fn char_is_space(&self, i: CharIndex) -> bool { assert!(i < self.char_len()); self.entry_buffer[i.to_usize()].char_is_space() } - pub fn char_is_tab(&self, i: CharIndex) -> bool { - assert!(i < self.char_len()); - self.entry_buffer[i.to_usize()].char_is_tab() - } - - pub fn char_is_newline(&self, i: CharIndex) -> bool { - assert!(i < self.char_len()); - self.entry_buffer[i.to_usize()].char_is_newline() - } - - pub fn is_ligature_start(&self, i: CharIndex) -> bool { - assert!(i < self.char_len()); - self.entry_buffer[i.to_usize()].is_ligature_start() - } - - pub fn is_cluster_start(&self, i: CharIndex) -> bool { - assert!(i < self.char_len()); - self.entry_buffer[i.to_usize()].is_cluster_start() - } - - pub fn can_break_before(&self, i: CharIndex) -> BreakType { - assert!(i < self.char_len()); - self.entry_buffer[i.to_usize()].can_break_before() - } - - // setter methods - pub fn set_char_is_space(&mut self, i: CharIndex) { - assert!(i < self.char_len()); - let entry = self.entry_buffer[i.to_usize()]; - self.entry_buffer[i.to_usize()] = entry.set_char_is_space(); - } - - pub fn set_char_is_tab(&mut self, i: CharIndex) { - assert!(i < self.char_len()); - let entry = self.entry_buffer[i.to_usize()]; - self.entry_buffer[i.to_usize()] = entry.set_char_is_tab(); - } - - pub fn set_char_is_newline(&mut self, i: CharIndex) { - assert!(i < self.char_len()); - let entry = self.entry_buffer[i.to_usize()]; - self.entry_buffer[i.to_usize()] = entry.set_char_is_newline(); - } - - pub fn set_can_break_before(&mut self, i: CharIndex, t: BreakType) { - assert!(i < self.char_len()); - let entry = self.entry_buffer[i.to_usize()]; - self.entry_buffer[i.to_usize()] = entry.set_can_break_before(t); - } - pub fn space_count_in_range(&self, range: &Range) -> u32 { let mut spaces = 0; for index in range.each_index() { diff --git a/components/gfx/text/shaping/harfbuzz.rs b/components/gfx/text/shaping/harfbuzz.rs index 462d5bf485c..426068a4106 100644 --- a/components/gfx/text/shaping/harfbuzz.rs +++ b/components/gfx/text/shaping/harfbuzz.rs @@ -576,13 +576,13 @@ extern fn glyph_h_advance_func(_: *mut hb_font_t, fn glyph_space_advance(font: *mut Font) -> f64 { let space_unicode = ' '; let space_glyph: hb_codepoint_t; - match unsafe {(*font).glyph_index(space_unicode)} { + match unsafe { (*font).glyph_index(space_unicode) } { Some(g) => { space_glyph = g as hb_codepoint_t; } None => panic!("No space info") } - let space_advance = unsafe {(*font).glyph_h_advance(space_glyph as GlyphId)}; + let space_advance = unsafe { (*font).glyph_h_advance(space_glyph as GlyphId) }; space_advance } diff --git a/components/layout/block.rs b/components/layout/block.rs index ca3ee670beb..d35c6f4cb9f 100644 --- a/components/layout/block.rs +++ b/components/layout/block.rs @@ -570,7 +570,7 @@ pub struct BlockFlow { bitflags! { flags BlockFlowFlags: u8 { - #[doc="If this is set, then this block flow is the root flow."] + #[doc = "If this is set, then this block flow is the root flow."] const IS_ROOT = 0x01, } } diff --git a/components/layout/data.rs b/components/layout/data.rs index 4b551e2fd9e..097852096fa 100644 --- a/components/layout/data.rs +++ b/components/layout/data.rs @@ -54,7 +54,7 @@ impl PrivateLayoutData { bitflags! { flags LayoutDataFlags: u8 { - #[doc="Whether a flow has been newly constructed."] + #[doc = "Whether a flow has been newly constructed."] const HAS_NEWLY_CONSTRUCTED_FLOW = 0x01 } } diff --git a/components/layout/flex.rs b/components/layout/flex.rs index 0124330e9b8..2cc2424a854 100644 --- a/components/layout/flex.rs +++ b/components/layout/flex.rs @@ -313,6 +313,10 @@ impl Flow for FlexFlow { &mut self.block_flow } + fn mark_as_root(&mut self) { + self.block_flow.mark_as_root(); + } + fn bubble_inline_sizes(&mut self) { let _scope = layout_debug_scope!("flex::bubble_inline_sizes {:x}", self.block_flow.base.debug_id()); diff --git a/components/layout/fragment.rs b/components/layout/fragment.rs index 9ac26393c3f..8ba97fc0031 100644 --- a/components/layout/fragment.rs +++ b/components/layout/fragment.rs @@ -2309,10 +2309,10 @@ bitflags! { // Various flags we can use when splitting fragments. See // `calculate_split_position_using_breaking_strategy()`. flags SplitOptions: u8 { - #[doc="True if this is the first fragment on the line."] + #[doc = "True if this is the first fragment on the line."] const STARTS_LINE = 0x01, - #[doc="True if we should attempt to split at character boundaries if this split fails. \ - This is used to implement `overflow-wrap: break-word`."] + #[doc = "True if we should attempt to split at character boundaries if this split fails. \ + This is used to implement `overflow-wrap: break-word`."] const RETRY_AT_CHARACTER_BOUNDARIES = 0x02, } } diff --git a/components/layout/incremental.rs b/components/layout/incremental.rs index 623fa4685fe..14205b32cb5 100644 --- a/components/layout/incremental.rs +++ b/components/layout/incremental.rs @@ -42,8 +42,8 @@ bitflags! { bitflags! { flags SpecialRestyleDamage: u8 { - #[doc="If this flag is set, we need to reflow the entire document. This is more or less a \ - temporary hack to deal with cases that we don't handle incrementally yet."] + #[doc = "If this flag is set, we need to reflow the entire document. This is more or less a \ + temporary hack to deal with cases that we don't handle incrementally yet."] const REFLOW_ENTIRE_DOCUMENT = 0x01, } } diff --git a/components/layout/inline.rs b/components/layout/inline.rs index 6307061d7ef..6e2b87d981e 100644 --- a/components/layout/inline.rs +++ b/components/layout/inline.rs @@ -183,9 +183,9 @@ int_range_index! { bitflags! { flags InlineReflowFlags: u8 { - #[doc="The `white-space: nowrap` property from CSS 2.1 § 16.6 is in effect."] + #[doc = "The `white-space: nowrap` property from CSS 2.1 § 16.6 is in effect."] const NO_WRAP_INLINE_REFLOW_FLAG = 0x01, - #[doc="The `white-space: pre` property from CSS 2.1 § 16.6 is in effect."] + #[doc = "The `white-space: pre` property from CSS 2.1 § 16.6 is in effect."] const WRAP_ON_NEWLINE_INLINE_REFLOW_FLAG = 0x02 } } diff --git a/components/layout/table_wrapper.rs b/components/layout/table_wrapper.rs index c3312bceba9..ebf96020634 100644 --- a/components/layout/table_wrapper.rs +++ b/components/layout/table_wrapper.rs @@ -13,12 +13,12 @@ #![deny(unsafe_code)] -use block::{BlockFlow, FloatNonReplaced, ISizeAndMarginsComputer, ISizeConstraintInput}; +use block::{BlockFlow, FloatNonReplaced, AbsoluteNonReplaced, ISizeAndMarginsComputer, ISizeConstraintInput}; use block::{ISizeConstraintSolution, MarginsMayCollapseFlag}; use context::LayoutContext; use floats::FloatKind; use flow::{FlowClass, Flow, ImmutableFlowUtils}; -use flow::{IMPACTED_BY_LEFT_FLOATS, IMPACTED_BY_RIGHT_FLOATS, OpaqueFlow}; +use flow::{IMPACTED_BY_LEFT_FLOATS, IMPACTED_BY_RIGHT_FLOATS, INLINE_POSITION_IS_STATIC, OpaqueFlow}; use fragment::{Fragment, FragmentBorderBoxIterator}; use model::MaybeAuto; use table::{ColumnComputedInlineSize, ColumnIntrinsicInlineSize}; @@ -242,6 +242,26 @@ impl TableWrapperFlow { return } + if !self.block_flow.base.flags.contains(INLINE_POSITION_IS_STATIC) { + let inline_size_computer = AbsoluteTable { + minimum_width_of_all_columns: minimum_width_of_all_columns, + preferred_width_of_all_columns: preferred_width_of_all_columns, + border_collapse: border_collapse, + }; + let input = + inline_size_computer.compute_inline_size_constraint_inputs(&mut self.block_flow, + parent_flow_inline_size, + layout_context); + + let solution = inline_size_computer.solve_inline_size_constraints(&mut self.block_flow, + &input); + inline_size_computer.set_inline_size_constraint_solutions(&mut self.block_flow, + solution); + inline_size_computer.set_inline_position_of_flow_if_necessary(&mut self.block_flow, + solution); + return + } + let inline_size_computer = Table { minimum_width_of_all_columns: minimum_width_of_all_columns, preferred_width_of_all_columns: preferred_width_of_all_columns, @@ -791,3 +811,54 @@ impl ISizeAndMarginsComputer for FloatedTable { FloatNonReplaced.solve_inline_size_constraints(block, input) } } + +struct AbsoluteTable { + minimum_width_of_all_columns: Au, + preferred_width_of_all_columns: Au, + border_collapse: border_collapse::T, +} + +impl ISizeAndMarginsComputer for AbsoluteTable { + fn compute_border_and_padding(&self, block: &mut BlockFlow, containing_block_inline_size: Au) { + block.fragment.compute_border_and_padding(containing_block_inline_size, + self.border_collapse) + } + + fn initial_computed_inline_size(&self, + block: &mut BlockFlow, + parent_flow_inline_size: Au, + layout_context: &LayoutContext) + -> MaybeAuto { + let containing_block_inline_size = + self.containing_block_inline_size(block, + parent_flow_inline_size, + layout_context); + initial_computed_inline_size(block, + containing_block_inline_size, + self.minimum_width_of_all_columns, + self.preferred_width_of_all_columns) + } + + fn containing_block_inline_size(&self, + block: &mut BlockFlow, + parent_flow_inline_size: Au, + layout_context: &LayoutContext) + -> Au { + AbsoluteNonReplaced.containing_block_inline_size(block, parent_flow_inline_size, layout_context) + } + + fn solve_inline_size_constraints(&self, + block: &mut BlockFlow, + input: &ISizeConstraintInput) + -> ISizeConstraintSolution { + AbsoluteNonReplaced.solve_inline_size_constraints(block, input) + } + + fn set_inline_position_of_flow_if_necessary(&self, + block: &mut BlockFlow, + solution: ISizeConstraintSolution) { + AbsoluteNonReplaced.set_inline_position_of_flow_if_necessary(block, solution); + } + +} + diff --git a/components/msg/lib.rs b/components/msg/lib.rs index 7c03b73d591..34a87cfd805 100644 --- a/components/msg/lib.rs +++ b/components/msg/lib.rs @@ -20,9 +20,9 @@ extern crate util; extern crate url; extern crate style; -#[cfg(target_os="macos")] +#[cfg(target_os = "macos")] extern crate core_foundation; -#[cfg(target_os="macos")] +#[cfg(target_os = "macos")] extern crate io_surface; pub mod compositor_msg; diff --git a/components/net/http_loader.rs b/components/net/http_loader.rs index bc47b6aa709..4c257513526 100644 --- a/components/net/http_loader.rs +++ b/components/net/http_loader.rs @@ -2,49 +2,47 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + use devtools_traits::{ChromeToDevtoolsControlMsg, DevtoolsControlMsg, NetworkEvent}; -use hsts::{HSTSList, secure_url}; +use file_loader; +use flate2::read::{DeflateDecoder, GzDecoder}; +use hsts::secure_url; +use hyper::Error as HttpError; +use hyper::client::{Request, Response}; +use hyper::header::{AcceptEncoding, Accept, ContentLength, ContentType, Host}; +use hyper::header::{Location, qitem, StrictTransportSecurity}; +use hyper::header::{Quality, QualityItem, Headers, ContentEncoding, Encoding}; +use hyper::http::RawStatus; +use hyper::method::Method; +use hyper::mime::{Mime, TopLevel, SubLevel}; +use hyper::net::{Fresh, HttpsConnector, Openssl}; +use hyper::status::{StatusCode, StatusClass}; +use ipc_channel::ipc::{self, IpcSender}; +use log; use mime_classifier::MIMEClassifier; use net_traits::ProgressMsg::{Payload, Done}; use net_traits::hosts::replace_hosts; use net_traits::{ControlMsg, CookieSource, LoadData, Metadata, LoadConsumer, IncludeSubdomains}; -use resource_task::{start_sending_opt, start_sending_sniffed_opt}; - -use file_loader; -use flate2::read::{DeflateDecoder, GzDecoder}; -use hyper::Error as HttpError; -use hyper::client::Request; -use hyper::header::StrictTransportSecurity; -use hyper::header::{AcceptEncoding, Accept, ContentLength, ContentType, Host, Location, qitem, Quality, QualityItem}; -use hyper::method::Method; -use hyper::mime::{Mime, TopLevel, SubLevel}; -use hyper::net::{HttpConnector, HttpsConnector, Openssl}; -use hyper::status::{StatusCode, StatusClass}; -use ipc_channel::ipc::{self, IpcSender}; -use log; use openssl::ssl::{SslContext, SslMethod, SSL_VERIFY_PEER}; +use resource_task::{start_sending_opt, start_sending_sniffed_opt}; +use std::borrow::ToOwned; +use std::boxed::FnBox; use std::collections::HashSet; use std::error::Error; use std::io::{self, Read, Write}; use std::sync::Arc; -use std::sync::Mutex; use std::sync::mpsc::{Sender, channel}; use url::{Url, UrlParser}; -use util::opts; use util::resource_files::resources_dir_path; use util::task::spawn_named; - -use std::borrow::ToOwned; -use std::boxed::FnBox; use uuid; pub fn factory(resource_mgr_chan: IpcSender, - devtools_chan: Option>, - hsts_list: Arc>) + devtools_chan: Option>) -> Box) + Send> { - box move |load_data, senders, classifier| { - spawn_named("http_loader".to_owned(), - move || load(load_data, senders, classifier, resource_mgr_chan, devtools_chan, hsts_list)) + box move |load_data: LoadData, senders, classifier| { + spawn_named(format!("http_loader for {}", load_data.url.serialize()), + move || load_for_consumer(load_data, senders, classifier, resource_mgr_chan, devtools_chan)) } } @@ -76,21 +74,365 @@ fn read_block(reader: &mut R) -> Result { } } -fn request_must_be_secured(hsts_list: &HSTSList, url: &Url) -> bool { - match url.domain() { - Some(ref h) => { - hsts_list.is_host_secure(h) - }, - _ => false +fn inner_url(url: &Url) -> Url { + let inner_url = url.non_relative_scheme_data().unwrap(); + Url::parse(inner_url).unwrap() +} + +fn load_for_consumer(load_data: LoadData, + start_chan: LoadConsumer, + classifier: Arc, + resource_mgr_chan: IpcSender, + devtools_chan: Option>) { + + match load::(load_data, resource_mgr_chan, devtools_chan, &NetworkHttpRequestFactory) { + Err(LoadError::UnsupportedScheme(url)) => { + let s = format!("{} request, but we don't support that scheme", &*url.scheme); + send_error(url, s, start_chan) + } + Err(LoadError::Connection(url, e)) => { + send_error(url, e, start_chan) + } + Err(LoadError::MaxRedirects(url)) => { + send_error(url, "too many redirects".to_string(), start_chan) + } + Err(LoadError::Cors(url, msg)) | + Err(LoadError::InvalidRedirect(url, msg)) | + Err(LoadError::Decoding(url, msg)) => { + send_error(url, msg, start_chan) + } + Err(LoadError::Ssl(url, msg)) => { + info!("ssl validation error {}, '{}'", url.serialize(), msg); + + let mut image = resources_dir_path(); + image.push("badcert.html"); + let load_data = LoadData::new(Url::from_file_path(&*image).unwrap(), None); + + file_loader::factory(load_data, start_chan, classifier) + + } + Ok(mut load_response) => { + let metadata = load_response.metadata.clone(); + send_data(&mut load_response, start_chan, metadata, classifier) + } } } -fn load(mut load_data: LoadData, - start_chan: LoadConsumer, - classifier: Arc, - resource_mgr_chan: IpcSender, - devtools_chan: Option>, - hsts_list: Arc>) { +pub trait HttpResponse: Read { + fn headers(&self) -> &Headers; + fn status(&self) -> StatusCode; + fn status_raw(&self) -> &RawStatus; + + fn content_encoding(&self) -> Option { + self.headers().get::().and_then(|h| { + match h { + &ContentEncoding(ref encodings) => { + if encodings.contains(&Encoding::Gzip) { + Some(Encoding::Gzip) + } else if encodings.contains(&Encoding::Deflate) { + Some(Encoding::Deflate) + } else { + // TODO: Is this the correct behaviour? + None + } + } + } + }) + } +} + +struct WrappedHttpResponse { + response: Response +} + +impl Read for WrappedHttpResponse { + #[inline] + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.response.read(buf) + } +} + +impl HttpResponse for WrappedHttpResponse { + fn headers(&self) -> &Headers { + &self.response.headers + } + + fn status(&self) -> StatusCode { + self.response.status + } + + fn status_raw(&self) -> &RawStatus { + self.response.status_raw() + } +} + +pub trait HttpRequestFactory { + type R: HttpRequest; + + fn create(&self, url: Url, method: Method) -> Result; +} + +struct NetworkHttpRequestFactory; + +impl HttpRequestFactory for NetworkHttpRequestFactory { + type R = WrappedHttpRequest; + + fn create(&self, url: Url, method: Method) -> Result { + let mut context = SslContext::new(SslMethod::Sslv23).unwrap(); + context.set_verify(SSL_VERIFY_PEER, None); + context.set_CA_file(&resources_dir_path().join("certs")).unwrap(); + + let connector = HttpsConnector::new(Openssl { context: Arc::new(context) }); + let connection = Request::with_connector(method, url.clone(), &connector); + + let ssl_err_string = "Some(OpenSslErrors([UnknownError { library: \"SSL routines\", \ + function: \"SSL3_GET_SERVER_CERTIFICATE\", \ + reason: \"certificate verify failed\" }]))"; + + let request = match connection { + Ok(req) => req, + + Err(HttpError::Io(ref io_error)) if ( + io_error.kind() == io::ErrorKind::Other && + io_error.description() == "Error in OpenSSL" && + // FIXME: This incredibly hacky. Make it more robust, and at least test it. + format!("{:?}", io_error.cause()) == ssl_err_string + ) => { + return Err( + LoadError::Ssl( + url, + format!("ssl error {:?}: {:?} {:?}", + io_error.kind(), + io_error.description(), + io_error.cause()) + ) + ) + }, + Err(e) => { + return Err(LoadError::Connection(url, e.description().to_string())) + } + }; + + Ok(WrappedHttpRequest { request: request }) + } +} + +pub trait HttpRequest { + type R: HttpResponse + 'static; + + fn headers_mut(&mut self) -> &mut Headers; + fn send(self, body: &Option>) -> Result; +} + +struct WrappedHttpRequest { + request: Request +} + +impl HttpRequest for WrappedHttpRequest { + type R = WrappedHttpResponse; + + fn headers_mut(&mut self) -> &mut Headers { + self.request.headers_mut() + } + + fn send(self, body: &Option>) -> Result { + let url = self.request.url.clone(); + let mut request_writer = match self.request.start() { + Ok(streaming) => streaming, + Err(e) => return Err(LoadError::Connection(url, e.description().to_string())) + }; + + if let Some(ref data) = *body { + match request_writer.write_all(&data) { + Err(e) => { + return Err(LoadError::Connection(url, e.description().to_string())) + } + _ => {} + } + } + + let response = match request_writer.send() { + Ok(w) => w, + Err(e) => return Err(LoadError::Connection(url, e.description().to_string())) + }; + + Ok(WrappedHttpResponse { response: response }) + } +} + +#[derive(Debug)] +pub enum LoadError { + UnsupportedScheme(Url), + Connection(Url, String), + Cors(Url, String), + Ssl(Url, String), + InvalidRedirect(Url, String), + Decoding(Url, String), + MaxRedirects(Url) +} + +fn set_default_accept_encoding(headers: &mut Headers) { + if headers.has::() { + return + } + + headers.set_raw("Accept-Encoding".to_owned(), vec![b"gzip, deflate".to_vec()]); +} + +fn set_default_accept(headers: &mut Headers) { + if !headers.has::() { + let accept = Accept(vec![ + qitem(Mime(TopLevel::Text, SubLevel::Html, vec![])), + qitem(Mime(TopLevel::Application, SubLevel::Ext("xhtml+xml".to_string()), vec![])), + QualityItem::new(Mime(TopLevel::Application, SubLevel::Xml, vec![]), Quality(900u16)), + QualityItem::new(Mime(TopLevel::Star, SubLevel::Star, vec![]), Quality(800u16)), + ]); + headers.set(accept); + } +} + +fn set_request_cookies(url: Url, headers: &mut Headers, resource_mgr_chan: &IpcSender) { + let (tx, rx) = ipc::channel().unwrap(); + resource_mgr_chan.send(ControlMsg::GetCookiesForUrl(url, tx, CookieSource::HTTP)).unwrap(); + if let Some(cookie_list) = rx.recv().unwrap() { + let mut v = Vec::new(); + v.push(cookie_list.into_bytes()); + headers.set_raw("Cookie".to_owned(), v); + } +} + +fn set_cookies_from_response(url: Url, response: &HttpResponse, resource_mgr_chan: &IpcSender) { + if let Some(cookies) = response.headers().get_raw("set-cookie") { + for cookie in cookies.iter() { + if let Ok(cookies) = String::from_utf8(cookie.clone()) { + resource_mgr_chan.send(ControlMsg::SetCookiesForUrl(url.clone(), + cookies, + CookieSource::HTTP)).unwrap(); + } + } + } +} + +fn request_must_be_secured(url: &Url, resource_mgr_chan: &IpcSender) -> bool { + let (tx, rx) = ipc::channel().unwrap(); + resource_mgr_chan.send( + ControlMsg::GetHostMustBeSecured(url.domain().unwrap().to_string(), tx) + ).unwrap(); + + rx.recv().unwrap() +} + +fn update_sts_list_from_response(url: &Url, response: &HttpResponse, resource_mgr_chan: &IpcSender) { + if url.scheme != "https" { + return; + } + + if let Some(header) = response.headers().get::() { + if let Some(host) = url.domain() { + info!("adding host {} to the strict transport security list", host); + info!("- max-age {}", header.max_age); + + let include_subdomains = if header.include_subdomains { + info!("- includeSubdomains"); + IncludeSubdomains::Included + } else { + IncludeSubdomains::NotIncluded + }; + + let msg = ControlMsg::SetHSTSEntryForHost( + host.to_string(), + include_subdomains, + header.max_age + ); + + resource_mgr_chan.send(msg).unwrap(); + } + } +} + +pub struct StreamedResponse { + decoder: Decoder, + pub metadata: Metadata +} + + +impl Read for StreamedResponse { + #[inline] + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match self.decoder { + Decoder::Gzip(ref mut d) => d.read(buf), + Decoder::Deflate(ref mut d) => d.read(buf), + Decoder::Plain(ref mut d) => d.read(buf) + } + } +} + +impl StreamedResponse { + fn new(m: Metadata, d: Decoder) -> StreamedResponse { + StreamedResponse { metadata: m, decoder: d } + } + + fn from_http_response(response: R, m: Metadata) -> Result, LoadError> { + match response.content_encoding() { + Some(Encoding::Gzip) => { + let result = GzDecoder::new(response); + match result { + Ok(response_decoding) => { + return Ok(StreamedResponse::new(m, Decoder::Gzip(response_decoding))); + } + Err(err) => { + return Err(LoadError::Decoding(m.final_url, err.to_string())); + } + } + } + Some(Encoding::Deflate) => { + let response_decoding = DeflateDecoder::new(response); + return Ok(StreamedResponse::new(m, Decoder::Deflate(response_decoding))); + } + _ => { + return Ok(StreamedResponse::new(m, Decoder::Plain(response))); + } + } + } +} + +enum Decoder { + Gzip(GzDecoder), + Deflate(DeflateDecoder), + Plain(R) +} + +fn send_request_to_devtools(devtools_chan: Option>, + request_id: String, + url: Url, + method: Method, + headers: Headers, + body: Option>) { + + if let Some(ref chan) = devtools_chan { + let net_event = NetworkEvent::HttpRequest(url, method, headers, body); + + let msg = ChromeToDevtoolsControlMsg::NetworkEvent(request_id, net_event); + chan.send(DevtoolsControlMsg::FromChrome(msg)).unwrap(); + } +} + +fn send_response_to_devtools(devtools_chan: Option>, + request_id: String, + headers: Option, + status: Option) { + if let Some(ref chan) = devtools_chan { + let net_event_response = NetworkEvent::HttpResponse(headers, status, None); + + let msg = ChromeToDevtoolsControlMsg::NetworkEvent(request_id, net_event_response); + chan.send(DevtoolsControlMsg::FromChrome(msg)).unwrap(); + } +} +pub fn load(load_data: LoadData, + resource_mgr_chan: IpcSender, + devtools_chan: Option>, + request_factory: &HttpRequestFactory) + -> Result, LoadError> where A: HttpRequest + 'static { // FIXME: At the time of writing this FIXME, servo didn't have any central // location for configuration. If you're reading this and such a // repository DOES exist, please update this constant to use it. @@ -102,6 +444,7 @@ fn load(mut load_data: LoadData, // specified in the hosts file. let mut url = replace_hosts(&load_data.url); let mut redirected_to = HashSet::new(); + let mut method = load_data.method.clone(); // If the URL is a view-source scheme then the scheme data contains the // real URL that should be used for which the source is to be viewed. @@ -109,80 +452,30 @@ fn load(mut load_data: LoadData, // the source rather than rendering the contents of the URL. let viewing_source = url.scheme == "view-source"; if viewing_source { - let inner_url = load_data.url.non_relative_scheme_data().unwrap(); - doc_url = Url::parse(inner_url).unwrap(); - url = replace_hosts(&doc_url); - match &*url.scheme { - "http" | "https" => {} - _ => { - let s = format!("The {} scheme with view-source is not supported", url.scheme); - send_error(url, s, start_chan); - return; - } - }; + url = inner_url(&load_data.url); + doc_url = url.clone(); } // Loop to handle redirects. loop { iters = iters + 1; - if &*url.scheme != "https" && request_must_be_secured(&hsts_list.lock().unwrap(), &url) { + if &*url.scheme == "http" && request_must_be_secured(&url, &resource_mgr_chan) { info!("{} is in the strict transport security list, requesting secure host", url); url = secure_url(&url); } if iters > max_redirects { - send_error(url, "too many redirects".to_string(), start_chan); - return; + return Err(LoadError::MaxRedirects(url)); } - match &*url.scheme { - "http" | "https" => {} - _ => { - let s = format!("{} request, but we don't support that scheme", url.scheme); - send_error(url, s, start_chan); - return; - } + if &*url.scheme != "http" && &*url.scheme != "https" { + return Err(LoadError::UnsupportedScheme(url)); } info!("requesting {}", url.serialize()); - let ssl_err_string = "Some(OpenSslErrors([UnknownError { library: \"SSL routines\", \ -function: \"SSL3_GET_SERVER_CERTIFICATE\", \ -reason: \"certificate verify failed\" }]))"; - - let req = if opts::get().nossl { - Request::with_connector(load_data.method.clone(), url.clone(), &HttpConnector) - } else { - let mut context = SslContext::new(SslMethod::Sslv23).unwrap(); - context.set_verify(SSL_VERIFY_PEER, None); - context.set_CA_file(&resources_dir_path().join("certs")).unwrap(); - Request::with_connector(load_data.method.clone(), url.clone(), - &HttpsConnector::new(Openssl { context: Arc::new(context) })) - }; - - let mut req = match req { - Ok(req) => req, - Err(HttpError::Io(ref io_error)) if ( - io_error.kind() == io::ErrorKind::Other && - io_error.description() == "Error in OpenSSL" && - // FIXME: This incredibly hacky. Make it more robust, and at least test it. - format!("{:?}", io_error.cause()) == ssl_err_string - ) => { - let mut image = resources_dir_path(); - image.push("badcert.html"); - let load_data = LoadData::new(Url::from_file_path(&*image).unwrap(), None); - file_loader::factory(load_data, start_chan, classifier); - return; - }, - Err(e) => { - println!("{:?}", e); - send_error(url, e.description().to_string(), start_chan); - return; - } - }; - - //Ensure that the host header is set from the original url + // Ensure that the host header is set from the original url let host = Host { hostname: doc_url.serialize_host().unwrap(), port: doc_url.port_or_default() @@ -192,156 +485,90 @@ reason: \"certificate verify failed\" }]))"; // See https://bugzilla.mozilla.org/show_bug.cgi?id=401564 and // https://bugzilla.mozilla.org/show_bug.cgi?id=216828 . // Only preserve ones which have been explicitly marked as such. - if iters == 1 { + let mut request_headers = if iters == 1 { let mut combined_headers = load_data.headers.clone(); combined_headers.extend(load_data.preserved_headers.iter()); - *req.headers_mut() = combined_headers; + combined_headers } else { - *req.headers_mut() = load_data.preserved_headers.clone(); - } + load_data.preserved_headers.clone() + }; - req.headers_mut().set(host); + request_headers.set(host); - if !req.headers().has::() { - let accept = Accept(vec![ - qitem(Mime(TopLevel::Text, SubLevel::Html, vec![])), - qitem(Mime(TopLevel::Application, SubLevel::Ext("xhtml+xml".to_string()), vec![])), - QualityItem::new(Mime(TopLevel::Application, SubLevel::Xml, vec![]), Quality(900u16)), - QualityItem::new(Mime(TopLevel::Star, SubLevel::Star, vec![]), Quality(800u16)), - ]); - req.headers_mut().set(accept); - } + set_default_accept(&mut request_headers); + set_default_accept_encoding(&mut request_headers); + set_request_cookies(doc_url.clone(), &mut request_headers, &resource_mgr_chan); - let (tx, rx) = ipc::channel().unwrap(); - resource_mgr_chan.send(ControlMsg::GetCookiesForUrl(doc_url.clone(), - tx, - CookieSource::HTTP)).unwrap(); - if let Some(cookie_list) = rx.recv().unwrap() { - let mut v = Vec::new(); - v.push(cookie_list.into_bytes()); - req.headers_mut().set_raw("Cookie".to_owned(), v); - } + let mut req = try!(request_factory.create(url.clone(), method.clone())); + *req.headers_mut() = request_headers; - if !req.headers().has::() { - req.headers_mut().set_raw("Accept-Encoding".to_owned(), vec![b"gzip, deflate".to_vec()]); - } if log_enabled!(log::LogLevel::Info) { - info!("{}", load_data.method); - for header in req.headers().iter() { + info!("{}", method); + for header in req.headers_mut().iter() { info!(" - {}", header); } info!("{:?}", load_data.data); } // Avoid automatically sending request body if a redirect has occurred. - let writer = match load_data.data { - Some(ref data) if iters == 1 => { - req.headers_mut().set(ContentLength(data.len() as u64)); - let mut writer = match req.start() { - Ok(w) => w, - Err(e) => { - send_error(url, e.description().to_string(), start_chan); - return; - } - }; - match writer.write_all(&*data) { - Err(e) => { - send_error(url, e.description().to_string(), start_chan); - return; - } - _ => {} - }; - writer - }, - _ => { - match load_data.method { - Method::Get | Method::Head => (), - _ => req.headers_mut().set(ContentLength(0)) - } - match req.start() { - Ok(w) => w, - Err(e) => { - send_error(url, e.description().to_string(), start_chan); - return; - } - } - } - }; - - // Send an HttpRequest message to devtools with a unique request_id - // TODO: Do this only if load_data has some pipeline_id, and send the pipeline_id in the message + // + // TODO - This is the wrong behaviour according to the RFC. However, I'm not + // sure how much "correctness" vs. real-world is important in this case. + // + // https://tools.ietf.org/html/rfc7231#section-6.4 + let is_redirected_request = iters != 1; let request_id = uuid::Uuid::new_v4().to_simple_string(); - if let Some(ref chan) = devtools_chan { - let net_event = NetworkEvent::HttpRequest(load_data.url.clone(), - load_data.method.clone(), - load_data.headers.clone(), - load_data.data.clone()); - chan.send(DevtoolsControlMsg::FromChrome( - ChromeToDevtoolsControlMsg::NetworkEvent(request_id.clone(), - net_event))).unwrap(); - } + let response = match load_data.data { + Some(ref data) if !is_redirected_request => { + req.headers_mut().set(ContentLength(data.len() as u64)); - let mut response = match writer.send() { - Ok(r) => r, - Err(e) => { - send_error(url, e.description().to_string(), start_chan); - return; + // TODO: Do this only if load_data has some pipeline_id, and send the pipeline_id + // in the message + send_request_to_devtools( + devtools_chan.clone(), request_id.clone(), url.clone(), + method.clone(), load_data.headers.clone(), + load_data.data.clone() + ); + + try!(req.send(&load_data.data)) + } + _ => { + if load_data.method != Method::Get && load_data.method != Method::Head { + req.headers_mut().set(ContentLength(0)) + } + + send_request_to_devtools( + devtools_chan.clone(), request_id.clone(), url.clone(), + method.clone(), load_data.headers.clone(), + None + ); + + try!(req.send(&None)) } }; - // Dump headers, but only do the iteration if info!() is enabled. - info!("got HTTP response {}, headers:", response.status); + info!("got HTTP response {}, headers:", response.status()); if log_enabled!(log::LogLevel::Info) { - for header in response.headers.iter() { + for header in response.headers().iter() { info!(" - {}", header); } } - if let Some(cookies) = response.headers.get_raw("set-cookie") { - for cookie in cookies { - if let Ok(cookies) = String::from_utf8(cookie.clone()) { - resource_mgr_chan.send(ControlMsg::SetCookiesForUrl(doc_url.clone(), - cookies, - CookieSource::HTTP)).unwrap(); - } - } - } + set_cookies_from_response(doc_url.clone(), &response, &resource_mgr_chan); + update_sts_list_from_response(&url, &response, &resource_mgr_chan); - if url.scheme == "https" { - if let Some(header) = response.headers.get::() { - if let Some(host) = url.domain() { - info!("adding host {} to the strict transport security list", host); - info!("- max-age {}", header.max_age); - - let include_subdomains = if header.include_subdomains { - info!("- includeSubdomains"); - IncludeSubdomains::Included - } else { - IncludeSubdomains::NotIncluded - }; - - resource_mgr_chan.send( - ControlMsg::SetHSTSEntryForHost( - host.to_string(), include_subdomains, header.max_age - ) - ).unwrap(); - } - } - } - - - if response.status.class() == StatusClass::Redirection { - match response.headers.get::() { + // --- Loop if there's a redirect + if response.status().class() == StatusClass::Redirection { + match response.headers().get::() { Some(&Location(ref new_url)) => { // CORS (https://fetch.spec.whatwg.org/#http-fetch, status section, point 9, 10) match load_data.cors { Some(ref c) => { if c.preflight { - // The preflight lied - send_error(url, - "Preflight fetch inconsistent with main fetch".to_string(), - start_chan); - return; + return Err( + LoadError::Cors( + url, + "Preflight fetch inconsistent with main fetch".to_string())); } else { // XXXManishearth There are some CORS-related steps here, // but they don't seem necessary until credentials are implemented @@ -349,28 +576,28 @@ reason: \"certificate verify failed\" }]))"; } _ => {} } + let new_doc_url = match UrlParser::new().base_url(&doc_url).parse(&new_url) { Ok(u) => u, Err(e) => { - send_error(doc_url, e.to_string(), start_chan); - return; + return Err(LoadError::InvalidRedirect(doc_url, e.to_string())); } }; + info!("redirecting to {}", new_doc_url); url = replace_hosts(&new_doc_url); doc_url = new_doc_url; // According to https://tools.ietf.org/html/rfc7231#section-6.4.2, // historically UAs have rewritten POST->GET on 301 and 302 responses. - if load_data.method == Method::Post && - (response.status == StatusCode::MovedPermanently || - response.status == StatusCode::Found) { - load_data.method = Method::Get; + if method == Method::Post && + (response.status() == StatusCode::MovedPermanently || + response.status() == StatusCode::Found) { + method = Method::Get; } - if redirected_to.contains(&doc_url) { - send_error(doc_url, "redirect loop".to_string(), start_chan); - return; + if redirected_to.contains(&url) { + return Err(LoadError::InvalidRedirect(doc_url, "redirect loop".to_string())); } redirected_to.insert(doc_url.clone()); @@ -380,11 +607,13 @@ reason: \"certificate verify failed\" }]))"; } } - let mut adjusted_headers = response.headers.clone(); + let mut adjusted_headers = response.headers().clone(); + if viewing_source { adjusted_headers.set(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec![]))); } - let mut metadata: Metadata = Metadata::default(doc_url); + + let mut metadata: Metadata = Metadata::default(doc_url.clone()); metadata.set_content_type(match adjusted_headers.get() { Some(&ContentType(ref mime)) => Some(mime), None => None @@ -392,56 +621,16 @@ reason: \"certificate verify failed\" }]))"; metadata.headers = Some(adjusted_headers); metadata.status = Some(response.status_raw().clone()); - let mut encoding_str: Option = None; - //FIXME: Implement Content-Encoding Header https://github.com/hyperium/hyper/issues/391 - if let Some(encodings) = response.headers.get_raw("content-encoding") { - for encoding in encodings { - if let Ok(encodings) = String::from_utf8(encoding.clone()) { - if encodings == "gzip" || encodings == "deflate" { - encoding_str = Some(encodings); - break; - } - } - } - } - + // --- Tell devtools that we got a response // Send an HttpResponse message to devtools with the corresponding request_id // TODO: Send this message only if load_data has a pipeline_id that is not None - if let Some(ref chan) = devtools_chan { - let net_event_response = - NetworkEvent::HttpResponse(metadata.headers.clone(), - metadata.status.clone(), - None); - chan.send(DevtoolsControlMsg::FromChrome( - ChromeToDevtoolsControlMsg::NetworkEvent(request_id, - net_event_response))).unwrap(); - } + // TODO: Send this message even when the load fails? + send_response_to_devtools( + devtools_chan, request_id, + metadata.headers.clone(), metadata.status.clone() + ); - match encoding_str { - Some(encoding) => { - if encoding == "gzip" { - let result = GzDecoder::new(response); - match result { - Ok(mut response_decoding) => { - send_data(&mut response_decoding, start_chan, metadata, classifier); - } - Err(err) => { - send_error(metadata.final_url, err.to_string(), start_chan); - return; - } - } - } else if encoding == "deflate" { - let mut response_decoding = DeflateDecoder::new(response); - send_data(&mut response_decoding, start_chan, metadata, classifier); - } - }, - None => { - send_data(&mut response, start_chan, metadata, classifier); - } - } - - // We didn't get redirected. - break; + return StreamedResponse::from_http_response(response, metadata) } } diff --git a/components/net/mime_classifier.rs b/components/net/mime_classifier.rs index ea71a26615d..0ed472b3982 100644 --- a/components/net/mime_classifier.rs +++ b/components/net/mime_classifier.rs @@ -3,7 +3,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::borrow::ToOwned; -use std::cmp::max; pub struct MIMEClassifier { image_classifier: GroupedClassifier, @@ -24,51 +23,34 @@ impl MIMEClassifier { data: &[u8]) -> Option<(String, String)> { match *supplied_type { - None => { - return self.sniff_unknown_type(!no_sniff, data); - } + None => self.sniff_unknown_type(!no_sniff, data), Some((ref media_type, ref media_subtype)) => { match (&**media_type, &**media_subtype) { - ("unknown", "unknown") | ("application", "unknown") | ("*", "*") => { - return self.sniff_unknown_type(!no_sniff, data); - } + ("unknown", "unknown") | + ("application", "unknown") | + ("*", "*") => self.sniff_unknown_type(!no_sniff, data), _ => { if no_sniff { - return supplied_type.clone(); - } - if check_for_apache_bug { - return self.sniff_text_or_data(data); - } - - if MIMEClassifier::is_xml(media_type, media_subtype) { - return supplied_type.clone(); - } - //Inplied in section 7.3, but flow is not clear - if MIMEClassifier::is_html(media_type, media_subtype) { - return self.feeds_classifier - .classify(data) - .or(supplied_type.clone()); - } - - if &**media_type == "image" { - if let Some(tp) = self.image_classifier.classify(data) { - return Some(tp); - } - } - - match (&**media_type, &**media_subtype) { - ("audio", _) | ("video", _) | ("application", "ogg") => { - if let Some(tp) = self.audio_video_classifer.classify(data) { - return Some(tp); - } - } - _ => {} + supplied_type.clone() + } else if check_for_apache_bug { + self.sniff_text_or_data(data) + } else if MIMEClassifier::is_xml(media_type, media_subtype) { + supplied_type.clone() + } else if MIMEClassifier::is_html(media_type, media_subtype) { + //Implied in section 7.3, but flow is not clear + self.feeds_classifier.classify(data).or(supplied_type.clone()) + } else { + match (&**media_type, &**media_subtype) { + ("image", _) => self.image_classifier.classify(data), + ("audio", _) | ("video", _) | ("application", "ogg") => + self.audio_video_classifer.classify(data), + _ => None + }.or(supplied_type.clone()) } } } } } - return supplied_type.clone(); } pub fn new() -> MIMEClassifier { @@ -99,13 +81,15 @@ impl MIMEClassifier { fn sniff_text_or_data(&self, data: &[u8]) -> Option<(String, String)> { self.binary_or_plaintext.classify(data) } + fn is_xml(tp: &str, sub_tp: &str) -> bool { - let suffix = &sub_tp[(max(sub_tp.len() as isize - "+xml".len() as isize, 0) as usize)..]; - match (tp, sub_tp, suffix) { - (_, _, "+xml") | ("application", "xml",_) | ("text", "xml",_) => {true} - _ => {false} - } + sub_tp.ends_with("+xml") || + match (tp, sub_tp) { + ("application", "xml") | ("text", "xml") => true, + _ => false + } } + fn is_html(tp: &str, sub_tp: &str) -> bool { tp == "text" && sub_tp == "html" } @@ -141,13 +125,11 @@ impl <'a, T: Iterator + Clone> Matches for T { // Side effects // moves the iterator when match is found fn matches(&mut self, matches: &[u8]) -> bool { - for (byte_a, byte_b) in self.clone().take(matches.len()).zip(matches) { - if byte_a != byte_b { - return false; - } + let result = self.clone().zip(matches).all(|(s, m)| *s == *m); + if result { + self.nth(matches.len()); } - self.nth(matches.len()); - true + result } } @@ -155,36 +137,27 @@ struct ByteMatcher { pattern: &'static [u8], mask: &'static [u8], leading_ignore: &'static [u8], - content_type: (&'static str,&'static str) + content_type: (&'static str, &'static str) } impl ByteMatcher { fn matches(&self, data: &[u8]) -> Option { - if data.len() < self.pattern.len() { - return None; + None + } else if data == self.pattern { + Some(self.pattern.len()) + } else { + data[..data.len() - self.pattern.len()].iter() + .position(|x| !self.leading_ignore.contains(x)) + .and_then(|start| + if data[start..].iter() + .zip(self.pattern.iter()).zip(self.mask.iter()) + .all(|((&data, &pattern), &mask)| (data & mask) == (pattern & mask)) { + Some(start + self.pattern.len()) + } else { + None + }) } - //TODO replace with iterators if I ever figure them out... - let mut i: usize = 0; - let max_i = data.len()-self.pattern.len(); - - loop { - if !self.leading_ignore.iter().any(|x| *x == data[i]) { - break; - } - - i = i + 1; - if i > max_i { - return None; - } - } - for j in 0..self.pattern.len() { - if (data[i] & self.mask[j]) != (self.pattern[j] & self.mask[j]) { - return None; - } - i = i + 1; - } - Some(i) } } @@ -202,14 +175,13 @@ struct TagTerminatedByteMatcher { impl MIMEChecker for TagTerminatedByteMatcher { fn classify(&self, data: &[u8]) -> Option<(String, String)> { - let pattern = self.matcher.matches(data); - let pattern_matches = pattern.map(|j| j < data.len() && (data[j] == b' ' || data[j] == b'>')); - if pattern_matches.unwrap_or(false) { - Some((self.matcher.content_type.0.to_owned(), - self.matcher.content_type.1.to_owned())) - } else { - None - } + self.matcher.matches(data).and_then(|j| + if j < data.len() && (data[j] == b' ' || data[j] == b'>') { + Some((self.matcher.content_type.0.to_owned(), + self.matcher.content_type.1.to_owned())) + } else { + None + }) } } pub struct Mp4Matcher; @@ -219,48 +191,21 @@ impl Mp4Matcher { if data.len() < 12 { return false; } + let box_size = ((data[0] as u32) << 3 | (data[1] as u32) << 2 | (data[2] as u32) << 1 | (data[3] as u32)) as usize; if (data.len() < box_size) || (box_size % 4 != 0) { return false; } - //TODO replace with iterators + let ftyp = [0x66, 0x74, 0x79, 0x70]; - let mp4 = [0x6D, 0x70, 0x34]; - - for i in 4..8 { - if data[i] != ftyp[i - 4] { - return false; - } - } - let mut all_match = true; - for i in 8..11 { - if data[i] != mp4[i - 8] { - all_match = false; - break; - } - } - if all_match { - return true; + if !data[4..].starts_with(&ftyp) { + return false; } - let mut bytes_read: usize = 16; - - while bytes_read < box_size { - all_match = true; - for i in 0..3 { - if mp4[i] != data[i + bytes_read] { - all_match = false; - break; - } - } - if all_match { - return true; - } - - bytes_read = bytes_read + 4; - } - false + let mp4 = [0x6D, 0x70, 0x34]; + data[8..].starts_with(&mp4) || + data[16..box_size].chunks(4).any(|chunk| chunk.starts_with(&mp4)) } } @@ -278,27 +223,24 @@ struct BinaryOrPlaintextClassifier; impl BinaryOrPlaintextClassifier { fn classify_impl(&self, data: &[u8]) -> (&'static str, &'static str) { - if (data.len() >= 2 && - ((data[0] == 0xFFu8 && data[1] == 0xFEu8) || - (data[0] == 0xFEu8 && data[1] == 0xFFu8))) || - (data.len() >= 3 && data[0] == 0xEFu8 && data[1] == 0xBBu8 && data[2] == 0xBFu8) + if data == &[0xFFu8, 0xFEu8] || + data == &[0xFEu8, 0xFFu8] || + data.starts_with(&[0xEFu8, 0xBBu8, 0xBFu8]) { ("text", "plain") - } - else if data.len() >= 1 && data.iter().any(|&x| x <= 0x08u8 || - x == 0x0Bu8 || - (x >= 0x0Eu8 && x <= 0x1Au8) || - (x >= 0x1Cu8 && x <= 0x1Fu8)) { + } else if data.iter().any(|&x| x <= 0x08u8 || + x == 0x0Bu8 || + (x >= 0x0Eu8 && x <= 0x1Au8) || + (x >= 0x1Cu8 && x <= 0x1Fu8)) { ("application", "octet-stream") - } - else { + } else { ("text", "plain") } } } impl MIMEChecker for BinaryOrPlaintextClassifier { fn classify(&self, data: &[u8]) -> Option<(String, String)> { - return as_string_option(Some(self.classify_impl(data))); + as_string_option(Some(self.classify_impl(data))) } } struct GroupedClassifier { @@ -358,7 +300,6 @@ impl GroupedClassifier { box ByteMatcher::application_pdf() ] } - } fn plaintext_classifier() -> GroupedClassifier { GroupedClassifier { @@ -403,68 +344,95 @@ impl MIMEChecker for GroupedClassifier { } } +enum Match { + Start, + DidNotMatch, + StartAndEnd +} + +impl Match { + fn chain Match>(self, f: F) -> Match { + if let Match::DidNotMatch = self { + return f(); + } + self + } +} + +fn eats_until<'a, T>(matcher: &mut T, start: &[u8], end: &[u8]) -> Match +where T: Iterator + Clone { + if !matcher.matches(start) { + Match::DidNotMatch + } else if end.len() == 1 { + if matcher.any(|&x| x == end[0]) { + Match::StartAndEnd + } else { + Match::Start + } + } else { + while !matcher.matches(end) { + if matcher.next().is_none() { + return Match::Start; + } + } + Match::StartAndEnd + } +} + struct FeedsClassifier; impl FeedsClassifier { fn classify_impl(&self, data: &[u8]) -> Option<(&'static str, &'static str)> { - let length = data.len(); - let mut data_iterator = data.iter(); - - // acceptable byte sequences - let utf8_bom = &[0xEFu8, 0xBBu8, 0xBFu8]; // can not be feed unless length is > 3 - if length < 3 { + if data.len() < 3 { return None; } - // eat the first three bytes if they are equal to UTF-8 BOM - data_iterator.matches(utf8_bom); + let mut matcher = data.iter(); - // continuously search for next "<" until end of data_iterator + // eat the first three acceptable byte sequences if they are equal to UTF-8 BOM + let utf8_bom = &[0xEFu8, 0xBBu8, 0xBFu8]; + matcher.matches(utf8_bom); + + // continuously search for next "<" until end of matcher // TODO: need max_bytes to prevent inadvertently examining html document // eg. an html page with a feed example - while !data_iterator.find(|&data_iterator| *data_iterator == b'<').is_none() { + loop { - if data_iterator.matches(b"?") { - // eat until ?> - while !data_iterator.matches(b"?>") { - if data_iterator.next().is_none() { - return None; - } - } - } else if data_iterator.matches(b"!--") { - // eat until --> - while !data_iterator.matches(b"-->") { - if data_iterator.next().is_none() { - return None; - } - } - } else if data_iterator.matches(b"!") { - data_iterator.find(|&data_iterator| *data_iterator == b'>'); - } else if data_iterator.matches(b"rss") { + if matcher.find(|&x| *x == b'<').is_none() { + return None; + } + + match eats_until(&mut matcher, b"?", b"?>") + .chain(|| eats_until(&mut matcher, b"!--", b"-->")) + .chain(|| eats_until(&mut matcher, b"!", b">")) { + Match::StartAndEnd => continue, + Match::DidNotMatch => {}, + Match::Start => return None + } + + if matcher.matches(b"rss") { return Some(("application", "rss+xml")); - } else if data_iterator.matches(b"feed") { + } + if matcher.matches(b"feed") { return Some(("application", "atom+xml")); - } else if data_iterator.matches(b"rdf: RDF") { - while !data_iterator.next().is_none() { - if data_iterator.matches(b"http: //purl.org/rss/1.0/") { - while !data_iterator.next().is_none() { - if data_iterator.matches(b"http: //www.w3.org/1999/02/22-rdf-syntax-ns#") { - return Some(("application", "rss+xml")); - } - } - } else if data_iterator.matches(b"http: //www.w3.org/1999/02/22-rdf-syntax-ns#") { - while !data_iterator.next().is_none() { - if data_iterator.matches(b"http: //purl.org/rss/1.0/") { - return Some(("application", "rss+xml")); - } - } + } + if matcher.matches(b"rdf: RDF") { + while matcher.next().is_some() { + match eats_until(&mut matcher, + b"http: //purl.org/rss/1.0/", + b"http: //www.w3.org/1999/02/22-rdf-syntax-ns#") + .chain(|| eats_until(&mut matcher, + b"http: //www.w3.org/1999/02/22-rdf-syntax-ns#", + b"http: //purl.org/rss/1.0/")) { + Match::StartAndEnd => return Some(("application", "rss+xml")), + Match::DidNotMatch => {}, + Match::Start => return None } } + return None; } } - - None } } diff --git a/components/net/resource_task.rs b/components/net/resource_task.rs index 62566f71c70..d232db51bff 100644 --- a/components/net/resource_task.rs +++ b/components/net/resource_task.rs @@ -29,7 +29,6 @@ use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use std::borrow::ToOwned; use std::boxed::FnBox; use std::sync::Arc; -use std::sync::Mutex; use std::sync::mpsc::{channel, Sender}; pub enum ProgressSender { @@ -161,23 +160,26 @@ impl ResourceChannelManager { fn start(&mut self) { loop { match self.from_client.recv().unwrap() { - ControlMsg::Load(load_data, consumer) => { - self.resource_manager.load(load_data, consumer) - } - ControlMsg::SetCookiesForUrl(request, cookie_list, source) => { - self.resource_manager.set_cookies_for_url(request, cookie_list, source) - } - ControlMsg::GetCookiesForUrl(url, consumer, source) => { - consumer.send(self.resource_manager.cookie_storage.cookies_for_url(&url, source)).unwrap(); - } - ControlMsg::SetHSTSEntryForHost(host, include_subdomains, max_age) => { - if let Some(entry) = HSTSEntry::new(host, include_subdomains, Some(max_age)) { - self.resource_manager.add_hsts_entry(entry) - } - } - ControlMsg::Exit => { - break - } + ControlMsg::Load(load_data, consumer) => { + self.resource_manager.load(load_data, consumer) + } + ControlMsg::SetCookiesForUrl(request, cookie_list, source) => { + self.resource_manager.set_cookies_for_url(request, cookie_list, source) + } + ControlMsg::GetCookiesForUrl(url, consumer, source) => { + consumer.send(self.resource_manager.cookie_storage.cookies_for_url(&url, source)).unwrap(); + } + ControlMsg::SetHSTSEntryForHost(host, include_subdomains, max_age) => { + if let Some(entry) = HSTSEntry::new(host, include_subdomains, Some(max_age)) { + self.resource_manager.add_hsts_entry(entry) + } + } + ControlMsg::GetHostMustBeSecured(host, consumer) => { + consumer.send(self.resource_manager.is_host_sts(&*host)).unwrap(); + } + ControlMsg::Exit => { + break + } } } } @@ -189,7 +191,7 @@ pub struct ResourceManager { resource_task: IpcSender, mime_classifier: Arc, devtools_chan: Option>, - hsts_list: Arc> + hsts_list: HSTSList } impl ResourceManager { @@ -203,7 +205,7 @@ impl ResourceManager { resource_task: resource_task, mime_classifier: Arc::new(MIMEClassifier::new()), devtools_chan: devtools_channel, - hsts_list: Arc::new(Mutex::new(hsts_list)) + hsts_list: hsts_list } } } @@ -221,11 +223,11 @@ impl ResourceManager { } pub fn add_hsts_entry(&mut self, entry: HSTSEntry) { - self.hsts_list.lock().unwrap().push(entry); + self.hsts_list.push(entry); } pub fn is_host_sts(&self, host: &str) -> bool { - self.hsts_list.lock().unwrap().is_host_secure(host) + self.hsts_list.is_host_secure(host) } fn load(&mut self, mut load_data: LoadData, consumer: LoadConsumer) { @@ -241,7 +243,7 @@ impl ResourceManager { let loader = match &*load_data.url.scheme { "file" => from_factory(file_loader::factory), "http" | "https" | "view-source" => - http_loader::factory(self.resource_task.clone(), self.devtools_chan.clone(), self.hsts_list.clone()), + http_loader::factory(self.resource_task.clone(), self.devtools_chan.clone()), "data" => from_factory(data_loader::factory), "about" => from_factory(about_loader::factory), _ => { diff --git a/components/net_traits/lib.rs b/components/net_traits/lib.rs index e4a93f56673..3f9db2a7ebc 100644 --- a/components/net_traits/lib.rs +++ b/components/net_traits/lib.rs @@ -161,6 +161,7 @@ pub enum ControlMsg { GetCookiesForUrl(Url, IpcSender>, CookieSource), /// Store a domain's STS information SetHSTSEntryForHost(String, IncludeSubdomains, u64), + GetHostMustBeSecured(String, IpcSender), Exit } diff --git a/components/plugins/jstraceable.rs b/components/plugins/jstraceable.rs index 035c50d5e46..2dfd4305c9d 100644 --- a/components/plugins/jstraceable.rs +++ b/components/plugins/jstraceable.rs @@ -17,6 +17,7 @@ pub fn expand_dom_struct(cx: &mut ExtCtxt, sp: Span, _: &MetaItem, anno: Annotat item2.attrs.push(quote_attr!(cx, #[must_root])); item2.attrs.push(quote_attr!(cx, #[privatize])); item2.attrs.push(quote_attr!(cx, #[derive(JSTraceable)])); + item2.attrs.push(quote_attr!(cx, #[derive(HeapSizeOf)])); // The following attributes are only for internal usage item2.attrs.push(quote_attr!(cx, #[_generate_reflector])); diff --git a/components/plugins/utils.rs b/components/plugins/utils.rs index 79025c33f70..e26cc4bc7cd 100644 --- a/components/plugins/utils.rs +++ b/components/plugins/utils.rs @@ -17,14 +17,14 @@ use syntax::ptr::P; /// Try not to use this for types defined in crates you own, use match_lang_ty instead (for lint passes) pub fn match_ty_unwrap<'a>(ty: &'a Ty, segments: &[&str]) -> Option<&'a [P]> { match ty.node { - TyPath(_, Path {segments: ref seg, ..}) => { + TyPath(_, Path { segments: ref seg, .. }) => { // So ast::Path isn't the full path, just the tokens that were provided. // I could muck around with the maps and find the full path // however the more efficient way is to simply reverse the iterators and zip them // which will compare them in reverse until one of them runs out of segments if seg.iter().rev().zip(segments.iter().rev()).all(|(a, b)| a.identifier.name.as_str() == *b) { match seg.last() { - Some(&PathSegment {parameters: AngleBracketedParameters(ref a), ..}) => { + Some(&PathSegment { parameters: AngleBracketedParameters(ref a), .. }) => { Some(&a.types) } _ => None diff --git a/components/profile/lib.rs b/components/profile/lib.rs index 9bf2018f4be..635b9af083f 100644 --- a/components/profile/lib.rs +++ b/components/profile/lib.rs @@ -13,9 +13,9 @@ extern crate ipc_channel; extern crate libc; #[macro_use] extern crate profile_traits; -#[cfg(target_os="linux")] +#[cfg(target_os = "linux")] extern crate regex; -#[cfg(target_os="macos")] +#[cfg(target_os = "macos")] extern crate task_info; extern crate time as std_time; extern crate util; diff --git a/components/profile/mem.rs b/components/profile/mem.rs index dae86a535fd..8b1e7b1397d 100644 --- a/components/profile/mem.rs +++ b/components/profile/mem.rs @@ -368,7 +368,7 @@ mod system_reporter { use std::mem::size_of; use std::ptr::null_mut; use super::{JEMALLOC_HEAP_ALLOCATED_STR, SYSTEM_HEAP_ALLOCATED_STR}; - #[cfg(target_os="macos")] + #[cfg(target_os = "macos")] use task_info::task_basic_info::{virtual_size, resident_size}; /// Collects global measurements from the OS and heap allocators. @@ -418,12 +418,12 @@ mod system_reporter { request.reports_channel.send(reports); } - #[cfg(target_os="linux")] + #[cfg(target_os = "linux")] extern { fn mallinfo() -> struct_mallinfo; } - #[cfg(target_os="linux")] + #[cfg(target_os = "linux")] #[repr(C)] pub struct struct_mallinfo { arena: c_int, @@ -438,7 +438,7 @@ mod system_reporter { keepcost: c_int, } - #[cfg(target_os="linux")] + #[cfg(target_os = "linux")] fn get_system_heap_allocated() -> Option { let info: struct_mallinfo = unsafe { mallinfo() }; @@ -457,7 +457,7 @@ mod system_reporter { } } - #[cfg(not(target_os="linux"))] + #[cfg(not(target_os = "linux"))] fn get_system_heap_allocated() -> Option { None } @@ -507,14 +507,14 @@ mod system_reporter { ($e:expr) => (match $e { Some(e) => e, None => return None }) ); - #[cfg(target_os="linux")] + #[cfg(target_os = "linux")] fn page_size() -> usize { unsafe { ::libc::sysconf(::libc::_SC_PAGESIZE) as usize } } - #[cfg(target_os="linux")] + #[cfg(target_os = "linux")] fn get_proc_self_statm_field(field: usize) -> Option { use std::fs::File; use std::io::Read; @@ -527,37 +527,37 @@ mod system_reporter { Some(npages * page_size()) } - #[cfg(target_os="linux")] + #[cfg(target_os = "linux")] fn get_vsize() -> Option { get_proc_self_statm_field(0) } - #[cfg(target_os="linux")] + #[cfg(target_os = "linux")] fn get_resident() -> Option { get_proc_self_statm_field(1) } - #[cfg(target_os="macos")] + #[cfg(target_os = "macos")] fn get_vsize() -> Option { virtual_size() } - #[cfg(target_os="macos")] + #[cfg(target_os = "macos")] fn get_resident() -> Option { resident_size() } - #[cfg(not(any(target_os="linux", target_os = "macos")))] + #[cfg(not(any(target_os = "linux", target_os = "macos")))] fn get_vsize() -> Option { None } - #[cfg(not(any(target_os="linux", target_os = "macos")))] + #[cfg(not(any(target_os = "linux", target_os = "macos")))] fn get_resident() -> Option { None } - #[cfg(target_os="linux")] + #[cfg(target_os = "linux")] fn get_resident_segments() -> Vec<(String, usize)> { use regex::Regex; use std::collections::HashMap; @@ -658,7 +658,7 @@ mod system_reporter { segs } - #[cfg(not(target_os="linux"))] + #[cfg(not(target_os = "linux"))] fn get_resident_segments() -> Vec<(String, usize)> { vec![] } diff --git a/components/script/Cargo.toml b/components/script/Cargo.toml index e52594d8c15..aa8967a62ae 100644 --- a/components/script/Cargo.toml +++ b/components/script/Cargo.toml @@ -55,6 +55,10 @@ features = ["query_encoding", "serde_serialization"] [dependencies.offscreen_gl_context] git = "https://github.com/ecoal95/rust-offscreen-rendering-context" +[dependencies.angle] +git = "https://github.com/ecoal95/angle" +branch = "servo" + [dependencies.cssparser] version = "0.3" features = [ "serde-serialization" ] diff --git a/components/script/devtools.rs b/components/script/devtools.rs index d2feb56674e..6c843e9e9eb 100644 --- a/components/script/devtools.rs +++ b/components/script/devtools.rs @@ -13,9 +13,7 @@ use dom::bindings::conversions::FromJSValConvertible; use dom::bindings::conversions::jsstring_to_str; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; -use dom::document::DocumentHelpers; -use dom::node::{Node, NodeHelpers}; -use dom::window::{WindowHelpers, ScriptHelpers}; +use dom::node::Node; use ipc_channel::ipc::IpcSender; use js::jsapi::{ObjectClassName, RootedObject, RootedValue}; use js::jsval::UndefinedValue; diff --git a/components/script/dom/activation.rs b/components/script/dom/activation.rs index 67dc0f1b731..441871f9abe 100644 --- a/components/script/dom/activation.rs +++ b/components/script/dom/activation.rs @@ -4,8 +4,8 @@ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast}; -use dom::element::{Element, ActivationElementHelpers}; -use dom::event::{Event, EventHelpers, EventBubbles, EventCancelable}; +use dom::element::Element; +use dom::event::{Event, EventBubbles, EventCancelable}; use dom::eventtarget::EventTarget; use dom::mouseevent::MouseEvent; use dom::node::window_from_node; diff --git a/components/script/dom/attr.rs b/components/script/dom/attr.rs index 3df9265580e..e1baff2bffd 100644 --- a/components/script/dom/attr.rs +++ b/components/script/dom/attr.rs @@ -9,7 +9,7 @@ use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutNullableHeap}; use dom::bindings::js::{Root, RootedReference, LayoutJS}; use dom::bindings::utils::{Reflector, reflect_dom_object}; -use dom::element::{Element, AttributeHandlers}; +use dom::element::Element; use dom::virtualmethods::vtable_for; use dom::window::Window; @@ -111,7 +111,6 @@ impl Deref for AttrValue { // https://dom.spec.whatwg.org/#interface-attr #[dom_struct] -#[derive(HeapSizeOf)] pub struct Attr { reflector_: Reflector, local_name: Atom, @@ -163,19 +162,19 @@ impl Attr { } } -impl<'a> AttrMethods for &'a Attr { +impl AttrMethods for Attr { // https://dom.spec.whatwg.org/#dom-attr-localname - fn LocalName(self) -> DOMString { + fn LocalName(&self) -> DOMString { (**self.local_name()).to_owned() } // https://dom.spec.whatwg.org/#dom-attr-value - fn Value(self) -> DOMString { + fn Value(&self) -> DOMString { (**self.value()).to_owned() } // https://dom.spec.whatwg.org/#dom-attr-value - fn SetValue(self, value: DOMString) { + fn SetValue(&self, value: DOMString) { match self.owner() { None => *self.value.borrow_mut() = AttrValue::String(value), Some(owner) => { @@ -186,32 +185,32 @@ impl<'a> AttrMethods for &'a Attr { } // https://dom.spec.whatwg.org/#dom-attr-textcontent - fn TextContent(self) -> DOMString { + fn TextContent(&self) -> DOMString { self.Value() } // https://dom.spec.whatwg.org/#dom-attr-textcontent - fn SetTextContent(self, value: DOMString) { + fn SetTextContent(&self, value: DOMString) { self.SetValue(value) } // https://dom.spec.whatwg.org/#dom-attr-nodevalue - fn NodeValue(self) -> DOMString { + fn NodeValue(&self) -> DOMString { self.Value() } // https://dom.spec.whatwg.org/#dom-attr-nodevalue - fn SetNodeValue(self, value: DOMString) { + fn SetNodeValue(&self, value: DOMString) { self.SetValue(value) } // https://dom.spec.whatwg.org/#dom-attr-name - fn Name(self) -> DOMString { + fn Name(&self) -> DOMString { (*self.name).to_owned() } // https://dom.spec.whatwg.org/#dom-attr-namespaceuri - fn GetNamespaceURI(self) -> Option { + fn GetNamespaceURI(&self) -> Option { let Namespace(ref atom) = self.namespace; match &**atom { "" => None, @@ -220,32 +219,24 @@ impl<'a> AttrMethods for &'a Attr { } // https://dom.spec.whatwg.org/#dom-attr-prefix - fn GetPrefix(self) -> Option { + fn GetPrefix(&self) -> Option { self.prefix().as_ref().map(|p| (**p).to_owned()) } // https://dom.spec.whatwg.org/#dom-attr-ownerelement - fn GetOwnerElement(self) -> Option> { + fn GetOwnerElement(&self) -> Option> { self.owner() } // https://dom.spec.whatwg.org/#dom-attr-specified - fn Specified(self) -> bool { + fn Specified(&self) -> bool { true // Always returns true } } -pub trait AttrHelpers<'a> { - fn set_value(self, set_type: AttrSettingType, value: AttrValue, owner: &Element); - fn value(self) -> Ref<'a, AttrValue>; - fn local_name(self) -> &'a Atom; - fn set_owner(self, owner: Option<&Element>); - fn owner(self) -> Option>; - fn summarize(self) -> AttrInfo; -} -impl<'a> AttrHelpers<'a> for &'a Attr { - fn set_value(self, set_type: AttrSettingType, value: AttrValue, owner: &Element) { +impl Attr { + pub fn set_value(&self, set_type: AttrSettingType, value: AttrValue, owner: &Element) { assert!(Some(owner) == self.owner().r()); let node = NodeCast::from_ref(owner); @@ -264,17 +255,17 @@ impl<'a> AttrHelpers<'a> for &'a Attr { } } - fn value(self) -> Ref<'a, AttrValue> { + pub fn value(&self) -> Ref { self.value.borrow() } - fn local_name(self) -> &'a Atom { + pub fn local_name(&self) -> &Atom { &self.local_name } /// Sets the owner element. Should be called after the attribute is added /// or removed from its older parent. - fn set_owner(self, owner: Option<&Element>) { + pub fn set_owner(&self, owner: Option<&Element>) { let ref ns = self.namespace; match (self.owner().r(), owner) { (None, Some(new)) => { @@ -290,11 +281,11 @@ impl<'a> AttrHelpers<'a> for &'a Attr { self.owner.set(owner.map(JS::from_ref)) } - fn owner(self) -> Option> { + pub fn owner(&self) -> Option> { self.owner.get().map(Root::from_rooted) } - fn summarize(self) -> AttrInfo { + pub fn summarize(&self) -> AttrInfo { let Namespace(ref ns) = self.namespace; AttrInfo { namespace: (**ns).to_owned(), diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index c8eda80834f..08370974cca 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -339,7 +339,7 @@ class CGMethodCall(CGThing): code = ( "if argc < %d {\n" " throw_type_error(cx, \"Not enough arguments to %s.\");\n" - " return 0;\n" + " return JSFalse;\n" "}" % (requiredArgs, methodName)) self.cgRoot.prepend( CGWrapper(CGGeneric(code), pre="\n", post="\n")) @@ -512,11 +512,11 @@ class CGMethodCall(CGThing): CGSwitch("argcount", argCountCases, CGGeneric("throw_type_error(cx, \"Not enough arguments to %s.\");\n" - "return 0;" % methodName))) + "return JSFalse;" % methodName))) # XXXjdm Avoid unreachable statement warnings # overloadCGThings.append( # CGGeneric('panic!("We have an always-returning default case");\n' - # 'return 0;')) + # 'return JSFalse;')) self.cgRoot = CGWrapper(CGList(overloadCGThings, "\n"), pre="\n") @@ -888,7 +888,11 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, if invalidEnumValueFatal: handleInvalidEnumValueCode = exceptionCode else: - handleInvalidEnumValueCode = "return 1;" + handleInvalidEnumValueCode = "return JSTrue;" + + transmute = "mem::transmute(index)" + if isMember == 'Dictionary': + transmute = 'unsafe { ' + transmute + ' }' template = ( "match find_enum_string_index(cx, ${val}, %(values)s) {\n" @@ -896,10 +900,11 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, " Ok(None) => { %(handleInvalidEnumValueCode)s },\n" " Ok(Some(index)) => {\n" " //XXXjdm need some range checks up in here.\n" - " unsafe { mem::transmute(index) }\n" + " %(transmute)s\n" " },\n" "}" % {"values": enum + "Values::strings", "exceptionCode": exceptionCode, + "transmute": transmute, "handleInvalidEnumValueCode": handleInvalidEnumValueCode}) if defaultValue is not None: @@ -1012,7 +1017,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, declType = CGGeneric(typeName) template = ("match %s::new(cx, ${val}) {\n" " Ok(dictionary) => dictionary,\n" - " Err(_) => return 0,\n" + " Err(_) => return JSFalse,\n" "}" % typeName) return handleOptional(template, declType, handleDefaultNull("%s::empty(cx)" % typeName)) @@ -1037,7 +1042,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, conversionBehavior = "()" if failureCode is None: - failureCode = 'return 0' + failureCode = 'return JSFalse' declType = CGGeneric(builtinNames[type.tag()]) if type.nullable(): @@ -1216,7 +1221,7 @@ class CGArgumentConverter(CGThing): return self.converter.define() -def wrapForType(jsvalRef, result='result', successCode='return 1;', pre=''): +def wrapForType(jsvalRef, result='result', successCode='return JSTrue;', pre=''): """ Reflect a Rust value into JS. @@ -1472,6 +1477,7 @@ class AttrDefiner(PropertyDefiner): def __init__(self, descriptor, name, static): PropertyDefiner.__init__(self, descriptor, name) self.name = name + self.descriptor = descriptor self.regular = [ m for m in descriptor.interface.members @@ -1488,14 +1494,14 @@ class AttrDefiner(PropertyDefiner): def getter(attr): if self.static: - accessor = 'get_' + attr.identifier.name + accessor = 'get_' + self.descriptor.internalNameFor(attr.identifier.name) jitinfo = "0 as *const JSJitInfo" else: if attr.hasLenientThis(): accessor = "generic_lenient_getter" else: accessor = "generic_getter" - jitinfo = "&%s_getterinfo" % attr.identifier.name + jitinfo = "&%s_getterinfo" % self.descriptor.internalNameFor(attr.identifier.name) return ("JSNativeWrapper { op: Some(%(native)s), info: %(info)s }" % {"info": jitinfo, @@ -1506,14 +1512,14 @@ class AttrDefiner(PropertyDefiner): return "JSNativeWrapper { op: None, info: 0 as *const JSJitInfo }" if self.static: - accessor = 'set_' + attr.identifier.name + accessor = 'set_' + self.descriptor.internalNameFor(attr.identifier.name) jitinfo = "0 as *const JSJitInfo" else: if attr.hasLenientThis(): accessor = "generic_lenient_setter" else: accessor = "generic_setter" - jitinfo = "&%s_setterinfo" % attr.identifier.name + jitinfo = "&%s_setterinfo" % self.descriptor.internalNameFor(attr.identifier.name) return ("JSNativeWrapper { op: Some(%(native)s), info: %(info)s }" % {"info": jitinfo, @@ -1620,19 +1626,11 @@ class CGImports(CGWrapper): """ if ignored_warnings is None: ignored_warnings = [ - # Allow unreachable_code because we use 'break' in a way that - # sometimes produces two 'break's in a row. See for example - # CallbackMember.getArgConversions. - 'unreachable_code', 'non_camel_case_types', 'non_upper_case_globals', - 'unused_parens', 'unused_imports', 'unused_variables', - 'unused_unsafe', - 'unused_mut', 'unused_assignments', - 'dead_code', ] def componentTypes(type): @@ -2049,7 +2047,7 @@ class CGAbstractMethod(CGThing): """ def __init__(self, descriptor, name, returnType, args, inline=False, alwaysInline=False, extern=False, pub=False, templateArgs=None, - unsafe=True): + unsafe=False): CGThing.__init__(self) self.descriptor = descriptor self.name = name @@ -2111,7 +2109,7 @@ class CGAbstractMethod(CGThing): def CreateBindingJSObject(descriptor, parent=None): - create = "let mut raw = Box::into_raw(object);\nlet _rt = RootedTraceable::new(&*raw);\n" + create = "let raw = Box::into_raw(object);\nlet _rt = RootedTraceable::new(&*raw);\n" if descriptor.proxy: assert not descriptor.isGlobal() create += """ @@ -2160,12 +2158,13 @@ class CGWrapMethod(CGAbstractMethod): assert not descriptor.interface.isCallback() if not descriptor.isGlobal(): args = [Argument('*mut JSContext', 'cx'), Argument('GlobalRef', 'scope'), - Argument("Box<%s>" % descriptor.concreteType, 'object', mutable=True)] + Argument("Box<%s>" % descriptor.concreteType, 'object')] else: args = [Argument('*mut JSContext', 'cx'), - Argument("Box<%s>" % descriptor.concreteType, 'object', mutable=True)] + Argument("Box<%s>" % descriptor.concreteType, 'object')] retval = 'Root<%s>' % descriptor.concreteType - CGAbstractMethod.__init__(self, descriptor, 'Wrap', retval, args, pub=True) + CGAbstractMethod.__init__(self, descriptor, 'Wrap', retval, args, + pub=True, unsafe=True) def definition_body(self): if not self.descriptor.isGlobal(): @@ -2309,6 +2308,7 @@ class CGCreateInterfaceObjectsMethod(CGAbstractMethod): def definition_body(self): protoChain = self.descriptor.prototypeChain if len(protoChain) == 1: + self.unsafe = True getParentProto = "parent_proto.ptr = JS_GetObjectPrototype(cx, global)" else: parentProtoName = self.descriptor.prototypeChain[-2] @@ -2382,7 +2382,7 @@ class CGGetPerInterfaceObject(CGAbstractMethod): Argument('HandleObject', 'receiver'), Argument('MutableHandleObject', 'rval')] CGAbstractMethod.__init__(self, descriptor, name, - 'void', args, pub=pub) + 'void', args, pub=pub, unsafe=True) self.id = idPrefix + "ID::" + self.descriptor.name def definition_body(self): @@ -2452,7 +2452,9 @@ class CGDefineProxyHandler(CGAbstractMethod): """ def __init__(self, descriptor): assert descriptor.proxy - CGAbstractMethod.__init__(self, descriptor, 'DefineProxyHandler', '*const libc::c_void', [], pub=True) + CGAbstractMethod.__init__(self, descriptor, 'DefineProxyHandler', + '*const libc::c_void', [], + pub=True, unsafe=True) def define(self): return CGAbstractMethod.define(self) @@ -2778,7 +2780,7 @@ class CGSetterCall(CGPerSignatureCall): def wrap_return_value(self): # We have no return value - return "\nreturn 1;" + return "\nreturn JSTrue;" def getArgc(self): return "1" @@ -2835,7 +2837,10 @@ class CGSpecializedMethod(CGAbstractExternMethod): @staticmethod def makeNativeName(descriptor, method): name = method.identifier.name - return MakeNativeName(descriptor.binaryNameFor(name)) + nativeName = descriptor.binaryNameFor(name) + if nativeName == name: + nativeName = descriptor.internalNameFor(name) + return MakeNativeName(nativeName) class CGStaticMethod(CGAbstractStaticBindingMethod): @@ -2850,7 +2855,7 @@ class CGStaticMethod(CGAbstractStaticBindingMethod): def generate_code(self): nativeName = CGSpecializedMethod.makeNativeName(self.descriptor, self.method) - setupArgs = CGGeneric("let mut args = CallArgs::from_vp(vp, argc);\n") + setupArgs = CGGeneric("let args = CallArgs::from_vp(vp, argc);\n") call = CGMethodCall(["global.r()"], nativeName, True, self.descriptor, self.method) return CGList([setupArgs, call]) @@ -2862,7 +2867,7 @@ class CGSpecializedGetter(CGAbstractExternMethod): """ def __init__(self, descriptor, attr): self.attr = attr - name = 'get_' + attr.identifier.name + name = 'get_' + descriptor.internalNameFor(attr.identifier.name) args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', '_obj'), Argument('*const %s' % descriptor.concreteType, 'this'), @@ -2880,7 +2885,10 @@ class CGSpecializedGetter(CGAbstractExternMethod): @staticmethod def makeNativeName(descriptor, attr): name = attr.identifier.name - nativeName = MakeNativeName(descriptor.binaryNameFor(name)) + nativeName = descriptor.binaryNameFor(name) + if nativeName == name: + nativeName = descriptor.internalNameFor(name) + nativeName = MakeNativeName(nativeName) infallible = ('infallible' in descriptor.getExtendedAttributes(attr, getter=True)) if attr.type.nullable() or not infallible: @@ -2901,7 +2909,7 @@ class CGStaticGetter(CGAbstractStaticBindingMethod): def generate_code(self): nativeName = CGSpecializedGetter.makeNativeName(self.descriptor, self.attr) - setupArgs = CGGeneric("let mut args = CallArgs::from_vp(vp, argc);\n") + setupArgs = CGGeneric("let args = CallArgs::from_vp(vp, argc);\n") call = CGGetterCall(["global.r()"], self.attr.type, nativeName, self.descriptor, self.attr) return CGList([setupArgs, call]) @@ -2914,7 +2922,7 @@ class CGSpecializedSetter(CGAbstractExternMethod): """ def __init__(self, descriptor, attr): self.attr = attr - name = 'set_' + attr.identifier.name + name = 'set_' + descriptor.internalNameFor(attr.identifier.name) args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'obj'), Argument('*const %s' % descriptor.concreteType, 'this'), @@ -2931,7 +2939,10 @@ class CGSpecializedSetter(CGAbstractExternMethod): @staticmethod def makeNativeName(descriptor, attr): name = attr.identifier.name - return "Set" + MakeNativeName(descriptor.binaryNameFor(name)) + nativeName = descriptor.binaryNameFor(name) + if nativeName == name: + nativeName = descriptor.internalNameFor(name) + return "Set" + MakeNativeName(nativeName) class CGStaticSetter(CGAbstractStaticBindingMethod): @@ -2948,9 +2959,9 @@ class CGStaticSetter(CGAbstractStaticBindingMethod): self.attr) checkForArg = CGGeneric( "let args = CallArgs::from_vp(vp, argc);\n" - "if (argc == 0) {\n" + "if argc == 0 {\n" " throw_type_error(cx, \"Not enough arguments to %s setter.\");\n" - " return 0;\n" + " return JSFalse;\n" "}" % self.attr.identifier.name) call = CGSetterCall(["global.r()"], self.attr.type, nativeName, self.descriptor, self.attr) @@ -3045,8 +3056,9 @@ class CGMemberJITInfo(CGThing): def define(self): if self.member.isAttr(): - getterinfo = ("%s_getterinfo" % self.member.identifier.name) - getter = ("get_%s" % self.member.identifier.name) + internalMemberName = self.descriptor.internalNameFor(self.member.identifier.name) + getterinfo = ("%s_getterinfo" % internalMemberName) + getter = ("get_%s" % internalMemberName) getterinfal = "infallible" in self.descriptor.getExtendedAttributes(self.member, getter=True) movable = self.mayBeMovable() and getterinfal @@ -3070,8 +3082,8 @@ class CGMemberJITInfo(CGThing): slotIndex, [self.member.type], None) if (not self.member.readonly or self.member.getExtendedAttribute("PutForwards")): - setterinfo = ("%s_setterinfo" % self.member.identifier.name) - setter = ("set_%s" % self.member.identifier.name) + setterinfo = ("%s_setterinfo" % internalMemberName) + setter = ("set_%s" % internalMemberName) # Setters are always fallible, since they have to do a typed unwrap. result += self.defineJitInfo(setterinfo, setter, "Setter", False, False, "AliasEverything", @@ -3966,7 +3978,23 @@ class CGProxyIndexedSetter(CGProxySpecialOperation): CGProxySpecialOperation.__init__(self, descriptor, 'IndexedSetter') -class CGProxyNamedGetter(CGProxySpecialOperation): +class CGProxyNamedOperation(CGProxySpecialOperation): + """ + Class to generate a call to a named operation. + """ + def __init__(self, descriptor, name): + CGProxySpecialOperation.__init__(self, descriptor, name) + + def define(self): + # Our first argument is the id we're getting. + argName = self.arguments[0].identifier.name + return ("let %s = jsid_to_str(cx, id);\n" + "let this = UnwrapProxy(proxy);\n" + "let this = &*this;\n" % argName + + CGProxySpecialOperation.define(self)) + + +class CGProxyNamedGetter(CGProxyNamedOperation): """ Class to generate a call to an named getter. If templateValues is not None the returned value will be wrapped with wrapForType using templateValues. @@ -3976,7 +4004,16 @@ class CGProxyNamedGetter(CGProxySpecialOperation): CGProxySpecialOperation.__init__(self, descriptor, 'NamedGetter') -class CGProxyNamedSetter(CGProxySpecialOperation): +class CGProxyNamedPresenceChecker(CGProxyNamedGetter): + """ + Class to generate a call that checks whether a named property exists. + For now, we just delegate to CGProxyNamedGetter + """ + def __init__(self, descriptor): + CGProxyNamedGetter.__init__(self, descriptor) + + +class CGProxyNamedSetter(CGProxyNamedOperation): """ Class to generate a call to a named setter. """ @@ -3984,7 +4021,7 @@ class CGProxyNamedSetter(CGProxySpecialOperation): CGProxySpecialOperation.__init__(self, descriptor, 'NamedSetter') -class CGProxyNamedDeleter(CGProxySpecialOperation): +class CGProxyNamedDeleter(CGProxyNamedOperation): """ Class to generate a call to a named deleter. """ @@ -3996,7 +4033,8 @@ class CGProxyUnwrap(CGAbstractMethod): def __init__(self, descriptor): args = [Argument('HandleObject', 'obj')] CGAbstractMethod.__init__(self, descriptor, "UnwrapProxy", - '*const ' + descriptor.concreteType, args, alwaysInline=True) + '*const ' + descriptor.concreteType, args, + alwaysInline=True, unsafe=True) def definition_body(self): return CGGeneric("""\ @@ -4057,9 +4095,6 @@ class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): # properties that shadow prototype properties. namedGet = ("\n" + "if RUST_JSID_IS_STRING(id) != 0 && !has_property_on_prototype(cx, proxy, id) {\n" + - " let name = jsid_to_str(cx, id);\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = &*this;\n" + CGIndenter(CGProxyNamedGetter(self.descriptor, templateValues)).define() + "\n" + "}\n") else: @@ -4121,9 +4156,6 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): if not self.descriptor.operations['NamedCreator'] is namedSetter: raise TypeError("Can't handle creator that's different from the setter") set += ("if RUST_JSID_IS_STRING(id) != 0 {\n" + - " let name = jsid_to_str(cx, id);\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = &*this;\n" + CGIndenter(CGProxyNamedSetter(self.descriptor)).define() + " (*opresult).code_ = 0; /* SpecialCodes::OkCode */\n" + " return JSTrue;\n" + @@ -4132,9 +4164,6 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod): "}\n") else: set += ("if RUST_JSID_IS_STRING(id) != 0 {\n" + - " let name = jsid_to_str(cx, id);\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = &*this;\n" + CGIndenter(CGProxyNamedGetter(self.descriptor)).define() + " if (found) {\n" # TODO(Issue 5876) @@ -4165,10 +4194,7 @@ class CGDOMJSProxyHandler_delete(CGAbstractExternMethod): def getBody(self): set = "" if self.descriptor.operations['NamedDeleter']: - set += ("let name = jsid_to_str(cx, id);\n" + - "let this = UnwrapProxy(proxy);\n" + - "let this = &*this;\n" + - "%s") % (CGProxyNamedDeleter(self.descriptor).define()) + set += CGProxyNamedDeleter(self.descriptor).define() set += "return proxyhandler::delete(%s) as u8;" % ", ".join(a.name for a in self.args) return set @@ -4205,7 +4231,7 @@ class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod): for name in (*unwrapped_proxy).SupportedPropertyNames() { let cstring = CString::new(name).unwrap(); let jsstring = JS_InternString(cx, cstring.as_ptr()); - let mut rooted = RootedString::new(cx, jsstring); + let rooted = RootedString::new(cx, jsstring); let jsid = INTERNED_STRING_TO_JSID(cx, rooted.handle().get()); let rooted_jsid = RootedId::new(cx, jsid); AppendToAutoIdVector(props, rooted_jsid.handle().get()); @@ -4253,9 +4279,6 @@ class CGDOMJSProxyHandler_hasOwn(CGAbstractExternMethod): namedGetter = self.descriptor.operations['NamedGetter'] if namedGetter: named = ("if RUST_JSID_IS_STRING(id) != 0 && !has_property_on_prototype(cx, proxy, id) {\n" + - " let name = jsid_to_str(cx, id);\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = &*this;\n" + CGIndenter(CGProxyNamedGetter(self.descriptor)).define() + "\n" + " *bp = found as u8;\n" " return JSTrue;\n" @@ -4328,10 +4351,7 @@ if !expando.ptr.is_null() { namedGetter = self.descriptor.operations['NamedGetter'] if namedGetter: - getNamed = ("if (RUST_JSID_IS_STRING(id) != 0) {\n" + - " let name = jsid_to_str(cx, id);\n" + - " let this = UnwrapProxy(proxy);\n" + - " let this = &*this;\n" + + getNamed = ("if RUST_JSID_IS_STRING(id) != 0 {\n" + CGIndenter(CGProxyNamedGetter(self.descriptor, templateValues)).define() + "}\n") else: @@ -4564,7 +4584,7 @@ class CGInterfaceTrait(CGThing): return "".join(", %s: %s" % argument for argument in arguments) methods = [ - CGGeneric("fn %s(self%s) -> %s;\n" % (name, fmt(arguments), rettype)) + CGGeneric("fn %s(&self%s) -> %s;\n" % (name, fmt(arguments), rettype)) for name, arguments, rettype in members() ] if methods: @@ -5499,7 +5519,7 @@ class CallbackMember(CGNativeMember): conversion = ( CGIfWrapper(CGGeneric(conversion), "%s.is_some()" % arg.identifier.name).define() + - " else if (argc == %d) {\n" + " else if argc == %d {\n" " // This is our current trailing argument; reduce argc\n" " argc -= 1;\n" "} else {\n" @@ -5532,6 +5552,8 @@ class CallbackMember(CGNativeMember): "}\n") def getArgcDecl(self): + if self.argCount <= 1: + return CGGeneric("let argc = %s;" % self.argCountStr) return CGGeneric("let mut argc = %s;" % self.argCountStr) @staticmethod @@ -5773,12 +5795,17 @@ class GlobalGenRoots(): CGGeneric("use std::mem;\n\n")] for descriptor in descriptors: name = descriptor.name - protos = [CGGeneric('pub trait %s : Sized {}\n' % (name + 'Base'))] + protos = [CGGeneric("""\ +/// Types which are derived from `%(name)s` and can be freely converted +/// to `%(name)s` +pub trait %(name)sBase : Sized {}\n""" % {'name': name})] for proto in descriptor.prototypeChain: protos += [CGGeneric('impl %s for %s {}\n' % (proto + 'Base', descriptor.concreteType))] - derived = [CGGeneric('pub trait %s : Sized { fn %s(&self) -> bool; }\n' % - (name + 'Derived', 'is_' + name.lower()))] + derived = [CGGeneric("""\ +/// Types which `%(name)s` derives from +pub trait %(name)sDerived : Sized { fn %(method)s(&self) -> bool; }\n""" % + {'name': name, 'method': 'is_' + name.lower()})] for protoName in descriptor.prototypeChain[1:-1]: protoDescriptor = config.getDescriptor(protoName) delegate = string.Template("""\ @@ -5800,6 +5827,8 @@ impl ${selfName} for ${baseName} { pub struct ${name}Cast; impl ${name}Cast { #[inline] + /// Downcast an instance of a base class of `${name}` to an instance of + /// `${name}`, if it internally is an instance of `${name}` pub fn to_ref<'a, T: ${toBound}+Reflectable>(base: &'a T) -> Option<&'a ${name}> { match base.${checkFn}() { true => Some(unsafe { mem::transmute(base) }), @@ -5807,14 +5836,6 @@ impl ${name}Cast { } } - #[inline] - pub fn to_borrowed_ref<'a, 'b, T: ${toBound}+Reflectable>(base: &'a &'b T) -> Option<&'a &'b ${name}> { - match base.${checkFn}() { - true => Some(unsafe { mem::transmute(base) }), - false => None - } - } - #[inline] #[allow(unrooted_must_root)] pub fn to_layout_js(base: &LayoutJS) -> Option> { @@ -5835,15 +5856,11 @@ impl ${name}Cast { } #[inline] + /// Upcast an instance of a derived class of `${name}` to `${name}` pub fn from_ref<'a, T: ${fromBound}+Reflectable>(derived: &'a T) -> &'a ${name} { unsafe { mem::transmute(derived) } } - #[inline] - pub fn from_borrowed_ref<'a, 'b, T: ${fromBound}+Reflectable>(derived: &'a &'b T) -> &'a &'b ${name} { - unsafe { mem::transmute(derived) } - } - #[inline] #[allow(unrooted_must_root)] pub fn from_layout_js(derived: &LayoutJS) -> LayoutJS<${name}> { diff --git a/components/script/dom/bindings/codegen/Configuration.py b/components/script/dom/bindings/codegen/Configuration.py index 4e740f83a16..1a88968619b 100644 --- a/components/script/dom/bindings/codegen/Configuration.py +++ b/components/script/dom/bindings/codegen/Configuration.py @@ -263,6 +263,8 @@ class Descriptor(DescriptorProvider): self._binaryNames.setdefault('__legacycaller', 'LegacyCall') self._binaryNames.setdefault('__stringifier', 'Stringifier') + self._internalNames = desc.get('internalNames', {}) + for member in self.interface.members: if not member.isAttr() and not member.isMethod(): continue @@ -272,6 +274,8 @@ class Descriptor(DescriptorProvider): assert len(binaryName) == 1 self._binaryNames.setdefault(member.identifier.name, binaryName[0]) + self._internalNames.setdefault(member.identifier.name, + member.identifier.name.replace('-', '_')) # Build the prototype chain. self.prototypeChain = [] @@ -285,6 +289,9 @@ class Descriptor(DescriptorProvider): def binaryNameFor(self, name): return self._binaryNames.get(name, name) + def internalNameFor(self, name): + return self._internalNames.get(name, name) + def getExtendedAttributes(self, member, getter=False, setter=False): def maybeAppendInfallibleToAttrs(attrs, throws): if throws is None: diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 2a9ee12e3a2..ef9e8ef82c9 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -12,9 +12,8 @@ use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::conversions::native_from_reflector_jsmanaged; use dom::bindings::js::{JS, Root}; use dom::bindings::utils::{Reflectable, Reflector}; -use dom::document::DocumentHelpers; -use dom::window::{self, WindowHelpers, ScriptHelpers}; -use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers}; +use dom::window::{self, ScriptHelpers}; +use dom::workerglobalscope::WorkerGlobalScope; use script_task::{ScriptChan, ScriptPort, CommonScriptMsg, ScriptTask}; use msg::constellation_msg::{ConstellationChan, PipelineId, WorkerId}; diff --git a/components/script/dom/bindings/js.rs b/components/script/dom/bindings/js.rs index 5b05d3ea99f..feb3a67d51f 100644 --- a/components/script/dom/bindings/js.rs +++ b/components/script/dom/bindings/js.rs @@ -207,6 +207,7 @@ impl MutHeapJSVal { /// `JS`. #[must_root] #[derive(JSTraceable)] +#[derive(HeapSizeOf)] pub struct MutHeap { val: Cell, } @@ -433,11 +434,6 @@ impl Root { &**self } - /// Don't use this. Don't make me find you. - pub fn get_unsound_ref_forever<'a, 'b>(&'a self) -> &'b T { - unsafe { &**self.ptr } - } - /// Generate a new root from a JS reference #[allow(unrooted_must_root)] pub fn from_rooted(js: JS) -> Root { diff --git a/components/script/dom/bindings/mod.rs b/components/script/dom/bindings/mod.rs index 283dc9b08c9..1ded213d0f4 100644 --- a/components/script/dom/bindings/mod.rs +++ b/components/script/dom/bindings/mod.rs @@ -168,15 +168,13 @@ pub mod codegen { pub mod PrototypeList { include!(concat!(env!("OUT_DIR"), "/PrototypeList.rs")); } - #[allow(unreachable_code, non_camel_case_types, non_upper_case_globals, unused_parens, - unused_imports, unused_variables, unused_unsafe, unused_mut, unused_assignments, - dead_code)] + #[allow(non_camel_case_types, non_upper_case_globals, + unused_imports, unused_variables, unused_assignments)] pub mod RegisterBindings { include!(concat!(env!("OUT_DIR"), "/RegisterBindings.rs")); } - #[allow(unreachable_code, non_camel_case_types, non_upper_case_globals, unused_parens, - unused_imports, unused_variables, unused_unsafe, unused_mut, unused_assignments, - dead_code)] + #[allow(non_camel_case_types, non_upper_case_globals, + unused_imports, unused_variables, unused_assignments)] pub mod UnionTypes { include!(concat!(env!("OUT_DIR"), "/UnionTypes.rs")); } diff --git a/components/script/dom/bindings/num.rs b/components/script/dom/bindings/num.rs index 87c5e38a3bb..1169ccdec7f 100644 --- a/components/script/dom/bindings/num.rs +++ b/components/script/dom/bindings/num.rs @@ -9,7 +9,7 @@ use num::Float; use std::ops::Deref; /// Encapsulates the IDL restricted float type. -#[derive(JSTraceable,Clone,Eq,PartialEq)] +#[derive(JSTraceable, Clone, Eq, PartialEq)] pub struct Finite(T); unsafe impl Zeroable for Finite {} diff --git a/components/script/dom/bindings/trace.rs b/components/script/dom/bindings/trace.rs index b1dcbbce163..8e48de2c680 100644 --- a/components/script/dom/bindings/trace.rs +++ b/components/script/dom/bindings/trace.rs @@ -29,7 +29,7 @@ //! The `no_jsmanaged_fields!()` macro adds an empty implementation of `JSTraceable` to //! a datatype. -use dom::bindings::js::JS; +use dom::bindings::js::{JS, Root}; use dom::bindings::refcounted::Trusted; use dom::bindings::utils::{Reflectable, Reflector, WindowProxyHandler}; use script_task::ScriptChan; @@ -69,6 +69,7 @@ use std::collections::{HashMap, HashSet}; use std::ffi::CString; use std::hash::{Hash, Hasher}; use std::intrinsics::return_address; +use std::iter::{FromIterator, IntoIterator}; use std::mem; use std::ops::{Deref, DerefMut}; use std::rc::Rc; @@ -511,6 +512,17 @@ impl DerefMut for RootedVec { } } +impl FromIterator> for RootedVec> { + #[allow(moved_no_move)] + fn from_iter(iterable: T) -> RootedVec> where T: IntoIterator> { + let mut vec = RootedVec::new_with_destination_address(unsafe { + return_address() as *const libc::c_void + }); + vec.extend(iterable.into_iter().map(|item| JS::from_rooted(&item))); + vec + } +} + /// SM Callback that traces the rooted traceables pub unsafe fn trace_traceables(tracer: *mut JSTracer) { ROOTED_TRACEABLES.with(|ref traceables| { diff --git a/components/script/dom/blob.rs b/components/script/dom/blob.rs index 717d50663ea..f8102dd9acf 100644 --- a/components/script/dom/blob.rs +++ b/components/script/dom/blob.rs @@ -25,7 +25,6 @@ pub enum BlobTypeId { // http://dev.w3.org/2006/webapi/FileAPI/#blob #[dom_struct] -#[derive(HeapSizeOf)] pub struct Blob { reflector_: Reflector, type_: BlobTypeId, @@ -78,21 +77,15 @@ impl Blob { }; Ok(Blob::new(global, bytes, &typeString.to_ascii_lowercase())) } -} -pub trait BlobHelpers { - fn read_out_buffer(self, send: Sender>); -} - -impl<'a> BlobHelpers for &'a Blob { - fn read_out_buffer(self, send: Sender>) { + pub fn read_out_buffer(&self, send: Sender>) { send.send(self.bytes.clone().unwrap_or(vec![])).unwrap(); } } -impl<'a> BlobMethods for &'a Blob { +impl BlobMethods for Blob { // https://dev.w3.org/2006/webapi/FileAPI/#dfn-size - fn Size(self) -> u64 { + fn Size(&self) -> u64 { match self.bytes { None => 0, Some(ref bytes) => bytes.len() as u64 @@ -100,12 +93,12 @@ impl<'a> BlobMethods for &'a Blob { } // https://dev.w3.org/2006/webapi/FileAPI/#dfn-type - fn Type(self) -> DOMString { + fn Type(&self) -> DOMString { self.typeString.clone() } // https://dev.w3.org/2006/webapi/FileAPI/#slice-method-algo - fn Slice(self, start: Option, end: Option, + fn Slice(&self, start: Option, end: Option, contentType: Option) -> Root { let size: i64 = self.Size().to_i64().unwrap(); let relativeStart: i64 = match start { @@ -153,12 +146,12 @@ impl<'a> BlobMethods for &'a Blob { } // https://dev.w3.org/2006/webapi/FileAPI/#dfn-isClosed - fn IsClosed(self) -> bool { + fn IsClosed(&self) -> bool { self.isClosed_.get() } // https://dev.w3.org/2006/webapi/FileAPI/#dfn-close - fn Close(self) { + fn Close(&self) { // Step 1 if self.isClosed_.get() { return; diff --git a/components/script/dom/browsercontext.rs b/components/script/dom/browsercontext.rs index cdd34ac7c71..3f6f1c0ebfb 100644 --- a/components/script/dom/browsercontext.rs +++ b/components/script/dom/browsercontext.rs @@ -8,10 +8,9 @@ use dom::bindings::js::{JS, Root}; use dom::bindings::proxyhandler::{get_property_descriptor, fill_property_descriptor}; use dom::bindings::utils::get_array_index_from_id; use dom::bindings::utils::{Reflectable, WindowProxyHandler}; -use dom::document::{Document, DocumentHelpers}; +use dom::document::Document; use dom::element::Element; use dom::window::Window; -use dom::window::WindowHelpers; use js::glue::{GetProxyPrivate}; use js::glue::{WrapperNew, CreateWrapperProxyHandler, ProxyTraps}; diff --git a/components/script/dom/canvasgradient.rs b/components/script/dom/canvasgradient.rs index ca91a7a7857..527b881778d 100644 --- a/components/script/dom/canvasgradient.rs +++ b/components/script/dom/canvasgradient.rs @@ -16,7 +16,6 @@ use dom::canvasrenderingcontext2d::parse_color; // https://html.spec.whatwg.org/multipage/#canvasgradient #[dom_struct] -#[derive(HeapSizeOf)] pub struct CanvasGradient { reflector_: Reflector, style: CanvasGradientStyle, @@ -44,9 +43,9 @@ impl CanvasGradient { } } -impl<'a> CanvasGradientMethods for &'a CanvasGradient { +impl CanvasGradientMethods for CanvasGradient { // https://html.spec.whatwg.org/multipage/#dom-canvasgradient-addcolorstop - fn AddColorStop(self, offset: Finite, color: String) -> ErrorResult { + fn AddColorStop(&self, offset: Finite, color: String) -> ErrorResult { if *offset < 0f64 || *offset > 1f64 { return Err(IndexSize); } diff --git a/components/script/dom/canvaspattern.rs b/components/script/dom/canvaspattern.rs index 49dae9c419b..25293e526f0 100644 --- a/components/script/dom/canvaspattern.rs +++ b/components/script/dom/canvaspattern.rs @@ -12,7 +12,6 @@ use euclid::size::Size2D; // https://html.spec.whatwg.org/multipage/#canvaspattern #[dom_struct] -#[derive(HeapSizeOf)] pub struct CanvasPattern { reflector_: Reflector, surface_data: Vec, diff --git a/components/script/dom/canvasrenderingcontext2d.rs b/components/script/dom/canvasrenderingcontext2d.rs index 03f4014ee7a..540cf744faf 100644 --- a/components/script/dom/canvasrenderingcontext2d.rs +++ b/components/script/dom/canvasrenderingcontext2d.rs @@ -17,11 +17,11 @@ use dom::bindings::num::Finite; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::canvasgradient::{CanvasGradient, CanvasGradientStyle, ToFillOrStrokeStyle}; use dom::canvaspattern::CanvasPattern; +use dom::htmlcanvaselement::HTMLCanvasElement; use dom::htmlcanvaselement::utils as canvas_utils; -use dom::htmlcanvaselement::{HTMLCanvasElement, HTMLCanvasElementHelpers}; -use dom::htmlimageelement::{HTMLImageElement, HTMLImageElementHelpers}; -use dom::imagedata::{ImageData, ImageDataHelpers}; -use dom::node::{window_from_node, NodeHelpers, NodeDamage}; +use dom::htmlimageelement::HTMLImageElement; +use dom::imagedata::ImageData; +use dom::node::{window_from_node, NodeDamage}; use msg::constellation_msg::Msg as ConstellationMsg; use net_traits::image::base::PixelFormat; @@ -61,7 +61,6 @@ pub enum CanvasFillOrStrokeStyle { // https://html.spec.whatwg.org/multipage/#canvasrenderingcontext2d #[dom_struct] -#[derive(HeapSizeOf)] pub struct CanvasRenderingContext2D { reflector_: Reflector, global: GlobalField, @@ -408,18 +407,11 @@ impl CanvasRenderingContext2D { Some(Rect::new(Point2D::new(x as f32, y as f32), Size2D::new(w as f32, h as f32))) } -} -pub trait CanvasRenderingContext2DHelpers { - fn get_renderer_id(self) -> usize; - fn get_ipc_renderer(self) -> IpcSender; -} - -impl<'a> CanvasRenderingContext2DHelpers for &'a CanvasRenderingContext2D { - fn get_renderer_id(self) -> usize { + pub fn get_renderer_id(&self) -> usize { self.renderer_id } - fn get_ipc_renderer(self) -> IpcSender { + pub fn get_ipc_renderer(&self) -> IpcSender { self.ipc_renderer.clone() } } @@ -451,20 +443,20 @@ impl LayoutCanvasRenderingContext2DHelpers for LayoutJS CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { +impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { // https://html.spec.whatwg.org/multipage/#dom-context-2d-canvas - fn Canvas(self) -> Root { + fn Canvas(&self) -> Root { self.canvas.root() } // https://html.spec.whatwg.org/multipage/#dom-context-2d-save - fn Save(self) { + fn Save(&self) { self.saved_states.borrow_mut().push(self.state.borrow().clone()); self.ipc_renderer.send(CanvasMsg::Canvas2d(Canvas2dMsg::SaveContext)).unwrap(); } // https://html.spec.whatwg.org/multipage/#dom-context-2d-restore - fn Restore(self) { + fn Restore(&self) { let mut saved_states = self.saved_states.borrow_mut(); if let Some(state) = saved_states.pop() { self.state.borrow_mut().clone_from(&state); @@ -473,7 +465,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-scale - fn Scale(self, x: f64, y: f64) { + fn Scale(&self, x: f64, y: f64) { if !(x.is_finite() && y.is_finite()) { return; } @@ -484,7 +476,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-rotate - fn Rotate(self, angle: f64) { + fn Rotate(&self, angle: f64) { if angle == 0.0 || !angle.is_finite() { return; } @@ -498,7 +490,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-translate - fn Translate(self, x: f64, y: f64) { + fn Translate(&self, x: f64, y: f64) { if !(x.is_finite() && y.is_finite()) { return; } @@ -509,7 +501,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a 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) { + 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()) { return; @@ -526,7 +518,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // 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) { + 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()) { return; @@ -542,19 +534,19 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-resettransform - fn ResetTransform(self) { + fn ResetTransform(&self) { self.state.borrow_mut().transform = Matrix2D::identity(); self.update_transform() } // https://html.spec.whatwg.org/multipage/#dom-context-2d-globalalpha - fn GlobalAlpha(self) -> f64 { + fn GlobalAlpha(&self) -> f64 { let state = self.state.borrow(); state.global_alpha } // https://html.spec.whatwg.org/multipage/#dom-context-2d-globalalpha - fn SetGlobalAlpha(self, alpha: f64) { + fn SetGlobalAlpha(&self, alpha: f64) { if !alpha.is_finite() || alpha > 1.0 || alpha < 0.0 { return; } @@ -566,7 +558,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-globalcompositeoperation - fn GlobalCompositeOperation(self) -> DOMString { + fn GlobalCompositeOperation(&self) -> DOMString { let state = self.state.borrow(); match state.global_composition { CompositionOrBlending::Composition(op) => op.to_str().to_owned(), @@ -575,7 +567,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-globalcompositeoperation - fn SetGlobalCompositeOperation(self, op_str: DOMString) { + fn SetGlobalCompositeOperation(&self, op_str: DOMString) { if let Some(op) = CompositionOrBlending::from_str(&op_str) { self.state.borrow_mut().global_composition = op; self.ipc_renderer @@ -585,7 +577,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-fillrect - fn FillRect(self, x: f64, y: f64, width: f64, height: f64) { + fn FillRect(&self, x: f64, y: f64, width: f64, height: f64) { if let Some(rect) = self.create_drawable_rect(x, y, width, height) { self.ipc_renderer.send(CanvasMsg::Canvas2d(Canvas2dMsg::FillRect(rect))).unwrap(); self.mark_as_dirty(); @@ -593,7 +585,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-clearrect - fn ClearRect(self, x: f64, y: f64, width: f64, height: f64) { + fn ClearRect(&self, x: f64, y: f64, width: f64, height: f64) { if let Some(rect) = self.create_drawable_rect(x, y, width, height) { self.ipc_renderer .send(CanvasMsg::Canvas2d(Canvas2dMsg::ClearRect(rect))) @@ -603,7 +595,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-strokerect - fn StrokeRect(self, x: f64, y: f64, width: f64, height: f64) { + fn StrokeRect(&self, x: f64, y: f64, width: f64, height: f64) { if let Some(rect) = self.create_drawable_rect(x, y, width, height) { self.ipc_renderer .send(CanvasMsg::Canvas2d(Canvas2dMsg::StrokeRect(rect))) @@ -613,36 +605,36 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-beginpath - fn BeginPath(self) { + fn BeginPath(&self) { self.ipc_renderer.send(CanvasMsg::Canvas2d(Canvas2dMsg::BeginPath)).unwrap(); } // https://html.spec.whatwg.org/multipage/#dom-context-2d-closepath - fn ClosePath(self) { + fn ClosePath(&self) { self.ipc_renderer.send(CanvasMsg::Canvas2d(Canvas2dMsg::ClosePath)).unwrap(); } // https://html.spec.whatwg.org/multipage/#dom-context-2d-fill - fn Fill(self, _: CanvasWindingRule) { + fn Fill(&self, _: CanvasWindingRule) { // TODO: Process winding rule self.ipc_renderer.send(CanvasMsg::Canvas2d(Canvas2dMsg::Fill)).unwrap(); self.mark_as_dirty(); } // https://html.spec.whatwg.org/multipage/#dom-context-2d-stroke - fn Stroke(self) { + fn Stroke(&self) { self.ipc_renderer.send(CanvasMsg::Canvas2d(Canvas2dMsg::Stroke)).unwrap(); self.mark_as_dirty(); } // https://html.spec.whatwg.org/multipage/#dom-context-2d-clip - fn Clip(self, _: CanvasWindingRule) { + fn Clip(&self, _: CanvasWindingRule) { // TODO: Process winding rule self.ipc_renderer.send(CanvasMsg::Canvas2d(Canvas2dMsg::Clip)).unwrap(); } // https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage - fn DrawImage(self, image: HTMLImageElementOrHTMLCanvasElementOrCanvasRenderingContext2D, + fn DrawImage(&self, image: HTMLImageElementOrHTMLCanvasElementOrCanvasRenderingContext2D, dx: f64, dy: f64) -> Fallible<()> { if !(dx.is_finite() && dy.is_finite()) { return Ok(()); @@ -652,7 +644,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage - fn DrawImage_(self, image: HTMLImageElementOrHTMLCanvasElementOrCanvasRenderingContext2D, + fn DrawImage_(&self, image: HTMLImageElementOrHTMLCanvasElementOrCanvasRenderingContext2D, dx: f64, dy: f64, dw: f64, dh: f64) -> Fallible<()> { if !(dx.is_finite() && dy.is_finite() && dw.is_finite() && dh.is_finite()) { @@ -663,7 +655,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage - fn DrawImage__(self, image: HTMLImageElementOrHTMLCanvasElementOrCanvasRenderingContext2D, + fn DrawImage__(&self, image: HTMLImageElementOrHTMLCanvasElementOrCanvasRenderingContext2D, sx: f64, sy: f64, sw: f64, sh: f64, dx: f64, dy: f64, dw: f64, dh: f64) -> Fallible<()> { if !(sx.is_finite() && sy.is_finite() && sw.is_finite() && sh.is_finite() && @@ -675,7 +667,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-moveto - fn MoveTo(self, x: f64, y: f64) { + fn MoveTo(&self, x: f64, y: f64) { if !(x.is_finite() && y.is_finite()) { return; } @@ -687,7 +679,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-lineto - fn LineTo(self, x: f64, y: f64) { + fn LineTo(&self, x: f64, y: f64) { if !(x.is_finite() && y.is_finite()) { return; } @@ -699,7 +691,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-rect - fn Rect(self, x: f64, y: f64, width: f64, height: f64) { + 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)); @@ -709,7 +701,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-quadraticcurveto - fn QuadraticCurveTo(self, cpx: f64, cpy: f64, x: f64, y: f64) { + fn QuadraticCurveTo(&self, cpx: f64, cpy: f64, x: f64, y: f64) { if !(cpx.is_finite() && cpy.is_finite() && x.is_finite() && y.is_finite()) { return; @@ -723,7 +715,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // 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) { + 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()) { return; @@ -738,7 +730,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-arc - fn Arc(self, x: f64, y: f64, r: f64, + fn Arc(&self, x: f64, y: f64, r: f64, start: f64, end: f64, ccw: bool) -> Fallible<()> { if !([x, y, r, start, end].iter().all(|x| x.is_finite())) { return Ok(()); @@ -758,7 +750,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-arcto - fn ArcTo(self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, r: f64) -> Fallible<()> { + fn ArcTo(&self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, r: f64) -> Fallible<()> { if !([cp1x, cp1y, cp2x, cp2y, r].iter().all(|x| x.is_finite())) { return Ok(()); } @@ -776,18 +768,18 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/#dom-context-2d-imagesmoothingenabled - fn ImageSmoothingEnabled(self) -> bool { + fn ImageSmoothingEnabled(&self) -> bool { let state = self.state.borrow(); state.image_smoothing_enabled } // https://html.spec.whatwg.org/#dom-context-2d-imagesmoothingenabled - fn SetImageSmoothingEnabled(self, value: bool) -> () { + fn SetImageSmoothingEnabled(&self, value: bool) -> () { self.state.borrow_mut().image_smoothing_enabled = value; } // https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle - fn StrokeStyle(self) -> StringOrCanvasGradientOrCanvasPattern { + fn StrokeStyle(&self) -> StringOrCanvasGradientOrCanvasPattern { match self.state.borrow().stroke_style { CanvasFillOrStrokeStyle::Color(ref rgba) => { let mut result = String::new(); @@ -801,7 +793,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle - fn SetStrokeStyle(self, value: StringOrCanvasGradientOrCanvasPattern) { + fn SetStrokeStyle(&self, value: StringOrCanvasGradientOrCanvasPattern) { match value { StringOrCanvasGradientOrCanvasPattern::eString(string) => { match parse_color(&string) { @@ -827,7 +819,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle - fn FillStyle(self) -> StringOrCanvasGradientOrCanvasPattern { + fn FillStyle(&self) -> StringOrCanvasGradientOrCanvasPattern { match self.state.borrow().fill_style { CanvasFillOrStrokeStyle::Color(ref rgba) => { let mut result = String::new(); @@ -841,7 +833,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle - fn SetFillStyle(self, value: StringOrCanvasGradientOrCanvasPattern) { + fn SetFillStyle(&self, value: StringOrCanvasGradientOrCanvasPattern) { match value { StringOrCanvasGradientOrCanvasPattern::eString(string) => { if let Ok(rgba) = parse_color(&string) { @@ -867,7 +859,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata - fn CreateImageData(self, sw: Finite, sh: Finite) -> Fallible> { + fn CreateImageData(&self, sw: Finite, sh: Finite) -> Fallible> { if *sw == 0.0 || *sh == 0.0 { return Err(IndexSize) } @@ -878,12 +870,12 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata - fn CreateImageData_(self, imagedata: &ImageData) -> Fallible> { + fn CreateImageData_(&self, imagedata: &ImageData) -> Fallible> { Ok(ImageData::new(self.global.root().r(), imagedata.Width(), imagedata.Height(), None)) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-getimagedata - fn GetImageData(self, + fn GetImageData(&self, sx: Finite, sy: Finite, sw: Finite, @@ -933,13 +925,13 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata - fn PutImageData(self, imagedata: &ImageData, dx: Finite, dy: Finite) { + fn PutImageData(&self, imagedata: &ImageData, dx: Finite, dy: Finite) { 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, dy: Finite, + fn PutImageData_(&self, imagedata: &ImageData, dx: Finite, dy: Finite, dirtyX: Finite, dirtyY: Finite, dirtyWidth: Finite, dirtyHeight: Finite) { let data = imagedata.get_data_array(&self.global.root().r()); let offset = Point2D::new(*dx, *dy); @@ -954,14 +946,14 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-createlineargradient - fn CreateLinearGradient(self, x0: Finite, y0: Finite, + fn CreateLinearGradient(&self, x0: Finite, y0: Finite, x1: Finite, y1: Finite) -> Root { CanvasGradient::new(self.global.root().r(), 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, y0: Finite, r0: Finite, + fn CreateRadialGradient(&self, x0: Finite, y0: Finite, r0: Finite, x1: Finite, y1: Finite, r1: Finite) -> Fallible> { if *r0 < 0. || *r1 < 0. { @@ -974,7 +966,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-createpattern - fn CreatePattern(self, image: HTMLImageElementOrHTMLCanvasElementOrCanvasRenderingContext2D, + fn CreatePattern(&self, image: HTMLImageElementOrHTMLCanvasElementOrCanvasRenderingContext2D, repetition: DOMString) -> Fallible> { let (image_data, image_size) = match image { HTMLImageElementOrHTMLCanvasElementOrCanvasRenderingContext2D::eHTMLImageElement(image) => { @@ -1024,13 +1016,13 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-linewidth - fn LineWidth(self) -> f64 { + fn LineWidth(&self) -> f64 { let state = self.state.borrow(); state.line_width } // https://html.spec.whatwg.org/multipage/#dom-context-2d-linewidth - fn SetLineWidth(self, width: f64) { + fn SetLineWidth(&self, width: f64) { if !width.is_finite() || width <= 0.0 { return; } @@ -1042,7 +1034,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-linecap - fn LineCap(self) -> DOMString { + fn LineCap(&self) -> DOMString { let state = self.state.borrow(); match state.line_cap { LineCapStyle::Butt => "butt".to_owned(), @@ -1052,7 +1044,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-linecap - fn SetLineCap(self, cap_str: DOMString) { + fn SetLineCap(&self, cap_str: DOMString) { if let Some(cap) = LineCapStyle::from_str(&cap_str) { self.state.borrow_mut().line_cap = cap; self.ipc_renderer.send(CanvasMsg::Canvas2d(Canvas2dMsg::SetLineCap(cap))).unwrap() @@ -1060,7 +1052,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-linejoin - fn LineJoin(self) -> DOMString { + fn LineJoin(&self) -> DOMString { let state = self.state.borrow(); match state.line_join { LineJoinStyle::Round => "round".to_owned(), @@ -1070,7 +1062,7 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-linejoin - fn SetLineJoin(self, join_str: DOMString) { + fn SetLineJoin(&self, join_str: DOMString) { if let Some(join) = LineJoinStyle::from_str(&join_str) { self.state.borrow_mut().line_join = join; self.ipc_renderer.send(CanvasMsg::Canvas2d(Canvas2dMsg::SetLineJoin(join))).unwrap() @@ -1078,13 +1070,13 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-miterlimit - fn MiterLimit(self) -> f64 { + fn MiterLimit(&self) -> f64 { let state = self.state.borrow(); state.miter_limit } // https://html.spec.whatwg.org/multipage/#dom-context-2d-miterlimit - fn SetMiterLimit(self, limit: f64) { + fn SetMiterLimit(&self, limit: f64) { if !limit.is_finite() || limit <= 0.0 { return; } @@ -1096,12 +1088,12 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsetx - fn ShadowOffsetX(self) -> f64 { + fn ShadowOffsetX(&self) -> f64 { self.state.borrow().shadow_offset_x } // https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsetx - fn SetShadowOffsetX(self, value: f64) { + fn SetShadowOffsetX(&self, value: f64) { if !value.is_finite() || value == self.state.borrow().shadow_offset_x { return; } @@ -1110,12 +1102,12 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsety - fn ShadowOffsetY(self) -> f64 { + fn ShadowOffsetY(&self) -> f64 { self.state.borrow().shadow_offset_y } // https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsety - fn SetShadowOffsetY(self, value: f64) { + fn SetShadowOffsetY(&self, value: f64) { if !value.is_finite() || value == self.state.borrow().shadow_offset_y { return; } @@ -1124,12 +1116,12 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowblur - fn ShadowBlur(self) -> f64 { + fn ShadowBlur(&self) -> f64 { self.state.borrow().shadow_blur } // https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowblur - fn SetShadowBlur(self, value: f64) { + fn SetShadowBlur(&self, value: f64) { if !value.is_finite() || value < 0f64 || value == self.state.borrow().shadow_blur { return; } @@ -1138,14 +1130,14 @@ impl<'a> CanvasRenderingContext2DMethods for &'a CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowcolor - fn ShadowColor(self) -> DOMString { + fn ShadowColor(&self) -> DOMString { let mut result = String::new(); serialize(&self.state.borrow().shadow_color, &mut result).unwrap(); result } // https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowcolor - fn SetShadowColor(self, value: DOMString) { + fn SetShadowColor(&self, value: DOMString) { if let Ok(color) = parse_color(&value) { self.state.borrow_mut().shadow_color = color; self.ipc_renderer diff --git a/components/script/dom/characterdata.rs b/components/script/dom/characterdata.rs index b2d3dfec0cb..d9c558ee2e8 100644 --- a/components/script/dom/characterdata.rs +++ b/components/script/dom/characterdata.rs @@ -15,16 +15,15 @@ use dom::bindings::js::{LayoutJS, Root}; use dom::document::Document; use dom::element::Element; use dom::eventtarget::{EventTarget, EventTargetTypeId}; -use dom::node::{Node, NodeHelpers, NodeTypeId}; +use dom::node::{Node, NodeTypeId}; -use util::str::{DOMString, slice_chars}; +use util::str::DOMString; use std::borrow::ToOwned; use std::cell::Ref; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] -#[derive(HeapSizeOf)] pub struct CharacterData { node: Node, data: DOMRefCell, @@ -48,103 +47,111 @@ impl CharacterData { } } -impl<'a> CharacterDataMethods for &'a CharacterData { +impl CharacterDataMethods for CharacterData { // https://dom.spec.whatwg.org/#dom-characterdata-data - fn Data(self) -> DOMString { + fn Data(&self) -> DOMString { self.data.borrow().clone() } // https://dom.spec.whatwg.org/#dom-characterdata-data - fn SetData(self, data: DOMString) { + fn SetData(&self, data: DOMString) { *self.data.borrow_mut() = data; } // https://dom.spec.whatwg.org/#dom-characterdata-length - fn Length(self) -> u32 { - self.data.borrow().chars().count() as u32 + fn Length(&self) -> u32 { + self.data.borrow().chars().map(|c| c.len_utf16()).sum::() as u32 } - // https://dom.spec.whatwg.org/#dom-characterdata-substringdataoffset-count - fn SubstringData(self, offset: u32, count: u32) -> Fallible { + // https://dom.spec.whatwg.org/#dom-characterdata-substringdata + fn SubstringData(&self, offset: u32, count: u32) -> Fallible { let data = self.data.borrow(); // Step 1. - let length = data.chars().count() as u32; - if offset > length { + let data_from_offset = match find_utf16_code_unit_offset(&data, offset) { + Some(offset_bytes) => &data[offset_bytes..], // Step 2. - return Err(IndexSize); - } - // Steps 3-4. - let end = if length - offset < count { length } else { offset + count }; - Ok(slice_chars(&*data, offset as usize, end as usize).to_owned()) + None => return Err(IndexSize) + }; + let substring = match find_utf16_code_unit_offset(data_from_offset, count) { + // Steps 3. + None => data_from_offset, + // Steps 4. + Some(count_bytes) => &data_from_offset[..count_bytes], + }; + Ok(substring.to_owned()) } // https://dom.spec.whatwg.org/#dom-characterdata-appenddatadata - fn AppendData(self, data: DOMString) { + fn AppendData(&self, data: DOMString) { self.append_data(&*data); } // https://dom.spec.whatwg.org/#dom-characterdata-insertdataoffset-data - fn InsertData(self, offset: u32, arg: DOMString) -> ErrorResult { + fn InsertData(&self, offset: u32, arg: DOMString) -> ErrorResult { self.ReplaceData(offset, 0, arg) } // https://dom.spec.whatwg.org/#dom-characterdata-deletedataoffset-count - fn DeleteData(self, offset: u32, count: u32) -> ErrorResult { + fn DeleteData(&self, offset: u32, count: u32) -> ErrorResult { self.ReplaceData(offset, count, "".to_owned()) } - // https://dom.spec.whatwg.org/#dom-characterdata-replacedataoffset-count-data - fn ReplaceData(self, offset: u32, count: u32, arg: DOMString) -> ErrorResult { - // Step 1. - let length = self.data.borrow().chars().count() as u32; - if offset > length { - // Step 2. - return Err(IndexSize); - } - // Step 3. - let count = match length - offset { - diff if diff < count => diff, - _ => count, + // https://dom.spec.whatwg.org/#dom-characterdata-replacedata + fn ReplaceData(&self, offset: u32, count: u32, arg: DOMString) -> ErrorResult { + let new_data = { + let data = self.data.borrow(); + let (prefix, data_from_offset) = match find_utf16_code_unit_offset(&data, offset) { + Some(offset_bytes) => data.split_at(offset_bytes), + // Step 2. + None => return Err(IndexSize) + }; + let suffix = match find_utf16_code_unit_offset(data_from_offset, count) { + // Steps 3. + None => "", + Some(count_bytes) => &data_from_offset[count_bytes..], + }; + // Step 4: Mutation observers. + // Step 5 to 7. + let mut new_data = String::with_capacity(prefix.len() + arg.len() + suffix.len()); + new_data.push_str(prefix); + new_data.push_str(&arg); + new_data.push_str(suffix); + new_data }; - // Step 4: Mutation observers. - // Step 5. - let mut data = slice_chars(&*self.data.borrow(), 0, offset as usize).to_owned(); - data.push_str(&arg); - data.push_str(slice_chars(&*self.data.borrow(), (offset + count) as usize, length as usize)); - *self.data.borrow_mut() = data; - // FIXME: Once we have `Range`, we should implement step7 to step11 + *self.data.borrow_mut() = new_data; + // FIXME: Once we have `Range`, we should implement step 8 to step 11 Ok(()) } // https://dom.spec.whatwg.org/#dom-childnode-before - fn Before(self, nodes: Vec) -> ErrorResult { + fn Before(&self, nodes: Vec) -> ErrorResult { NodeCast::from_ref(self).before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after - fn After(self, nodes: Vec) -> ErrorResult { + fn After(&self, nodes: Vec) -> ErrorResult { NodeCast::from_ref(self).after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith - fn ReplaceWith(self, nodes: Vec) -> ErrorResult { + fn ReplaceWith(&self, nodes: Vec) -> ErrorResult { NodeCast::from_ref(self).replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove - fn Remove(self) { + fn Remove(&self) { let node = NodeCast::from_ref(self); node.remove_self(); } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling - fn GetPreviousElementSibling(self) -> Option> { + fn GetPreviousElementSibling(&self) -> Option> { NodeCast::from_ref(self).preceding_siblings() .filter_map(ElementCast::to_root).next() } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling - fn GetNextElementSibling(self) -> Option> { + fn GetNextElementSibling(&self) -> Option> { NodeCast::from_ref(self).following_siblings() .filter_map(ElementCast::to_root).next() } @@ -158,18 +165,14 @@ pub enum CharacterDataTypeId { ProcessingInstruction, } -pub trait CharacterDataHelpers<'a> { - fn data(self) -> Ref<'a, DOMString>; - fn append_data(self, data: &str); -} -impl<'a> CharacterDataHelpers<'a> for &'a CharacterData { +impl CharacterData { #[inline] - fn data(self) -> Ref<'a, DOMString> { + pub fn data(&self) -> Ref { self.data.borrow() } #[inline] - fn append_data(self, data: &str) { + pub fn append_data(&self, data: &str) { self.data.borrow_mut().push_str(data) } } @@ -186,3 +189,32 @@ impl LayoutCharacterDataHelpers for LayoutJS { &(*self.unsafe_get()).data.borrow_for_layout() } } + +/// Given a number of UTF-16 code units from the start of the given string, +/// return the corresponding number of UTF-8 bytes. +/// +/// s[find_utf16_code_unit_offset(s, o).unwrap()..] == s.to_utf16()[o..].to_utf8() +fn find_utf16_code_unit_offset(s: &str, offset: u32) -> Option { + let mut code_units = 0; + for (i, c) in s.char_indices() { + if code_units == offset { + return Some(i) + } + code_units += 1; + if c > '\u{FFFF}' { + if code_units == offset { + 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; + } + } + if code_units == offset { + Some(s.len()) + } else { + None + } +} diff --git a/components/script/dom/closeevent.rs b/components/script/dom/closeevent.rs index a9a6c8e960e..5dfbaf5aecd 100644 --- a/components/script/dom/closeevent.rs +++ b/components/script/dom/closeevent.rs @@ -16,7 +16,6 @@ use script_task::ScriptChan; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct CloseEvent { event: Event, wasClean: bool, @@ -69,19 +68,19 @@ impl CloseEvent { } } -impl<'a> CloseEventMethods for &'a CloseEvent { +impl CloseEventMethods for CloseEvent { // https://html.spec.whatwg.org/multipage/#dom-closeevent-wasclean - fn WasClean(self) -> bool { + fn WasClean(&self) -> bool { self.wasClean } // https://html.spec.whatwg.org/multipage/#dom-closeevent-code - fn Code(self) -> u16 { + fn Code(&self) -> u16 { self.code } // https://html.spec.whatwg.org/multipage/#dom-closeevent-reason - fn Reason(self) -> DOMString { + fn Reason(&self) -> DOMString { self.reason.clone() } } diff --git a/components/script/dom/comment.rs b/components/script/dom/comment.rs index 930d737a168..5f742ffb3b3 100644 --- a/components/script/dom/comment.rs +++ b/components/script/dom/comment.rs @@ -16,7 +16,6 @@ use util::str::DOMString; /// An HTML comment. #[dom_struct] -#[derive(HeapSizeOf)] pub struct Comment { characterdata: CharacterData, } @@ -44,4 +43,3 @@ impl Comment { Ok(Comment::new(data, document.r())) } } - diff --git a/components/script/dom/console.rs b/components/script/dom/console.rs index fb0e2ab08f3..faa3c507e5f 100644 --- a/components/script/dom/console.rs +++ b/components/script/dom/console.rs @@ -8,12 +8,10 @@ use dom::bindings::codegen::Bindings::ConsoleBinding::ConsoleMethods; use dom::bindings::global::{GlobalRef, GlobalField}; use dom::bindings::js::Root; use dom::bindings::utils::{Reflector, reflect_dom_object}; -use dom::window::WindowHelpers; use util::str::DOMString; // https://developer.mozilla.org/en-US/docs/Web/API/Console #[dom_struct] -#[derive(HeapSizeOf)] pub struct Console { reflector_: Reflector, global: GlobalField, @@ -32,9 +30,9 @@ impl Console { } } -impl<'a> ConsoleMethods for &'a Console { +impl ConsoleMethods for Console { // https://developer.mozilla.org/en-US/docs/Web/API/Console/log - fn Log(self, messages: Vec) { + fn Log(&self, messages: Vec) { for message in messages { println!("{}", message); propagate_console_msg(&self, prepare_message(LogLevel::Log, message)); @@ -42,7 +40,7 @@ impl<'a> ConsoleMethods for &'a Console { } // https://developer.mozilla.org/en-US/docs/Web/API/Console - fn Debug(self, messages: Vec) { + fn Debug(&self, messages: Vec) { for message in messages { println!("{}", message); propagate_console_msg(&self, prepare_message(LogLevel::Debug, message)); @@ -50,7 +48,7 @@ impl<'a> ConsoleMethods for &'a Console { } // https://developer.mozilla.org/en-US/docs/Web/API/Console/info - fn Info(self, messages: Vec) { + fn Info(&self, messages: Vec) { for message in messages { println!("{}", message); propagate_console_msg(&self, prepare_message(LogLevel::Info, message)); @@ -58,7 +56,7 @@ impl<'a> ConsoleMethods for &'a Console { } // https://developer.mozilla.org/en-US/docs/Web/API/Console/warn - fn Warn(self, messages: Vec) { + fn Warn(&self, messages: Vec) { for message in messages { println!("{}", message); propagate_console_msg(&self, prepare_message(LogLevel::Warn, message)); @@ -66,7 +64,7 @@ impl<'a> ConsoleMethods for &'a Console { } // https://developer.mozilla.org/en-US/docs/Web/API/Console/error - fn Error(self, messages: Vec) { + fn Error(&self, messages: Vec) { for message in messages { println!("{}", message); propagate_console_msg(&self, prepare_message(LogLevel::Error, message)); @@ -74,7 +72,7 @@ impl<'a> ConsoleMethods for &'a Console { } // https://developer.mozilla.org/en-US/docs/Web/API/Console/assert - fn Assert(self, condition: bool, message: Option) { + fn Assert(&self, condition: bool, message: Option) { if !condition { let message = match message { Some(ref message) => &**message, diff --git a/components/script/dom/crypto.rs b/components/script/dom/crypto.rs index 8764dd900ff..49ca25ff376 100644 --- a/components/script/dom/crypto.rs +++ b/components/script/dom/crypto.rs @@ -22,7 +22,6 @@ no_jsmanaged_fields!(OsRng); // https://developer.mozilla.org/en-US/docs/Web/API/Crypto #[dom_struct] -#[derive(HeapSizeOf)] pub struct Crypto { reflector_: Reflector, rng: DOMRefCell, @@ -41,10 +40,10 @@ impl Crypto { } } -impl<'a> CryptoMethods for &'a Crypto { +impl CryptoMethods for Crypto { #[allow(unsafe_code)] // https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#Crypto-method-getRandomValues - fn GetRandomValues(self, _cx: *mut JSContext, input: *mut JSObject) + fn GetRandomValues(&self, _cx: *mut JSContext, input: *mut JSObject) -> Fallible<*mut JSObject> { let mut length = 0; let mut data = ptr::null_mut(); diff --git a/components/script/dom/css.rs b/components/script/dom/css.rs index c88b3ea92fc..5f4bce94d28 100644 --- a/components/script/dom/css.rs +++ b/components/script/dom/css.rs @@ -10,7 +10,6 @@ use util::str::DOMString; use cssparser::serialize_identifier; #[dom_struct] -#[derive(HeapSizeOf)] pub struct CSS { reflector_: Reflector, } diff --git a/components/script/dom/cssstyledeclaration.rs b/components/script/dom/cssstyledeclaration.rs index 5e2b82c186d..247de62b23f 100644 --- a/components/script/dom/cssstyledeclaration.rs +++ b/components/script/dom/cssstyledeclaration.rs @@ -8,10 +8,9 @@ use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::utils::{Reflector, reflect_dom_object}; -use dom::document::DocumentHelpers; -use dom::element::{ElementHelpers, StylePriority, Element}; -use dom::node::{window_from_node, document_from_node, NodeDamage, NodeHelpers}; -use dom::window::{Window, WindowHelpers}; +use dom::element::{StylePriority, Element}; +use dom::node::{window_from_node, document_from_node, NodeDamage}; +use dom::window::Window; use selectors::parser::PseudoElement; use string_cache::Atom; use style::properties::PropertyDeclaration; @@ -24,7 +23,6 @@ use std::cell::Ref; // http://dev.w3.org/csswg/cssom/#the-cssstyledeclaration-interface #[dom_struct] -#[derive(HeapSizeOf)] pub struct CSSStyleDeclaration { reflector_: Reflector, owner: JS, @@ -41,10 +39,10 @@ pub enum CSSModificationAccess { macro_rules! css_properties( ( $([$getter:ident, $setter:ident, $cssprop:expr]),* ) => ( $( - fn $getter(self) -> DOMString { + fn $getter(&self) -> DOMString { self.GetPropertyValue($cssprop.to_owned()) } - fn $setter(self, value: DOMString) -> ErrorResult { + fn $setter(&self, value: DOMString) -> ErrorResult { self.SetPropertyValue($cssprop.to_owned(), value) } )* @@ -76,9 +74,7 @@ impl CSSStyleDeclaration { GlobalRef::Window(global), CSSStyleDeclarationBinding::Wrap) } -} -impl CSSStyleDeclaration { fn get_computed_style(&self, property: &Atom) -> Option { let owner = self.owner.root(); let node = NodeCast::from_ref(owner.r()); @@ -92,9 +88,9 @@ impl CSSStyleDeclaration { } } -impl<'a> CSSStyleDeclarationMethods for &'a CSSStyleDeclaration { +impl CSSStyleDeclarationMethods for CSSStyleDeclaration { // https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-length - fn Length(self) -> u32 { + fn Length(&self) -> u32 { let owner = self.owner.root(); let elem = ElementCast::from_ref(owner.r()); let len = match *elem.style_attribute().borrow() { @@ -105,7 +101,7 @@ impl<'a> CSSStyleDeclarationMethods for &'a CSSStyleDeclaration { } // https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-item - fn Item(self, index: u32) -> DOMString { + fn Item(&self, index: u32) -> DOMString { let index = index as usize; let owner = self.owner.root(); let elem = ElementCast::from_ref(owner.r()); @@ -126,7 +122,7 @@ impl<'a> CSSStyleDeclarationMethods for &'a CSSStyleDeclaration { } // https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-getpropertyvalue - fn GetPropertyValue(self, property: DOMString) -> DOMString { + fn GetPropertyValue(&self, property: DOMString) -> DOMString { let owner = self.owner.root(); // Step 1 @@ -169,7 +165,7 @@ impl<'a> CSSStyleDeclarationMethods for &'a CSSStyleDeclaration { } // https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-getpropertypriority - fn GetPropertyPriority(self, property: DOMString) -> DOMString { + fn GetPropertyPriority(&self, property: DOMString) -> DOMString { // Step 1 let property = Atom::from_slice(&property.to_ascii_lowercase()); @@ -197,7 +193,7 @@ impl<'a> CSSStyleDeclarationMethods for &'a CSSStyleDeclaration { } // https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-setproperty - fn SetProperty(self, property: DOMString, value: DOMString, + fn SetProperty(&self, property: DOMString, value: DOMString, priority: DOMString) -> ErrorResult { // Step 1 if self.readonly { @@ -252,7 +248,7 @@ impl<'a> CSSStyleDeclarationMethods for &'a CSSStyleDeclaration { } // https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-setpropertypriority - fn SetPropertyPriority(self, property: DOMString, priority: DOMString) -> ErrorResult { + fn SetPropertyPriority(&self, property: DOMString, priority: DOMString) -> ErrorResult { // Step 1 if self.readonly { return Err(Error::NoModificationAllowed); @@ -286,12 +282,12 @@ impl<'a> CSSStyleDeclarationMethods for &'a CSSStyleDeclaration { } // https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-setpropertyvalue - fn SetPropertyValue(self, property: DOMString, value: DOMString) -> ErrorResult { + fn SetPropertyValue(&self, property: DOMString, value: DOMString) -> ErrorResult { self.SetProperty(property, value, "".to_owned()) } // https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-removeproperty - fn RemoveProperty(self, property: DOMString) -> Fallible { + fn RemoveProperty(&self, property: DOMString) -> Fallible { // Step 1 if self.readonly { return Err(Error::NoModificationAllowed); @@ -322,21 +318,22 @@ impl<'a> CSSStyleDeclarationMethods for &'a CSSStyleDeclaration { } // https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-cssfloat - fn CssFloat(self) -> DOMString { + fn CssFloat(&self) -> DOMString { self.GetPropertyValue("float".to_owned()) } // https://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-cssfloat - fn SetCssFloat(self, value: DOMString) -> ErrorResult { + fn SetCssFloat(&self, value: DOMString) -> ErrorResult { self.SetPropertyValue("float".to_owned(), value) } // https://dev.w3.org/csswg/cssom/#the-cssstyledeclaration-interface - fn IndexedGetter(self, index: u32, found: &mut bool) -> DOMString { + fn IndexedGetter(&self, index: u32, found: &mut bool) -> DOMString { let rval = self.Item(index); *found = index < self.Length(); rval } + // https://drafts.csswg.org/cssom/#cssstyledeclaration css_properties_accessors!(css_properties); } diff --git a/components/script/dom/customevent.rs b/components/script/dom/customevent.rs index a020b7ef5cd..a0bd520bb1e 100644 --- a/components/script/dom/customevent.rs +++ b/components/script/dom/customevent.rs @@ -17,7 +17,6 @@ use util::str::DOMString; // https://dom.spec.whatwg.org/#interface-customevent #[dom_struct] -#[derive(HeapSizeOf)] pub struct CustomEvent { event: Event, #[ignore_heap_size_of = "Defined in rust-mozjs"] @@ -63,14 +62,14 @@ impl CustomEvent { } } -impl<'a> CustomEventMethods for &'a CustomEvent { +impl CustomEventMethods for CustomEvent { // https://dom.spec.whatwg.org/#dom-customevent-detail - fn Detail(self, _cx: *mut JSContext) -> JSVal { + fn Detail(&self, _cx: *mut JSContext) -> JSVal { self.detail.get() } // https://dom.spec.whatwg.org/#dom-customevent-initcustomevent - fn InitCustomEvent(self, + fn InitCustomEvent(&self, _cx: *mut JSContext, type_: DOMString, can_bubble: bool, @@ -85,4 +84,3 @@ impl<'a> CustomEventMethods for &'a CustomEvent { event.InitEvent(type_, can_bubble, cancelable); } } - diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index 1521b0d5bba..d4a3b216914 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -6,7 +6,6 @@ use devtools; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding; use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding::DedicatedWorkerGlobalScopeMethods; -use dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::InheritTypes::DedicatedWorkerGlobalScopeDerived; use dom::bindings::codegen::InheritTypes::{EventTargetCast, WorkerGlobalScopeCast}; @@ -16,12 +15,12 @@ use dom::bindings::js::{RootCollection, Root}; use dom::bindings::refcounted::LiveDOMReferences; use dom::bindings::structuredclone::StructuredCloneData; use dom::bindings::utils::Reflectable; -use dom::errorevent::ErrorEvent; -use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::messageevent::MessageEvent; -use dom::worker::{TrustedWorkerAddress, WorkerMessageHandler, WorkerEventHandler, WorkerErrorHandler}; -use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers}; +use dom::worker::{TrustedWorkerAddress, WorkerMessageHandler, SimpleWorkerErrorHandler}; +use dom::workerglobalscope::WorkerGlobalScope; use dom::workerglobalscope::{WorkerGlobalScopeTypeId, WorkerGlobalScopeInit}; +use script_task::ScriptTaskEventCategory::WorkerEvent; use script_task::{ScriptTask, ScriptChan, TimerSource, ScriptPort, StackRootTLS, CommonScriptMsg}; use devtools_traits::DevtoolScriptControlMsg; @@ -138,7 +137,6 @@ enum MixedMessage { // https://html.spec.whatwg.org/multipage/#dedicatedworkerglobalscope #[dom_struct] -#[derive(HeapSizeOf)] pub struct DedicatedWorkerGlobalScope { workerglobalscope: WorkerGlobalScope, id: PipelineId, @@ -189,9 +187,7 @@ impl DedicatedWorkerGlobalScope { own_sender, receiver); DedicatedWorkerGlobalScopeBinding::Wrap(runtime.cx(), scope) } -} -impl DedicatedWorkerGlobalScope { pub fn run_worker_scope(init: WorkerGlobalScopeInit, worker_url: Url, id: PipelineId, @@ -210,8 +206,8 @@ impl DedicatedWorkerGlobalScope { let (url, source) = match load_whole_resource(&init.resource_task, worker_url) { Err(_) => { println!("error loading script {}", serialized_worker_url); - parent_sender.send(CommonScriptMsg::RunnableMsg( - box WorkerEventHandler::new(worker))).unwrap(); + parent_sender.send(CommonScriptMsg::RunnableMsg(WorkerEvent, + box SimpleWorkerErrorHandler::new(worker))).unwrap(); return; } Ok((metadata, bytes)) => { @@ -244,28 +240,19 @@ impl DedicatedWorkerGlobalScope { }, reporter_name, parent_sender, CommonScriptMsg::CollectReports); }); } -} -pub trait DedicatedWorkerGlobalScopeHelpers { - fn script_chan(self) -> Box; - fn pipeline(self) -> PipelineId; - fn new_script_pair(self) -> (Box, Box); - fn process_event(self, msg: CommonScriptMsg); -} - -impl<'a> DedicatedWorkerGlobalScopeHelpers for &'a DedicatedWorkerGlobalScope { - fn script_chan(self) -> Box { + pub fn script_chan(&self) -> Box { box WorkerThreadWorkerChan { sender: self.own_sender.clone(), worker: self.worker.borrow().as_ref().unwrap().clone(), } } - fn pipeline(self) -> PipelineId { + pub fn pipeline(&self) -> PipelineId { self.id } - fn new_script_pair(self) -> (Box, Box) { + pub fn new_script_pair(&self) -> (Box, Box) { let (tx, rx) = channel(); let chan = box SendableWorkerScriptChan { sender: tx, @@ -274,21 +261,12 @@ impl<'a> DedicatedWorkerGlobalScopeHelpers for &'a DedicatedWorkerGlobalScope { (chan, box rx) } - fn process_event(self, msg: CommonScriptMsg) { + pub fn process_event(&self, msg: CommonScriptMsg) { self.handle_script_event(WorkerScriptMsg::Common(msg)); } -} -trait PrivateDedicatedWorkerGlobalScopeHelpers { - fn handle_script_event(self, msg: WorkerScriptMsg); - fn dispatch_error_to_worker(self, &ErrorEvent); - fn receive_event(self) -> Result; - fn handle_event(self, event: MixedMessage); -} - -impl<'a> PrivateDedicatedWorkerGlobalScopeHelpers for &'a DedicatedWorkerGlobalScope { #[allow(unsafe_code)] - fn receive_event(self) -> Result { + fn receive_event(&self) -> Result { let scope = WorkerGlobalScopeCast::from_ref(self); let worker_port = &self.receiver; let devtools_port = scope.from_devtools_receiver(); @@ -312,7 +290,7 @@ impl<'a> PrivateDedicatedWorkerGlobalScopeHelpers for &'a DedicatedWorkerGlobalS } } - fn handle_script_event(self, msg: WorkerScriptMsg) { + fn handle_script_event(&self, msg: WorkerScriptMsg) { match msg { WorkerScriptMsg::DOMMessage(data) => { let scope = WorkerGlobalScopeCast::from_ref(self); @@ -323,7 +301,7 @@ impl<'a> PrivateDedicatedWorkerGlobalScopeHelpers for &'a DedicatedWorkerGlobalS data.read(GlobalRef::Worker(scope), message.handle_mut()); MessageEvent::dispatch_jsval(target, GlobalRef::Worker(scope), message.handle()); }, - WorkerScriptMsg::Common(CommonScriptMsg::RunnableMsg(runnable)) => { + WorkerScriptMsg::Common(CommonScriptMsg::RunnableMsg(_, runnable)) => { runnable.handler() }, WorkerScriptMsg::Common(CommonScriptMsg::RefcountCleanup(addr)) => { @@ -347,7 +325,7 @@ impl<'a> PrivateDedicatedWorkerGlobalScopeHelpers for &'a DedicatedWorkerGlobalS } } - fn handle_event(self, event: MixedMessage) { + fn handle_event(&self, event: MixedMessage) { match event { MixedMessage::FromDevtools(msg) => { let global_ref = GlobalRef::Worker(WorkerGlobalScopeCast::from_ref(self)); @@ -367,28 +345,19 @@ impl<'a> PrivateDedicatedWorkerGlobalScopeHelpers for &'a DedicatedWorkerGlobalS }, } } - - fn dispatch_error_to_worker(self, errorevent: &ErrorEvent) { - let msg = errorevent.Message(); - let file_name = errorevent.Filename(); - let line_num = errorevent.Lineno(); - let col_num = errorevent.Colno(); - let worker = self.worker.borrow().as_ref().unwrap().clone(); - self.parent_sender.send(CommonScriptMsg::RunnableMsg( - box WorkerErrorHandler::new(worker, msg, file_name, line_num, col_num))).unwrap(); - } } -impl<'a> DedicatedWorkerGlobalScopeMethods for &'a DedicatedWorkerGlobalScope { +impl DedicatedWorkerGlobalScopeMethods for DedicatedWorkerGlobalScope { // https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-postmessage - fn PostMessage(self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { + fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { let data = try!(StructuredCloneData::write(cx, message)); let worker = self.worker.borrow().as_ref().unwrap().clone(); - self.parent_sender.send(CommonScriptMsg::RunnableMsg( + self.parent_sender.send(CommonScriptMsg::RunnableMsg(WorkerEvent, box WorkerMessageHandler::new(worker, data))).unwrap(); Ok(()) } + // https://html.spec.whatwg.org/multipage/#handler-dedicatedworkerglobalscope-onmessage event_handler!(message, GetOnmessage, SetOnmessage); } diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index 7e5adec0353..196ea7af438 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use document_loader::{DocumentLoader, LoadType}; -use dom::attr::{Attr, AttrHelpers, AttrValue}; +use dom::attr::{Attr, AttrValue}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::DocumentBinding; use dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, DocumentReadyState}; @@ -41,23 +41,22 @@ use dom::customevent::CustomEvent; use dom::documentfragment::DocumentFragment; use dom::documenttype::DocumentType; use dom::domimplementation::DOMImplementation; -use dom::element::{Element, ElementCreator, ElementHelpers, AttributeHandlers}; -use dom::element::{ElementTypeId, ActivationElementHelpers, FocusElementHelpers}; -use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers}; -use dom::eventtarget::{EventTarget, EventTargetTypeId, EventTargetHelpers}; +use dom::element::{Element, ElementCreator, ElementTypeId}; +use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlanchorelement::HTMLAnchorElement; use dom::htmlbaseelement::HTMLBaseElement; use dom::htmlcollection::{HTMLCollection, CollectionFilter}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::htmlheadelement::HTMLHeadElement; use dom::htmlhtmlelement::HTMLHtmlElement; -use dom::htmliframeelement::HTMLIFrameElement; +use dom::htmliframeelement::{self, HTMLIFrameElement}; use dom::htmlscriptelement::HTMLScriptElement; use dom::keyboardevent::KeyboardEvent; use dom::location::Location; use dom::messageevent::MessageEvent; use dom::mouseevent::MouseEvent; -use dom::node::{self, Node, NodeHelpers, NodeTypeId, CloneChildrenFlag, NodeDamage, window_from_node}; +use dom::node::{self, Node, NodeTypeId, CloneChildrenFlag, NodeDamage, window_from_node}; use dom::nodeiterator::NodeIterator; use dom::nodelist::NodeList; use dom::processinginstruction::ProcessingInstruction; @@ -66,7 +65,7 @@ use dom::servohtmlparser::ServoHTMLParser; use dom::text::Text; use dom::treewalker::TreeWalker; use dom::uievent::UIEvent; -use dom::window::{Window, WindowHelpers, ReflowReason}; +use dom::window::{Window, ReflowReason}; use layout_interface::{HitTestResponse, MouseOverResponse}; use layout_interface::{ReflowGoal, ReflowQueryType}; @@ -80,7 +79,6 @@ use net_traits::CookieSource::NonHTTP; use net_traits::{Metadata, PendingAsyncLoad, AsyncResponseTarget}; use script_task::Runnable; use script_traits::{MouseButton, UntrustedNodeAddress}; -use util::opts; use util::str::{DOMString, split_html_space_chars}; use euclid::point::Point2D; @@ -113,7 +111,6 @@ pub enum IsHTMLDocument { // https://dom.spec.whatwg.org/#document #[dom_struct] -#[derive(HeapSizeOf)] pub struct Document { node: Node, window: JS, @@ -229,113 +226,35 @@ impl CollectionFilter for AppletsFilter { } } -pub trait DocumentHelpers<'a> { - fn loader(&self) -> Ref; - fn mut_loader(&self) -> RefMut; - fn window(self) -> Root; - fn encoding_name(self) -> Ref<'a, DOMString>; - fn is_html_document(self) -> bool; - fn is_fully_active(self) -> bool; - /// https://dom.spec.whatwg.org/#concept-document-url - fn url(self) -> Url; - /// https://html.spec.whatwg.org/multipage/#fallback-base-url - fn fallback_base_url(self) -> Url; - /// https://html.spec.whatwg.org/multipage/#document-base-url - fn base_url(self) -> Url; - /// Returns the first `base` element in the DOM that has an `href` attribute. - fn base_element(self) -> Option>; - /// Refresh the cached first base element in the DOM. - fn refresh_base_element(self); - fn quirks_mode(self) -> QuirksMode; - fn set_quirks_mode(self, mode: QuirksMode); - fn set_encoding_name(self, name: DOMString); - fn content_changed(self, node: &Node, damage: NodeDamage); - fn content_and_heritage_changed(self, node: &Node, damage: NodeDamage); - fn reflow_if_reflow_timer_expired(self); - fn set_reflow_timeout(self, timeout: u64); - fn disarm_reflow_timeout(self); - fn unregister_named_element(self, to_unregister: &Element, id: Atom); - fn register_named_element(self, element: &Element, id: Atom); - fn find_fragment_node(self, fragid: &str) -> Option>; - fn hit_test(self, point: &Point2D) -> Option; - fn get_nodes_under_mouse(self, point: &Point2D) -> Vec; - fn set_ready_state(self, state: DocumentReadyState); - fn get_focused_element(self) -> Option>; - fn is_scripting_enabled(self) -> bool; - fn begin_focus_transaction(self); - fn request_focus(self, elem: &Element); - fn commit_focus_transaction(self, focus_type: FocusType); - fn title_changed(self); - fn send_title_to_compositor(self); - fn dirty_all_nodes(self); - fn dispatch_key_event(self, - key: Key, - state: KeyState, - modifiers: KeyModifiers, - compositor: &mut IpcSender); - fn node_from_nodes_and_strings(self, nodes: Vec) - -> Fallible>; - fn get_body_attribute(self, local_name: &Atom) -> DOMString; - fn set_body_attribute(self, local_name: &Atom, value: DOMString); - fn fire_mouse_event(self, point: Point2D, - target: &EventTarget, - event_name: String); - fn handle_mouse_event(self, js_runtime: *mut JSRuntime, - button: MouseButton, point: Point2D, - mouse_event_type: MouseEventType); - /// Handles a mouse-move event coming from the compositor. - fn handle_mouse_move_event(self, - js_runtime: *mut JSRuntime, - point: Point2D, - prev_mouse_over_targets: &mut RootedVec>); - - fn set_current_script(self, script: Option<&HTMLScriptElement>); - fn trigger_mozbrowser_event(self, event: MozBrowserEvent); - /// https://html.spec.whatwg.org/multipage/#dom-window-requestanimationframe - fn request_animation_frame(self, callback: Box) -> i32; - /// https://html.spec.whatwg.org/multipage/#dom-window-cancelanimationframe - fn cancel_animation_frame(self, ident: i32); - /// https://html.spec.whatwg.org/multipage/#run-the-animation-frame-callbacks - fn run_the_animation_frame_callbacks(self); - fn prepare_async_load(self, load: LoadType) -> PendingAsyncLoad; - fn load_async(self, load: LoadType, listener: AsyncResponseTarget); - fn load_sync(self, load: LoadType) -> Result<(Metadata, Vec), String>; - fn finish_load(self, load: LoadType); - fn notify_constellation_load(self); - fn set_current_parser(self, script: Option<&ServoHTMLParser>); - fn get_current_parser(self) -> Option>; - fn find_iframe(self, subpage_id: SubpageId) -> Option>; -} - -impl<'a> DocumentHelpers<'a> for &'a Document { +impl Document { #[inline] - fn loader(&self) -> Ref { + pub fn loader(&self) -> Ref { self.loader.borrow() } #[inline] - fn mut_loader(&self) -> RefMut { + pub fn mut_loader(&self) -> RefMut { self.loader.borrow_mut() } #[inline] - fn window(self) -> Root { + pub fn window(&self) -> Root { self.window.root() } #[inline] - fn encoding_name(self) -> Ref<'a, DOMString> { + pub fn encoding_name(&self) -> Ref { self.encoding_name.borrow() } #[inline] - fn is_html_document(self) -> bool { + pub fn is_html_document(&self) -> bool { self.is_html_document } // https://html.spec.whatwg.org/multipage/#fully-active - fn is_fully_active(self) -> bool { + pub fn is_fully_active(&self) -> bool { let window = self.window.root(); let window = window.r(); let browsing_context = window.browsing_context(); @@ -350,12 +269,12 @@ impl<'a> DocumentHelpers<'a> for &'a Document { } // https://dom.spec.whatwg.org/#concept-document-url - fn url(self) -> Url { + pub fn url(&self) -> Url { self.url.clone() } // https://html.spec.whatwg.org/multipage/#fallback-base-url - fn fallback_base_url(self) -> Url { + pub fn fallback_base_url(&self) -> Url { // Step 1: iframe srcdoc (#4767). // Step 2: about:blank with a creator browsing context. // Step 3. @@ -363,7 +282,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { } // https://html.spec.whatwg.org/multipage/#document-base-url - fn base_url(self) -> Url { + pub fn base_url(&self) -> Url { match self.base_element() { // Step 1. None => self.fallback_base_url(), @@ -373,12 +292,12 @@ impl<'a> DocumentHelpers<'a> for &'a Document { } /// Returns the first `base` element in the DOM that has an `href` attribute. - fn base_element(self) -> Option> { + pub fn base_element(&self) -> Option> { self.base_element.get().map(Root::from_rooted) } /// Refresh the cached first base element in the DOM. - fn refresh_base_element(self) { + pub fn refresh_base_element(&self) { let base = NodeCast::from_ref(self) .traverse_preorder() .filter_map(HTMLBaseElementCast::to_root) @@ -387,11 +306,11 @@ impl<'a> DocumentHelpers<'a> for &'a Document { self.base_element.set(base.map(|element| JS::from_ref(&*element))); } - fn quirks_mode(self) -> QuirksMode { + pub fn quirks_mode(&self) -> QuirksMode { self.quirks_mode.get() } - fn set_quirks_mode(self, mode: QuirksMode) { + pub fn set_quirks_mode(&self, mode: QuirksMode) { self.quirks_mode.set(mode); if mode == Quirks { @@ -402,21 +321,21 @@ impl<'a> DocumentHelpers<'a> for &'a Document { } } - fn set_encoding_name(self, name: DOMString) { + pub fn set_encoding_name(&self, name: DOMString) { *self.encoding_name.borrow_mut() = name; } - fn content_changed(self, node: &Node, damage: NodeDamage) { + pub fn content_changed(&self, node: &Node, damage: NodeDamage) { node.dirty(damage); } - fn content_and_heritage_changed(self, node: &Node, damage: NodeDamage) { + pub fn content_and_heritage_changed(&self, node: &Node, damage: NodeDamage) { node.force_dirty_ancestors(damage); node.dirty(damage); } /// Reflows and disarms the timer if the reflow timer has expired. - fn reflow_if_reflow_timer_expired(self) { + pub fn reflow_if_reflow_timer_expired(&self) { if let Some(reflow_timeout) = self.reflow_timeout.get() { if time::precise_time_ns() < reflow_timeout { return @@ -433,7 +352,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { /// Schedules a reflow to be kicked off at the given `timeout` (in `time::precise_time_ns()` /// units). This reflow happens even if the event loop is busy. This is used to display initial /// page content during parsing. - fn set_reflow_timeout(self, timeout: u64) { + pub fn set_reflow_timeout(&self, timeout: u64) { if let Some(existing_timeout) = self.reflow_timeout.get() { if existing_timeout < timeout { return @@ -443,12 +362,12 @@ impl<'a> DocumentHelpers<'a> for &'a Document { } /// Disables any pending reflow timeouts. - fn disarm_reflow_timeout(self) { + pub fn disarm_reflow_timeout(&self) { self.reflow_timeout.set(None) } /// Remove any existing association between the provided id and any elements in this document. - fn unregister_named_element(self, + pub fn unregister_named_element(&self, to_unregister: &Element, id: Atom) { debug!("Removing named element from document {:p}: {:p} id={}", self, to_unregister, id); @@ -470,7 +389,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { } /// Associate an element present in this document with the provided id. - fn register_named_element(self, + pub fn register_named_element(&self, element: &Element, id: Atom) { debug!("Adding named element to document {:p}: {:p} id={}", self, element, id); @@ -513,7 +432,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { /// Attempt to find a named element in this page's document. /// https://html.spec.whatwg.org/multipage/#the-indicated-part-of-the-document - fn find_fragment_node(self, fragid: &str) -> Option> { + pub fn find_fragment_node(&self, fragid: &str) -> Option> { self.GetElementById(fragid.to_owned()).or_else(|| { let check_anchor = |&node: &&HTMLAnchorElement| { let elem = ElementCast::from_ref(node); @@ -529,7 +448,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { }) } - fn hit_test(self, point: &Point2D) -> Option { + pub fn hit_test(&self, point: &Point2D) -> Option { let root = self.GetDocumentElement(); let root = match root.r() { Some(root) => root, @@ -547,7 +466,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { address } - fn get_nodes_under_mouse(self, point: &Point2D) -> Vec { + pub fn get_nodes_under_mouse(&self, point: &Point2D) -> Vec { let root = self.GetDocumentElement(); let root = match root.r() { Some(root) => root, @@ -562,7 +481,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { } // https://html.spec.whatwg.org/multipage/#current-document-readiness - fn set_ready_state(self, state: DocumentReadyState) { + pub fn set_ready_state(&self, state: DocumentReadyState) { self.ready_state.set(state); let window = self.window.root(); @@ -574,24 +493,24 @@ impl<'a> DocumentHelpers<'a> for &'a Document { } /// Return whether scripting is enabled or not - fn is_scripting_enabled(self) -> bool { + pub fn is_scripting_enabled(&self) -> bool { self.scripting_enabled.get() } /// Return the element that currently has focus. // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#events-focusevent-doc-focus - fn get_focused_element(self) -> Option> { + pub fn get_focused_element(&self) -> Option> { self.focused.get().map(Root::from_rooted) } /// Initiate a new round of checking for elements requesting focus. The last element to call /// `request_focus` before `commit_focus_transaction` is called will receive focus. - fn begin_focus_transaction(self) { + pub fn begin_focus_transaction(&self) { self.possibly_focused.set(None); } /// Request that the given element receive focus once the current transaction is complete. - fn request_focus(self, elem: &Element) { + pub fn request_focus(&self, elem: &Element) { if elem.is_focusable_area() { self.possibly_focused.set(Some(JS::from_ref(elem))) } @@ -599,7 +518,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { /// Reassign the focus context to the element that last requested focus during this /// transaction, or none if no elements requested it. - fn commit_focus_transaction(self, focus_type: FocusType) { + pub fn commit_focus_transaction(&self, focus_type: FocusType) { //TODO: dispatch blur, focus, focusout, and focusin events if let Some(ref elem) = self.focused.get().map(|t| t.root()) { @@ -625,7 +544,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { } /// Handles any updates when the document's title has changed. - fn title_changed(self) { + pub fn title_changed(&self) { // https://developer.mozilla.org/en-US/docs/Web/Events/mozbrowsertitlechange self.trigger_mozbrowser_event(MozBrowserEvent::TitleChange(self.Title())); @@ -633,7 +552,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { } /// Sends this document's title to the compositor. - fn send_title_to_compositor(self) { + pub fn send_title_to_compositor(&self) { let window = self.window(); // FIXME(https://github.com/rust-lang/rust/issues/23338) let window = window.r(); @@ -641,14 +560,14 @@ impl<'a> DocumentHelpers<'a> for &'a Document { compositor.send(ScriptToCompositorMsg::SetTitle(window.pipeline(), Some(self.Title()))).unwrap(); } - fn dirty_all_nodes(self) { + pub fn dirty_all_nodes(&self) { let root = NodeCast::from_ref(self); for node in root.traverse_preorder() { node.r().dirty(NodeDamage::OtherNodeDamage) } } - fn handle_mouse_event(self, js_runtime: *mut JSRuntime, + pub fn handle_mouse_event(&self, js_runtime: *mut JSRuntime, _button: MouseButton, point: Point2D, mouse_event_type: MouseEventType) { let mouse_event_type_string = match mouse_event_type { @@ -722,7 +641,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { window.r().reflow(ReflowGoal::ForDisplay, ReflowQueryType::NoQuery, ReflowReason::MouseEvent); } - fn fire_mouse_event(self, + pub fn fire_mouse_event(&self, point: Point2D, target: &EventTarget, event_name: String) { @@ -745,7 +664,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { event.fire(target); } - fn handle_mouse_move_event(self, + pub fn handle_mouse_move_event(&self, js_runtime: *mut JSRuntime, point: Point2D, prev_mouse_over_targets: &mut RootedVec>) { @@ -809,7 +728,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { } /// The entry point for all key processing for web content - fn dispatch_key_event(self, + pub fn dispatch_key_event(&self, key: Key, state: KeyState, modifiers: KeyModifiers, @@ -888,7 +807,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { window.r().reflow(ReflowGoal::ForDisplay, ReflowQueryType::NoQuery, ReflowReason::KeyEvent); } - fn node_from_nodes_and_strings(self, nodes: Vec) + pub fn node_from_nodes_and_strings(&self, nodes: Vec) -> Fallible> { if nodes.len() == 1 { match nodes.into_iter().next().unwrap() { @@ -916,7 +835,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { } } - fn get_body_attribute(self, local_name: &Atom) -> DOMString { + pub fn get_body_attribute(&self, local_name: &Atom) -> DOMString { match self.GetBody().and_then(HTMLBodyElementCast::to_root) { Some(ref body) => { ElementCast::from_ref(body.r()).get_string_attribute(local_name) @@ -925,18 +844,18 @@ impl<'a> DocumentHelpers<'a> for &'a Document { } } - fn set_body_attribute(self, local_name: &Atom, value: DOMString) { + pub fn set_body_attribute(&self, local_name: &Atom, value: DOMString) { if let Some(ref body) = self.GetBody().and_then(HTMLBodyElementCast::to_root) { ElementCast::from_ref(body.r()).set_string_attribute(local_name, value); } } - fn set_current_script(self, script: Option<&HTMLScriptElement>) { + pub fn set_current_script(&self, script: Option<&HTMLScriptElement>) { self.current_script.set(script.map(JS::from_ref)); } - fn trigger_mozbrowser_event(self, event: MozBrowserEvent) { - if opts::experimental_enabled() { + pub fn trigger_mozbrowser_event(&self, event: MozBrowserEvent) { + if htmliframeelement::mozbrowser_enabled() { let window = self.window.root(); if let Some((containing_pipeline_id, subpage_id)) = window.r().parent_info() { @@ -950,7 +869,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { } /// https://html.spec.whatwg.org/multipage/#dom-window-requestanimationframe - fn request_animation_frame(self, callback: Box) -> i32 { + pub fn request_animation_frame(&self, callback: Box) -> i32 { let window = self.window.root(); let window = window.r(); let ident = self.animation_frame_ident.get() + 1; @@ -968,7 +887,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { } /// https://html.spec.whatwg.org/multipage/#dom-window-cancelanimationframe - fn cancel_animation_frame(self, ident: i32) { + pub fn cancel_animation_frame(&self, ident: i32) { self.animation_frame_list.borrow_mut().remove(&ident); if self.animation_frame_list.borrow().is_empty() { let window = self.window.root(); @@ -981,7 +900,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { } /// https://html.spec.whatwg.org/multipage/#run-the-animation-frame-callbacks - fn run_the_animation_frame_callbacks(self) { + pub fn run_the_animation_frame_callbacks(&self) { let animation_frame_list; { let mut list = self.animation_frame_list.borrow_mut(); @@ -1009,27 +928,27 @@ impl<'a> DocumentHelpers<'a> for &'a Document { ReflowReason::RequestAnimationFrame); } - fn prepare_async_load(self, load: LoadType) -> PendingAsyncLoad { + pub fn prepare_async_load(&self, load: LoadType) -> PendingAsyncLoad { let mut loader = self.loader.borrow_mut(); loader.prepare_async_load(load) } - fn load_async(self, load: LoadType, listener: AsyncResponseTarget) { + pub fn load_async(&self, load: LoadType, listener: AsyncResponseTarget) { let mut loader = self.loader.borrow_mut(); loader.load_async(load, listener) } - fn load_sync(self, load: LoadType) -> Result<(Metadata, Vec), String> { + pub fn load_sync(&self, load: LoadType) -> Result<(Metadata, Vec), String> { let mut loader = self.loader.borrow_mut(); loader.load_sync(load) } - fn finish_load(self, load: LoadType) { + pub fn finish_load(&self, load: LoadType) { let mut loader = self.loader.borrow_mut(); loader.finish_load(load); } - fn notify_constellation_load(self) { + pub fn notify_constellation_load(&self) { let window = self.window.root(); let pipeline_id = window.r().pipeline(); let ConstellationChan(ref chan) = window.r().constellation_chan(); @@ -1038,16 +957,16 @@ impl<'a> DocumentHelpers<'a> for &'a Document { } - fn set_current_parser(self, script: Option<&ServoHTMLParser>) { + pub fn set_current_parser(&self, script: Option<&ServoHTMLParser>) { self.current_parser.set(script.map(JS::from_ref)); } - fn get_current_parser(self) -> Option> { + pub fn get_current_parser(&self) -> Option> { self.current_parser.get().map(Root::from_rooted) } /// Find an iframe element in the document. - fn find_iframe(self, subpage_id: SubpageId) -> Option> { + pub fn find_iframe(&self, subpage_id: SubpageId) -> Option> { NodeCast::from_ref(self).traverse_preorder() .filter_map(HTMLIFrameElementCast::to_root) .find(|node| node.r().subpage_id() == Some(subpage_id)) @@ -1170,15 +1089,8 @@ impl Document { } document } -} -trait PrivateDocumentHelpers { - fn create_node_list bool>(self, callback: F) -> Root; - fn get_html_element(self) -> Option>; -} - -impl<'a> PrivateDocumentHelpers for &'a Document { - fn create_node_list bool>(self, callback: F) -> Root { + fn create_node_list bool>(&self, callback: F) -> Root { let window = self.window.root(); let doc = self.GetDocumentElement(); let maybe_node = doc.r().map(NodeCast::from_ref); @@ -1187,7 +1099,7 @@ impl<'a> PrivateDocumentHelpers for &'a Document { NodeList::new_simple_list(window.r(), iter) } - fn get_html_element(self) -> Option> { + fn get_html_element(&self) -> Option> { self.GetDocumentElement() .r() .and_then(HTMLHtmlElementCast::to_ref) @@ -1195,12 +1107,9 @@ impl<'a> PrivateDocumentHelpers for &'a Document { } } -trait PrivateClickEventHelpers { - fn click_event_filter_by_disabled_state(self) -> bool; -} -impl<'a> PrivateClickEventHelpers for &'a Node { - fn click_event_filter_by_disabled_state(self) -> bool { +impl Node { + fn click_event_filter_by_disabled_state(&self) -> bool { match self.type_id() { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) | NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) | @@ -1214,19 +1123,19 @@ impl<'a> PrivateClickEventHelpers for &'a Node { } } -impl<'a> DocumentMethods for &'a Document { +impl DocumentMethods for Document { // https://dom.spec.whatwg.org/#dom-document-implementation - fn Implementation(self) -> Root { + fn Implementation(&self) -> Root { self.implementation.or_init(|| DOMImplementation::new(self)) } // https://dom.spec.whatwg.org/#dom-document-url - fn URL(self) -> DOMString { + fn URL(&self) -> DOMString { self.url().serialize() } // https://html.spec.whatwg.org/multipage/#dom-document-activeelement - fn GetActiveElement(self) -> Option> { + fn GetActiveElement(&self) -> Option> { // TODO: Step 2. match self.get_focused_element() { @@ -1239,7 +1148,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://html.spec.whatwg.org/#dom-document-hasfocus - fn HasFocus(self) -> bool { + fn HasFocus(&self) -> bool { let target = self; // Step 1. let window = self.window.root(); let window = window.r(); @@ -1260,12 +1169,12 @@ impl<'a> DocumentMethods for &'a Document { } // https://dom.spec.whatwg.org/#dom-document-documenturi - fn DocumentURI(self) -> DOMString { + fn DocumentURI(&self) -> DOMString { self.URL() } // https://dom.spec.whatwg.org/#dom-document-compatmode - fn CompatMode(self) -> DOMString { + fn CompatMode(&self) -> DOMString { match self.quirks_mode.get() { LimitedQuirks | NoQuirks => "CSS1Compat".to_owned(), Quirks => "BackCompat".to_owned() @@ -1273,22 +1182,22 @@ impl<'a> DocumentMethods for &'a Document { } // https://dom.spec.whatwg.org/#dom-document-characterset - fn CharacterSet(self) -> DOMString { + fn CharacterSet(&self) -> DOMString { self.encoding_name.borrow().clone() } // https://dom.spec.whatwg.org/#dom-document-inputencoding - fn InputEncoding(self) -> DOMString { + fn InputEncoding(&self) -> DOMString { self.encoding_name.borrow().clone() } // https://dom.spec.whatwg.org/#dom-document-content_type - fn ContentType(self) -> DOMString { + fn ContentType(&self) -> DOMString { self.content_type.clone() } // https://dom.spec.whatwg.org/#dom-document-doctype - fn GetDoctype(self) -> Option> { + fn GetDoctype(&self) -> Option> { let node = NodeCast::from_ref(self); node.children() .filter_map(|c| DocumentTypeCast::to_ref(c.r()).map(Root::from_ref)) @@ -1296,39 +1205,39 @@ impl<'a> DocumentMethods for &'a Document { } // https://dom.spec.whatwg.org/#dom-document-documentelement - fn GetDocumentElement(self) -> Option> { + fn GetDocumentElement(&self) -> Option> { let node = NodeCast::from_ref(self); node.child_elements().next() } // https://dom.spec.whatwg.org/#dom-document-getelementsbytagname - fn GetElementsByTagName(self, tag_name: DOMString) -> Root { + fn GetElementsByTagName(&self, tag_name: DOMString) -> Root { let window = self.window.root(); HTMLCollection::by_tag_name(window.r(), NodeCast::from_ref(self), tag_name) } // https://dom.spec.whatwg.org/#dom-document-getelementsbytagnamens - fn GetElementsByTagNameNS(self, maybe_ns: Option, tag_name: DOMString) + fn GetElementsByTagNameNS(&self, maybe_ns: Option, tag_name: DOMString) -> Root { let window = self.window.root(); HTMLCollection::by_tag_name_ns(window.r(), NodeCast::from_ref(self), tag_name, maybe_ns) } // https://dom.spec.whatwg.org/#dom-document-getelementsbyclassname - fn GetElementsByClassName(self, classes: DOMString) -> Root { + fn GetElementsByClassName(&self, classes: DOMString) -> Root { let window = self.window.root(); HTMLCollection::by_class_name(window.r(), NodeCast::from_ref(self), classes) } // https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid - fn GetElementById(self, id: DOMString) -> Option> { + fn GetElementById(&self, id: DOMString) -> Option> { let id = Atom::from_slice(&id); self.idmap.borrow().get(&id).map(|ref elements| (*elements)[0].root()) } // https://dom.spec.whatwg.org/#dom-document-createelement - fn CreateElement(self, mut local_name: DOMString) -> Fallible> { + fn CreateElement(&self, mut local_name: DOMString) -> Fallible> { if xml_name_type(&local_name) == InvalidXMLName { debug!("Not a valid element name"); return Err(InvalidCharacter); @@ -1341,7 +1250,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://dom.spec.whatwg.org/#dom-document-createelementns - fn CreateElementNS(self, + fn CreateElementNS(&self, namespace: Option, qualified_name: DOMString) -> Fallible> { let (namespace, prefix, local_name) = @@ -1351,7 +1260,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://dom.spec.whatwg.org/#dom-document-createattribute - fn CreateAttribute(self, local_name: DOMString) -> Fallible> { + fn CreateAttribute(&self, local_name: DOMString) -> Fallible> { if xml_name_type(&local_name) == InvalidXMLName { debug!("Not a valid element name"); return Err(InvalidCharacter); @@ -1367,7 +1276,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://dom.spec.whatwg.org/#dom-document-createattributens - fn CreateAttributeNS(self, namespace: Option, qualified_name: DOMString) + fn CreateAttributeNS(&self, namespace: Option, qualified_name: DOMString) -> Fallible> { let (namespace, prefix, local_name) = try!(validate_and_extract(namespace, &qualified_name)); @@ -1379,22 +1288,22 @@ impl<'a> DocumentMethods for &'a Document { } // https://dom.spec.whatwg.org/#dom-document-createdocumentfragment - fn CreateDocumentFragment(self) -> Root { + fn CreateDocumentFragment(&self) -> Root { DocumentFragment::new(self) } // https://dom.spec.whatwg.org/#dom-document-createtextnode - fn CreateTextNode(self, data: DOMString) -> Root { + fn CreateTextNode(&self, data: DOMString) -> Root { Text::new(data, self) } // https://dom.spec.whatwg.org/#dom-document-createcomment - fn CreateComment(self, data: DOMString) -> Root { + fn CreateComment(&self, data: DOMString) -> Root { Comment::new(data, self) } // https://dom.spec.whatwg.org/#dom-document-createprocessinginstruction - fn CreateProcessingInstruction(self, target: DOMString, data: DOMString) -> + fn CreateProcessingInstruction(&self, target: DOMString, data: DOMString) -> Fallible> { // Step 1. if xml_name_type(&target) == InvalidXMLName { @@ -1411,7 +1320,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://dom.spec.whatwg.org/#dom-document-importnode - fn ImportNode(self, node: &Node, deep: bool) -> Fallible> { + fn ImportNode(&self, node: &Node, deep: bool) -> Fallible> { // Step 1. if node.is_document() { return Err(NotSupported); @@ -1427,7 +1336,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://dom.spec.whatwg.org/#dom-document-adoptnode - fn AdoptNode(self, node: &Node) -> Fallible> { + fn AdoptNode(&self, node: &Node) -> Fallible> { // Step 1. if node.is_document() { return Err(NotSupported); @@ -1441,7 +1350,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://dom.spec.whatwg.org/#dom-document-createevent - fn CreateEvent(self, interface: DOMString) -> Fallible> { + fn CreateEvent(&self, interface: DOMString) -> Fallible> { let window = self.window.root(); match &*interface.to_ascii_lowercase() { @@ -1462,7 +1371,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://html.spec.whatwg.org/#dom-document-lastmodified - fn LastModified(self) -> DOMString { + fn LastModified(&self) -> DOMString { match self.last_modified { Some(ref t) => t.clone(), None => time::now().strftime("%m/%d/%Y %H:%M:%S").unwrap().to_string(), @@ -1470,24 +1379,24 @@ impl<'a> DocumentMethods for &'a Document { } // https://dom.spec.whatwg.org/#dom-document-createrange - fn CreateRange(self) -> Root { + fn CreateRange(&self) -> Root { Range::new_with_doc(self) } // https://dom.spec.whatwg.org/#dom-document-createnodeiteratorroot-whattoshow-filter - fn CreateNodeIterator(self, root: &Node, whatToShow: u32, filter: Option>) + fn CreateNodeIterator(&self, root: &Node, whatToShow: u32, filter: Option>) -> Root { NodeIterator::new(self, root, whatToShow, filter) } // https://dom.spec.whatwg.org/#dom-document-createtreewalker - fn CreateTreeWalker(self, root: &Node, whatToShow: u32, filter: Option>) + fn CreateTreeWalker(&self, root: &Node, whatToShow: u32, filter: Option>) -> Root { TreeWalker::new(self, root, whatToShow, filter) } // https://html.spec.whatwg.org/#document.title - fn Title(self) -> DOMString { + fn Title(&self) -> DOMString { let title = self.GetDocumentElement().and_then(|root| { if root.r().namespace() == &ns!(SVG) && root.r().local_name() == &atom!("svg") { // Step 1. @@ -1514,7 +1423,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://html.spec.whatwg.org/#document.title - fn SetTitle(self, title: DOMString) { + fn SetTitle(&self, title: DOMString) { let root = match self.GetDocumentElement() { Some(root) => root, None => return, @@ -1565,7 +1474,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://html.spec.whatwg.org/#dom-document-head - fn GetHead(self) -> Option> { + fn GetHead(&self) -> Option> { self.get_html_element().and_then(|root| { let node = NodeCast::from_ref(root.r()); node.children() @@ -1575,12 +1484,12 @@ impl<'a> DocumentMethods for &'a Document { } // https://html.spec.whatwg.org/#dom-document-currentscript - fn GetCurrentScript(self) -> Option> { + fn GetCurrentScript(&self) -> Option> { self.current_script.get().map(Root::from_rooted) } // https://html.spec.whatwg.org/#dom-document-body - fn GetBody(self) -> Option> { + fn GetBody(&self) -> Option> { self.get_html_element().and_then(|root| { let node = NodeCast::from_ref(root.r()); node.children().find(|child| { @@ -1596,7 +1505,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://html.spec.whatwg.org/#dom-document-body - fn SetBody(self, new_body: Option<&HTMLElement>) -> ErrorResult { + fn SetBody(&self, new_body: Option<&HTMLElement>) -> ErrorResult { // Step 1. let new_body = match new_body { Some(new_body) => new_body, @@ -1639,7 +1548,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://html.spec.whatwg.org/#dom-document-getelementsbyname - fn GetElementsByName(self, name: DOMString) -> Root { + fn GetElementsByName(&self, name: DOMString) -> Root { self.create_node_list(|node| { let element = match ElementCast::to_ref(node) { Some(element) => element, @@ -1655,7 +1564,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://html.spec.whatwg.org/#dom-document-images - fn Images(self) -> Root { + fn Images(&self) -> Root { self.images.or_init(|| { let window = self.window.root(); let root = NodeCast::from_ref(self); @@ -1665,7 +1574,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://html.spec.whatwg.org/#dom-document-embeds - fn Embeds(self) -> Root { + fn Embeds(&self) -> Root { self.embeds.or_init(|| { let window = self.window.root(); let root = NodeCast::from_ref(self); @@ -1675,12 +1584,12 @@ impl<'a> DocumentMethods for &'a Document { } // https://html.spec.whatwg.org/#dom-document-plugins - fn Plugins(self) -> Root { + fn Plugins(&self) -> Root { self.Embeds() } // https://html.spec.whatwg.org/#dom-document-links - fn Links(self) -> Root { + fn Links(&self) -> Root { self.links.or_init(|| { let window = self.window.root(); let root = NodeCast::from_ref(self); @@ -1690,7 +1599,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://html.spec.whatwg.org/#dom-document-forms - fn Forms(self) -> Root { + fn Forms(&self) -> Root { self.forms.or_init(|| { let window = self.window.root(); let root = NodeCast::from_ref(self); @@ -1700,7 +1609,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://html.spec.whatwg.org/#dom-document-scripts - fn Scripts(self) -> Root { + fn Scripts(&self) -> Root { self.scripts.or_init(|| { let window = self.window.root(); let root = NodeCast::from_ref(self); @@ -1710,7 +1619,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://html.spec.whatwg.org/#dom-document-anchors - fn Anchors(self) -> Root { + fn Anchors(&self) -> Root { self.anchors.or_init(|| { let window = self.window.root(); let root = NodeCast::from_ref(self); @@ -1720,7 +1629,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://html.spec.whatwg.org/#dom-document-applets - fn Applets(self) -> Root { + fn Applets(&self) -> Root { // FIXME: This should be return OBJECT elements containing applets. self.applets.or_init(|| { let window = self.window.root(); @@ -1731,67 +1640,67 @@ impl<'a> DocumentMethods for &'a Document { } // https://html.spec.whatwg.org/#dom-document-location - fn Location(self) -> Root { + fn Location(&self) -> Root { let window = self.window.root(); let window = window.r(); self.location.or_init(|| Location::new(window)) } // https://dom.spec.whatwg.org/#dom-parentnode-children - fn Children(self) -> Root { + fn Children(&self) -> Root { let window = self.window.root(); HTMLCollection::children(window.r(), NodeCast::from_ref(self)) } // https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild - fn GetFirstElementChild(self) -> Option> { + fn GetFirstElementChild(&self) -> Option> { NodeCast::from_ref(self).child_elements().next() } // https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild - fn GetLastElementChild(self) -> Option> { + fn GetLastElementChild(&self) -> Option> { NodeCast::from_ref(self).rev_children().filter_map(ElementCast::to_root).next() } // https://dom.spec.whatwg.org/#dom-parentnode-childelementcount - fn ChildElementCount(self) -> u32 { + fn ChildElementCount(&self) -> u32 { NodeCast::from_ref(self).child_elements().count() as u32 } // https://dom.spec.whatwg.org/#dom-parentnode-prepend - fn Prepend(self, nodes: Vec) -> ErrorResult { + fn Prepend(&self, nodes: Vec) -> ErrorResult { NodeCast::from_ref(self).prepend(nodes) } // https://dom.spec.whatwg.org/#dom-parentnode-append - fn Append(self, nodes: Vec) -> ErrorResult { + fn Append(&self, nodes: Vec) -> ErrorResult { NodeCast::from_ref(self).append(nodes) } // https://dom.spec.whatwg.org/#dom-parentnode-queryselector - fn QuerySelector(self, selectors: DOMString) -> Fallible>> { + fn QuerySelector(&self, selectors: DOMString) -> Fallible>> { let root = NodeCast::from_ref(self); root.query_selector(selectors) } // https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall - fn QuerySelectorAll(self, selectors: DOMString) -> Fallible> { + fn QuerySelectorAll(&self, selectors: DOMString) -> Fallible> { let root = NodeCast::from_ref(self); root.query_selector_all(selectors) } // https://html.spec.whatwg.org/multipage/#dom-document-readystate - fn ReadyState(self) -> DocumentReadyState { + fn ReadyState(&self) -> DocumentReadyState { self.ready_state.get() } // https://html.spec.whatwg.org/multipage/#dom-document-defaultview - fn DefaultView(self) -> Root { + fn DefaultView(&self) -> Root { self.window.root() } // https://html.spec.whatwg.org/multipage/#dom-document-cookie - fn GetCookie(self) -> Fallible { + fn GetCookie(&self) -> Fallible { //TODO: return empty string for cookie-averse Document let url = self.url(); if !is_scheme_host_port_tuple(&url) { @@ -1805,7 +1714,7 @@ impl<'a> DocumentMethods for &'a Document { } // https://html.spec.whatwg.org/multipage/#dom-document-cookie - fn SetCookie(self, cookie: DOMString) -> ErrorResult { + fn SetCookie(&self, cookie: DOMString) -> ErrorResult { //TODO: ignore for cookie-averse Document let url = self.url(); if !is_scheme_host_port_tuple(&url) { @@ -1817,17 +1726,17 @@ impl<'a> DocumentMethods for &'a Document { } // https://html.spec.whatwg.org/multipage/#dom-document-bgcolor - fn BgColor(self) -> DOMString { + fn BgColor(&self) -> DOMString { self.get_body_attribute(&atom!("bgcolor")) } // https://html.spec.whatwg.org/multipage/#dom-document-bgcolor - fn SetBgColor(self, value: DOMString) { + fn SetBgColor(&self, value: DOMString) { self.set_body_attribute(&atom!("bgcolor"), value) } // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter - fn NamedGetter(self, _cx: *mut JSContext, name: DOMString, found: &mut bool) + fn NamedGetter(&self, _cx: *mut JSContext, name: DOMString, found: &mut bool) -> *mut JSObject { #[derive(JSTraceable, HeapSizeOf)] struct NamedElementFilter { @@ -1912,13 +1821,31 @@ impl<'a> DocumentMethods for &'a Document { collection.r().reflector().get_jsobject().get() } - // https://html.spec.whatwg.org/#document - fn SupportedPropertyNames(self) -> Vec { + // https://html.spec.whatwg.org/multipage/#document + fn SupportedPropertyNames(&self) -> Vec { // FIXME: unimplemented (https://github.com/servo/servo/issues/7273) vec![] } + // https://html.spec.whatwg.org/multipage/#dom-document-clear + fn Clear(&self) { + // This method intentionally does nothing + } + + // https://html.spec.whatwg.org/multipage/#dom-document-captureevents + fn CaptureEvents(&self) { + // This method intentionally does nothing + } + + // https://html.spec.whatwg.org/#dom-document-releaseevents + fn ReleaseEvents(&self) { + // This method intentionally does nothing + } + + // https://html.spec.whatwg.org/multipage/#globaleventhandlers global_event_handlers!(); + + // https://html.spec.whatwg.org/multipage/#handler-onreadystatechange event_handler!(readystatechange, GetOnreadystatechange, SetOnreadystatechange); } diff --git a/components/script/dom/documentfragment.rs b/components/script/dom/documentfragment.rs index 6ffba9208f7..2f0ccecda5c 100644 --- a/components/script/dom/documentfragment.rs +++ b/components/script/dom/documentfragment.rs @@ -15,13 +15,12 @@ use dom::document::Document; use dom::element::Element; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlcollection::HTMLCollection; -use dom::node::{Node, NodeHelpers, NodeTypeId, window_from_node}; +use dom::node::{Node, NodeTypeId, window_from_node}; use dom::nodelist::NodeList; use util::str::DOMString; // https://dom.spec.whatwg.org/#documentfragment #[dom_struct] -#[derive(HeapSizeOf)] pub struct DocumentFragment { node: Node, } @@ -52,48 +51,47 @@ impl DocumentFragment { } } -impl<'a> DocumentFragmentMethods for &'a DocumentFragment { +impl DocumentFragmentMethods for DocumentFragment { // https://dom.spec.whatwg.org/#dom-parentnode-children - fn Children(self) -> Root { + fn Children(&self) -> Root { let window = window_from_node(self); HTMLCollection::children(window.r(), NodeCast::from_ref(self)) } // https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild - fn GetFirstElementChild(self) -> Option> { + fn GetFirstElementChild(&self) -> Option> { NodeCast::from_ref(self).child_elements().next() } // https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild - fn GetLastElementChild(self) -> Option> { + fn GetLastElementChild(&self) -> Option> { NodeCast::from_ref(self).rev_children().filter_map(ElementCast::to_root).next() } // https://dom.spec.whatwg.org/#dom-parentnode-childelementcount - fn ChildElementCount(self) -> u32 { + fn ChildElementCount(&self) -> u32 { NodeCast::from_ref(self).child_elements().count() as u32 } // https://dom.spec.whatwg.org/#dom-parentnode-prepend - fn Prepend(self, nodes: Vec) -> ErrorResult { + fn Prepend(&self, nodes: Vec) -> ErrorResult { NodeCast::from_ref(self).prepend(nodes) } // https://dom.spec.whatwg.org/#dom-parentnode-append - fn Append(self, nodes: Vec) -> ErrorResult { + fn Append(&self, nodes: Vec) -> ErrorResult { NodeCast::from_ref(self).append(nodes) } // https://dom.spec.whatwg.org/#dom-parentnode-queryselector - fn QuerySelector(self, selectors: DOMString) -> Fallible>> { + fn QuerySelector(&self, selectors: DOMString) -> Fallible>> { let root = NodeCast::from_ref(self); root.query_selector(selectors) } // https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall - fn QuerySelectorAll(self, selectors: DOMString) -> Fallible> { + fn QuerySelectorAll(&self, selectors: DOMString) -> Fallible> { let root = NodeCast::from_ref(self); root.query_selector_all(selectors) } } - diff --git a/components/script/dom/documenttype.rs b/components/script/dom/documenttype.rs index 2a13acb2fe2..265c918b466 100644 --- a/components/script/dom/documenttype.rs +++ b/components/script/dom/documenttype.rs @@ -10,7 +10,7 @@ use dom::bindings::error::ErrorResult; use dom::bindings::js::Root; use dom::document::Document; use dom::eventtarget::{EventTarget, EventTargetTypeId}; -use dom::node::{Node, NodeHelpers, NodeTypeId}; +use dom::node::{Node, NodeTypeId}; use util::str::DOMString; use std::borrow::ToOwned; @@ -18,7 +18,6 @@ use std::borrow::ToOwned; // https://dom.spec.whatwg.org/#documenttype /// The `DOCTYPE` tag. #[dom_struct] -#[derive(HeapSizeOf)] pub struct DocumentType { node: Node, name: DOMString, @@ -74,41 +73,40 @@ impl DocumentType { } } -impl<'a> DocumentTypeMethods for &'a DocumentType { +impl DocumentTypeMethods for DocumentType { // https://dom.spec.whatwg.org/#dom-documenttype-name - fn Name(self) -> DOMString { + fn Name(&self) -> DOMString { self.name.clone() } // https://dom.spec.whatwg.org/#dom-documenttype-publicid - fn PublicId(self) -> DOMString { + fn PublicId(&self) -> DOMString { self.public_id.clone() } // https://dom.spec.whatwg.org/#dom-documenttype-systemid - fn SystemId(self) -> DOMString { + fn SystemId(&self) -> DOMString { self.system_id.clone() } // https://dom.spec.whatwg.org/#dom-childnode-before - fn Before(self, nodes: Vec) -> ErrorResult { + fn Before(&self, nodes: Vec) -> ErrorResult { NodeCast::from_ref(self).before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after - fn After(self, nodes: Vec) -> ErrorResult { + fn After(&self, nodes: Vec) -> ErrorResult { NodeCast::from_ref(self).after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith - fn ReplaceWith(self, nodes: Vec) -> ErrorResult { + fn ReplaceWith(&self, nodes: Vec) -> ErrorResult { NodeCast::from_ref(self).replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove - fn Remove(self) { + fn Remove(&self) { let node = NodeCast::from_ref(self); node.remove_self(); } } - diff --git a/components/script/dom/domexception.rs b/components/script/dom/domexception.rs index 7ac87ce61c4..fdc4257a40d 100644 --- a/components/script/dom/domexception.rs +++ b/components/script/dom/domexception.rs @@ -41,7 +41,6 @@ pub enum DOMErrorName { } #[dom_struct] -#[derive(HeapSizeOf)] pub struct DOMException { reflector_: Reflector, code: DOMErrorName, @@ -60,9 +59,9 @@ impl DOMException { } } -impl<'a> DOMExceptionMethods for &'a DOMException { +impl DOMExceptionMethods for DOMException { // https://heycam.github.io/webidl/#dfn-DOMException - fn Code(self) -> u16 { + fn Code(&self) -> u16 { match self.code { // https://heycam.github.io/webidl/#dfn-throw DOMErrorName::EncodingError => 0, @@ -71,12 +70,12 @@ impl<'a> DOMExceptionMethods for &'a DOMException { } // https://heycam.github.io/webidl/#idl-DOMException-error-names - fn Name(self) -> DOMString { + fn Name(&self) -> DOMString { format!("{:?}", self.code) } // https://heycam.github.io/webidl/#error-names - fn Message(self) -> DOMString { + 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.", diff --git a/components/script/dom/domimplementation.rs b/components/script/dom/domimplementation.rs index 50999d71c0c..91b97487b4f 100644 --- a/components/script/dom/domimplementation.rs +++ b/components/script/dom/domimplementation.rs @@ -14,7 +14,7 @@ use dom::bindings::js::{JS, Root}; use dom::bindings::utils::validate_qualified_name; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::document::DocumentSource; -use dom::document::{Document, DocumentHelpers, IsHTMLDocument}; +use dom::document::{Document, IsHTMLDocument}; use dom::documenttype::DocumentType; use dom::htmlbodyelement::HTMLBodyElement; use dom::htmlheadelement::HTMLHeadElement; @@ -27,7 +27,6 @@ use std::borrow::ToOwned; // https://dom.spec.whatwg.org/#domimplementation #[dom_struct] -#[derive(HeapSizeOf)] pub struct DOMImplementation { reflector_: Reflector, document: JS, @@ -50,9 +49,9 @@ impl DOMImplementation { } // https://dom.spec.whatwg.org/#domimplementation -impl<'a> DOMImplementationMethods for &'a DOMImplementation { +impl DOMImplementationMethods for DOMImplementation { // https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype - fn CreateDocumentType(self, qualified_name: DOMString, pubid: DOMString, sysid: DOMString) + fn CreateDocumentType(&self, qualified_name: DOMString, pubid: DOMString, sysid: DOMString) -> Fallible> { try!(validate_qualified_name(&qualified_name)); let document = self.document.root(); @@ -60,7 +59,7 @@ impl<'a> DOMImplementationMethods for &'a DOMImplementation { } // https://dom.spec.whatwg.org/#dom-domimplementation-createdocument - fn CreateDocument(self, namespace: Option, qname: DOMString, + fn CreateDocument(&self, namespace: Option, qname: DOMString, maybe_doctype: Option<&DocumentType>) -> Fallible> { let doc = self.document.root(); let doc = doc.r(); @@ -109,7 +108,7 @@ impl<'a> DOMImplementationMethods for &'a DOMImplementation { } // https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument - fn CreateHTMLDocument(self, title: Option) -> Root { + fn CreateHTMLDocument(&self, title: Option) -> Root { let document = self.document.root(); let document = document.r(); let win = document.window(); @@ -168,7 +167,7 @@ impl<'a> DOMImplementationMethods for &'a DOMImplementation { } // https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature - fn HasFeature(self) -> bool { + fn HasFeature(&self) -> bool { true } } diff --git a/components/script/dom/domparser.rs b/components/script/dom/domparser.rs index 48834425821..00172fc398d 100644 --- a/components/script/dom/domparser.rs +++ b/components/script/dom/domparser.rs @@ -13,15 +13,14 @@ use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::document::DocumentSource; -use dom::document::{Document, DocumentHelpers, IsHTMLDocument}; -use dom::window::{Window, WindowHelpers}; +use dom::document::{Document, IsHTMLDocument}; +use dom::window::Window; use parse::html::{ParseContext, parse_html}; use util::str::DOMString; use std::borrow::ToOwned; #[dom_struct] -#[derive(HeapSizeOf)] pub struct DOMParser { reflector_: Reflector, window: JS, //XXXjdm Document instead? @@ -45,9 +44,9 @@ impl DOMParser { } } -impl<'a> DOMParserMethods for &'a DOMParser { +impl DOMParserMethods for DOMParser { // https://domparsing.spec.whatwg.org/#the-domparser-interface - fn ParseFromString(self, + fn ParseFromString(&self, s: DOMString, ty: DOMParserBinding::SupportedType) -> Fallible> { @@ -81,4 +80,3 @@ impl<'a> DOMParserMethods for &'a DOMParser { } } } - diff --git a/components/script/dom/dompoint.rs b/components/script/dom/dompoint.rs index 0da4d13d415..1f8e85f50ad 100644 --- a/components/script/dom/dompoint.rs +++ b/components/script/dom/dompoint.rs @@ -12,7 +12,6 @@ use dom::dompointreadonly::{DOMPointReadOnly, DOMPointWriteMethods}; // http://dev.w3.org/fxtf/geometry/Overview.html#dompoint #[dom_struct] -#[derive(HeapSizeOf)] pub struct DOMPoint { point: DOMPointReadOnly } @@ -34,45 +33,44 @@ impl DOMPoint { } } -impl<'a> DOMPointMethods for &'a DOMPoint { +impl DOMPointMethods for DOMPoint { // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x - fn X(self) -> f64 { + fn X(&self) -> f64 { self.point.X() } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x - fn SetX(self, value: f64) { + fn SetX(&self, value: f64) { self.point.SetX(value); } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-y - fn Y(self) -> f64 { + fn Y(&self) -> f64 { self.point.Y() } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-y - fn SetY(self, value: f64) { + fn SetY(&self, value: f64) { self.point.SetY(value); } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z - fn Z(self) -> f64 { + fn Z(&self) -> f64 { self.point.Z() } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z - fn SetZ(self, value: f64) { + fn SetZ(&self, value: f64) { self.point.SetZ(value); } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w - fn W(self) -> f64 { + fn W(&self) -> f64 { self.point.W() } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w - fn SetW(self, value: f64) { + fn SetW(&self, value: f64) { self.point.SetW(value); } } - diff --git a/components/script/dom/dompointreadonly.rs b/components/script/dom/dompointreadonly.rs index 57bc2ae24b7..fd4965402cf 100644 --- a/components/script/dom/dompointreadonly.rs +++ b/components/script/dom/dompointreadonly.rs @@ -11,7 +11,6 @@ use std::cell::Cell; // http://dev.w3.org/fxtf/geometry/Overview.html#dompointreadonly #[dom_struct] -#[derive(HeapSizeOf)] pub struct DOMPointReadOnly { reflector_: Reflector, x: Cell, @@ -41,49 +40,49 @@ impl DOMPointReadOnly { } } -impl<'a> DOMPointReadOnlyMethods for &'a DOMPointReadOnly { +impl DOMPointReadOnlyMethods for DOMPointReadOnly { // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x - fn X(self) -> f64 { + fn X(&self) -> f64 { self.x.get() } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-y - fn Y(self) -> f64 { + fn Y(&self) -> f64 { self.y.get() } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z - fn Z(self) -> f64 { + fn Z(&self) -> f64 { self.z.get() } // https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w - fn W(self) -> f64 { + fn W(&self) -> f64 { self.w.get() } } pub trait DOMPointWriteMethods { - fn SetX(self, value: f64); - fn SetY(self, value: f64); - fn SetZ(self, value: f64); - fn SetW(self, value: f64); + fn SetX(&self, value: f64); + fn SetY(&self, value: f64); + fn SetZ(&self, value: f64); + fn SetW(&self, value: f64); } -impl<'a> DOMPointWriteMethods for &'a DOMPointReadOnly { - fn SetX(self, value: f64) { +impl DOMPointWriteMethods for DOMPointReadOnly { + fn SetX(&self, value: f64) { self.x.set(value); } - fn SetY(self, value: f64) { + fn SetY(&self, value: f64) { self.y.set(value); } - fn SetZ(self, value: f64) { + fn SetZ(&self, value: f64) { self.z.set(value); } - fn SetW(self, value: f64) { + fn SetW(&self, value: f64) { self.w.set(value); } } diff --git a/components/script/dom/domrect.rs b/components/script/dom/domrect.rs index a3608d3d865..b2b701e8fc1 100644 --- a/components/script/dom/domrect.rs +++ b/components/script/dom/domrect.rs @@ -12,7 +12,6 @@ use dom::window::Window; use util::geometry::Au; #[dom_struct] -#[derive(HeapSizeOf)] pub struct DOMRect { reflector_: Reflector, top: f32, @@ -41,37 +40,36 @@ impl DOMRect { } } -impl<'a> DOMRectMethods for &'a DOMRect { +impl DOMRectMethods for DOMRect { // https://drafts.fxtf.org/geometry/#dom-domrectreadonly-top - fn Top(self) -> Finite { + fn Top(&self) -> Finite { Finite::wrap(self.top) } // https://drafts.fxtf.org/geometry/#dom-domrectreadonly-bottom - fn Bottom(self) -> Finite { + fn Bottom(&self) -> Finite { Finite::wrap(self.bottom) } // https://drafts.fxtf.org/geometry/#dom-domrectreadonly-left - fn Left(self) -> Finite { + fn Left(&self) -> Finite { Finite::wrap(self.left) } // https://drafts.fxtf.org/geometry/#dom-domrectreadonly-right - fn Right(self) -> Finite { + fn Right(&self) -> Finite { Finite::wrap(self.right) } // https://drafts.fxtf.org/geometry/#dom-domrectreadonly-width - fn Width(self) -> Finite { + fn Width(&self) -> Finite { let result = (self.right - self.left).abs(); Finite::wrap(result) } // https://drafts.fxtf.org/geometry/#dom-domrectreadonly-height - fn Height(self) -> Finite { + fn Height(&self) -> Finite { let result = (self.bottom - self.top).abs(); Finite::wrap(result) } } - diff --git a/components/script/dom/domrectlist.rs b/components/script/dom/domrectlist.rs index 640a07a49c7..cd67dbc28c7 100644 --- a/components/script/dom/domrectlist.rs +++ b/components/script/dom/domrectlist.rs @@ -11,7 +11,6 @@ use dom::domrect::DOMRect; use dom::window::Window; #[dom_struct] -#[derive(HeapSizeOf)] pub struct DOMRectList { reflector_: Reflector, rects: Vec>, @@ -33,14 +32,14 @@ impl DOMRectList { } } -impl<'a> DOMRectListMethods for &'a DOMRectList { +impl DOMRectListMethods for DOMRectList { // https://drafts.fxtf.org/geometry/#dom-domrectlist-length - fn Length(self) -> u32 { + fn Length(&self) -> u32 { self.rects.len() as u32 } // https://drafts.fxtf.org/geometry/#dom-domrectlist-item - fn Item(self, index: u32) -> Option> { + fn Item(&self, index: u32) -> Option> { let rects = &self.rects; if index < rects.len() as u32 { Some(rects[index as usize].root()) @@ -50,9 +49,8 @@ impl<'a> DOMRectListMethods for &'a DOMRectList { } // check-tidy: no specs after this line - fn IndexedGetter(self, index: u32, found: &mut bool) -> Option> { + fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option> { *found = index < self.rects.len() as u32; self.Item(index) } } - diff --git a/components/script/dom/domstringmap.rs b/components/script/dom/domstringmap.rs index 7d3683f74db..112fb42ca32 100644 --- a/components/script/dom/domstringmap.rs +++ b/components/script/dom/domstringmap.rs @@ -8,12 +8,11 @@ use dom::bindings::error::ErrorResult; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::utils::{Reflector, reflect_dom_object}; -use dom::htmlelement::{HTMLElement, HTMLElementCustomAttributeHelpers}; +use dom::htmlelement::HTMLElement; use dom::node::window_from_node; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct DOMStringMap { reflector_: Reflector, element: JS, @@ -35,26 +34,26 @@ impl DOMStringMap { } // https://html.spec.whatwg.org/#domstringmap -impl<'a> DOMStringMapMethods for &'a DOMStringMap { +impl DOMStringMapMethods for DOMStringMap { // https://html.spec.whatwg.org/multipage/#dom-domstringmap-additem - fn NamedCreator(self, name: DOMString, value: DOMString) -> ErrorResult { + fn NamedCreator(&self, name: DOMString, value: DOMString) -> ErrorResult { self.NamedSetter(name, value) } // https://html.spec.whatwg.org/multipage/#dom-domstringmap-removeitem - fn NamedDeleter(self, name: DOMString) { + fn NamedDeleter(&self, name: DOMString) { let element = self.element.root(); element.r().delete_custom_attr(name) } // https://html.spec.whatwg.org/multipage/#dom-domstringmap-setitem - fn NamedSetter(self, name: DOMString, value: DOMString) -> ErrorResult { + fn NamedSetter(&self, name: DOMString, value: DOMString) -> ErrorResult { let element = self.element.root(); element.r().set_custom_attr(name, value) } // https://html.spec.whatwg.org/multipage/#dom-domstringmap-nameditem - fn NamedGetter(self, name: DOMString, found: &mut bool) -> DOMString { + fn NamedGetter(&self, name: DOMString, found: &mut bool) -> DOMString { let element = self.element.root(); match element.r().get_custom_attr(name) { Some(value) => { @@ -69,7 +68,7 @@ impl<'a> DOMStringMapMethods for &'a DOMStringMap { } // https://html.spec.whatwg.org/multipage/#domstringmap - fn SupportedPropertyNames(self) -> Vec { + fn SupportedPropertyNames(&self) -> Vec { // FIXME: unimplemented (https://github.com/servo/servo/issues/7273) vec![] } diff --git a/components/script/dom/domtokenlist.rs b/components/script/dom/domtokenlist.rs index 8571ec6b482..c8940a33f7b 100644 --- a/components/script/dom/domtokenlist.rs +++ b/components/script/dom/domtokenlist.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use dom::attr::{Attr, AttrHelpers}; +use dom::attr::Attr; use dom::bindings::codegen::Bindings::DOMTokenListBinding; use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods; use dom::bindings::error::Error::{InvalidCharacter, Syntax}; @@ -10,7 +10,7 @@ use dom::bindings::error::{ErrorResult, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::utils::{Reflector, reflect_dom_object}; -use dom::element::{Element, AttributeHandlers}; +use dom::element::Element; use dom::node::window_from_node; use string_cache::Atom; @@ -19,7 +19,6 @@ use util::str::{DOMString, HTML_SPACE_CHARACTERS, str_join}; use std::borrow::ToOwned; #[dom_struct] -#[derive(HeapSizeOf)] pub struct DOMTokenList { reflector_: Reflector, element: JS, @@ -41,20 +40,13 @@ impl DOMTokenList { GlobalRef::Window(window.r()), DOMTokenListBinding::Wrap) } -} -trait PrivateDOMTokenListHelpers { - fn attribute(self) -> Option>; - fn check_token_exceptions(self, token: &str) -> Fallible; -} - -impl<'a> PrivateDOMTokenListHelpers for &'a DOMTokenList { - fn attribute(self) -> Option> { + fn attribute(&self) -> Option> { let element = self.element.root(); element.r().get_attribute(&ns!(""), &self.local_name) } - fn check_token_exceptions(self, token: &str) -> Fallible { + fn check_token_exceptions(&self, token: &str) -> Fallible { match token { "" => Err(Syntax), slice if slice.find(HTML_SPACE_CHARACTERS).is_some() => Err(InvalidCharacter), @@ -64,9 +56,9 @@ impl<'a> PrivateDOMTokenListHelpers for &'a DOMTokenList { } // https://dom.spec.whatwg.org/#domtokenlist -impl<'a> DOMTokenListMethods for &'a DOMTokenList { +impl DOMTokenListMethods for DOMTokenList { // https://dom.spec.whatwg.org/#dom-domtokenlist-length - fn Length(self) -> u32 { + fn Length(&self) -> u32 { self.attribute().map(|attr| { let attr = attr.r(); attr.value().tokens().map(|tokens| tokens.len()).unwrap_or(0) @@ -74,7 +66,7 @@ impl<'a> DOMTokenListMethods for &'a DOMTokenList { } // https://dom.spec.whatwg.org/#dom-domtokenlist-item - fn Item(self, index: u32) -> Option { + fn Item(&self, index: u32) -> Option { self.attribute().and_then(|attr| { let attr = attr.r(); attr.value().tokens().and_then(|tokens| { @@ -84,7 +76,7 @@ impl<'a> DOMTokenListMethods for &'a DOMTokenList { } // https://dom.spec.whatwg.org/#dom-domtokenlist-contains - fn Contains(self, token: DOMString) -> Fallible { + fn Contains(&self, token: DOMString) -> Fallible { self.check_token_exceptions(&token).map(|token| { self.attribute().map(|attr| { let attr = attr.r(); @@ -98,7 +90,7 @@ impl<'a> DOMTokenListMethods for &'a DOMTokenList { } // https://dom.spec.whatwg.org/#dom-domtokenlist-add - fn Add(self, tokens: Vec) -> ErrorResult { + fn Add(&self, tokens: Vec) -> ErrorResult { let element = self.element.root(); let mut atoms = element.r().get_tokenlist_attribute(&self.local_name); for token in &tokens { @@ -112,7 +104,7 @@ impl<'a> DOMTokenListMethods for &'a DOMTokenList { } // https://dom.spec.whatwg.org/#dom-domtokenlist-remove - fn Remove(self, tokens: Vec) -> ErrorResult { + fn Remove(&self, tokens: Vec) -> ErrorResult { let element = self.element.root(); let mut atoms = element.r().get_tokenlist_attribute(&self.local_name); for token in &tokens { @@ -126,7 +118,7 @@ impl<'a> DOMTokenListMethods for &'a DOMTokenList { } // https://dom.spec.whatwg.org/#dom-domtokenlist-toggle - fn Toggle(self, token: DOMString, force: Option) -> Fallible { + fn Toggle(&self, token: DOMString, force: Option) -> Fallible { let element = self.element.root(); let mut atoms = element.r().get_tokenlist_attribute(&self.local_name); let token = try!(self.check_token_exceptions(&token)); @@ -151,13 +143,13 @@ impl<'a> DOMTokenListMethods for &'a DOMTokenList { } // https://dom.spec.whatwg.org/#stringification-behavior - fn Stringifier(self) -> DOMString { + fn Stringifier(&self) -> DOMString { let tokenlist = self.element.root().r().get_tokenlist_attribute(&self.local_name); str_join(&tokenlist, "\x20") } // check-tidy: no specs after this line - fn IndexedGetter(self, index: u32, found: &mut bool) -> Option { + fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option { let item = self.Item(index); *found = item.is_some(); item diff --git a/components/script/dom/element.rs b/components/script/dom/element.rs index 859a38ba282..f16ca2bbb28 100644 --- a/components/script/dom/element.rs +++ b/components/script/dom/element.rs @@ -6,7 +6,7 @@ use dom::activation::Activatable; use dom::attr::AttrValue; -use dom::attr::{Attr, AttrSettingType, AttrHelpers, AttrHelpersForLayout}; +use dom::attr::{Attr, AttrSettingType, AttrHelpersForLayout}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; use dom::bindings::codegen::Bindings::ElementBinding; @@ -35,27 +35,26 @@ use dom::bindings::js::{Root, RootedReference}; use dom::bindings::trace::RootedVec; use dom::bindings::utils::XMLName::InvalidXMLName; use dom::bindings::utils::{namespace_from_domstring, xml_name_type, validate_and_extract}; -use dom::characterdata::CharacterDataHelpers; use dom::create::create_element; -use dom::document::{Document, DocumentHelpers, LayoutDocumentHelpers}; +use dom::document::{Document, LayoutDocumentHelpers}; use dom::domrect::DOMRect; use dom::domrectlist::DOMRectList; use dom::domtokenlist::DOMTokenList; -use dom::event::{Event, EventHelpers}; +use dom::event::Event; use dom::eventtarget::{EventTarget, EventTargetTypeId}; -use dom::htmlbodyelement::{HTMLBodyElement, HTMLBodyElementHelpers}; +use dom::htmlbodyelement::HTMLBodyElement; use dom::htmlcollection::HTMLCollection; use dom::htmlelement::HTMLElementTypeId; -use dom::htmlfontelement::{HTMLFontElement, HTMLFontElementHelpers}; -use dom::htmliframeelement::{HTMLIFrameElement, RawHTMLIFrameElementHelpers}; -use dom::htmlinputelement::{HTMLInputElement, RawLayoutHTMLInputElementHelpers, HTMLInputElementHelpers}; -use dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementHelpers}; -use dom::htmltableelement::{HTMLTableElement, HTMLTableElementHelpers}; -use dom::htmltablerowelement::{HTMLTableRowElement, HTMLTableRowElementHelpers}; -use dom::htmltablesectionelement::{HTMLTableSectionElement, HTMLTableSectionElementHelpers}; +use dom::htmlfontelement::HTMLFontElement; +use dom::htmliframeelement::HTMLIFrameElement; +use dom::htmlinputelement::{HTMLInputElement, RawLayoutHTMLInputElementHelpers}; +use dom::htmltablecellelement::HTMLTableCellElement; +use dom::htmltableelement::HTMLTableElement; +use dom::htmltablerowelement::HTMLTableRowElement; +use dom::htmltablesectionelement::HTMLTableSectionElement; use dom::htmltextareaelement::{HTMLTextAreaElement, RawLayoutHTMLTextAreaElementHelpers}; use dom::namednodemap::NamedNodeMap; -use dom::node::{CLICK_IN_PROGRESS, LayoutNodeHelpers, Node, NodeHelpers, NodeTypeId, SEQUENTIALLY_FOCUSABLE}; +use dom::node::{CLICK_IN_PROGRESS, LayoutNodeHelpers, Node, NodeTypeId, SEQUENTIALLY_FOCUSABLE}; use dom::node::{document_from_node, NodeDamage}; use dom::node::{window_from_node}; use dom::nodelist::NodeList; @@ -92,7 +91,6 @@ use std::mem; use std::sync::Arc; #[dom_struct] -#[derive(HeapSizeOf)] pub struct Element { node: Node, local_name: Atom, @@ -571,38 +569,18 @@ pub enum StylePriority { Normal, } -pub trait ElementHelpers<'a> { - fn html_element_in_html_document(self) -> bool; - fn local_name(self) -> &'a Atom; - fn parsed_name(self, name: DOMString) -> Atom; - fn namespace(self) -> &'a Namespace; - fn prefix(self) -> &'a Option; - fn attrs(&self) -> Ref>>; - fn attrs_mut(&self) -> RefMut>>; - fn style_attribute(self) -> &'a DOMRefCell>; - fn summarize(self) -> Vec; - fn is_void(self) -> bool; - fn remove_inline_style_property(self, property: &str); - fn update_inline_style(self, property_decl: PropertyDeclaration, style_priority: StylePriority); - fn set_inline_style_property_priority(self, properties: &[&str], style_priority: StylePriority); - fn get_inline_style_declaration(self, property: &Atom) -> Option>; - fn get_important_inline_style_declaration(self, property: &Atom) -> Option>; - fn serialize(self, traversal_scope: TraversalScope) -> Fallible; - fn get_root_element(self) -> Root; - fn lookup_prefix(self, namespace: Namespace) -> Option; -} -impl<'a> ElementHelpers<'a> for &'a Element { - fn html_element_in_html_document(self) -> bool { +impl Element { + pub fn html_element_in_html_document(&self) -> bool { let node = NodeCast::from_ref(self); self.namespace == ns!(HTML) && node.is_in_html_doc() } - fn local_name(self) -> &'a Atom { + pub fn local_name(&self) -> &Atom { &self.local_name } - fn parsed_name(self, name: DOMString) -> Atom { + pub fn parsed_name(&self, name: DOMString) -> Atom { if self.html_element_in_html_document() { Atom::from_slice(&name.to_ascii_lowercase()) } else { @@ -610,27 +588,27 @@ impl<'a> ElementHelpers<'a> for &'a Element { } } - fn namespace(self) -> &'a Namespace { + pub fn namespace(&self) -> &Namespace { &self.namespace } - fn prefix(self) -> &'a Option { + pub fn prefix(&self) -> &Option { &self.prefix } - fn attrs(&self) -> Ref>> { + pub fn attrs(&self) -> Ref>> { self.attrs.borrow() } - fn attrs_mut(&self) -> RefMut>> { + pub fn attrs_mut(&self) -> RefMut>> { self.attrs.borrow_mut() } - fn style_attribute(self) -> &'a DOMRefCell> { + pub fn style_attribute(&self) -> &DOMRefCell> { &self.style_attribute } - fn summarize(self) -> Vec { + pub fn summarize(&self) -> Vec { let attrs = self.Attributes(); let mut summarized = vec!(); for i in 0..attrs.r().Length() { @@ -640,7 +618,7 @@ impl<'a> ElementHelpers<'a> for &'a Element { summarized } - fn is_void(self) -> bool { + pub fn is_void(&self) -> bool { if self.namespace != ns!(HTML) { return false } @@ -654,7 +632,7 @@ impl<'a> ElementHelpers<'a> for &'a Element { } } - fn remove_inline_style_property(self, property: &str) { + pub fn remove_inline_style_property(&self, property: &str) { let mut inline_declarations = self.style_attribute.borrow_mut(); if let &mut Some(ref mut declarations) = &mut *inline_declarations { let index = declarations.normal @@ -675,7 +653,7 @@ impl<'a> ElementHelpers<'a> for &'a Element { } } - fn update_inline_style(self, property_decl: PropertyDeclaration, style_priority: StylePriority) { + pub fn update_inline_style(&self, property_decl: PropertyDeclaration, style_priority: StylePriority) { let mut inline_declarations = self.style_attribute().borrow_mut(); if let &mut Some(ref mut declarations) = &mut *inline_declarations { let existing_declarations = if style_priority == StylePriority::Important { @@ -709,7 +687,7 @@ impl<'a> ElementHelpers<'a> for &'a Element { }); } - fn set_inline_style_property_priority(self, properties: &[&str], style_priority: StylePriority) { + pub fn set_inline_style_property_priority(&self, properties: &[&str], style_priority: StylePriority) { let mut inline_declarations = self.style_attribute().borrow_mut(); if let &mut Some(ref mut declarations) = &mut *inline_declarations { let (from, to) = if style_priority == StylePriority::Important { @@ -734,7 +712,7 @@ impl<'a> ElementHelpers<'a> for &'a Element { } } - fn get_inline_style_declaration(self, property: &Atom) -> Option> { + pub fn get_inline_style_declaration(&self, property: &Atom) -> Option> { Ref::filter_map(self.style_attribute.borrow(), |inline_declarations| { inline_declarations.as_ref().and_then(|declarations| { declarations.normal @@ -745,7 +723,8 @@ impl<'a> ElementHelpers<'a> for &'a Element { }) } - fn get_important_inline_style_declaration(self, property: &Atom) -> Option> { + pub fn get_important_inline_style_declaration(&self, property: &Atom) + -> Option> { Ref::filter_map(self.style_attribute.borrow(), |inline_declarations| { inline_declarations.as_ref().and_then(|declarations| { declarations.important @@ -755,7 +734,7 @@ impl<'a> ElementHelpers<'a> for &'a Element { }) } - fn serialize(self, traversal_scope: TraversalScope) -> Fallible { + pub fn serialize(&self, traversal_scope: TraversalScope) -> Fallible { let node = NodeCast::from_ref(self); let mut writer = vec![]; match serialize(&mut writer, &node, @@ -769,7 +748,7 @@ impl<'a> ElementHelpers<'a> for &'a Element { } // https://html.spec.whatwg.org/multipage/#root-element - fn get_root_element(self) -> Root { + pub fn get_root_element(&self) -> Root { let node = NodeCast::from_ref(self); node.inclusive_ancestors() .filter_map(ElementCast::to_root) @@ -778,7 +757,7 @@ impl<'a> ElementHelpers<'a> for &'a Element { } // https://dom.spec.whatwg.org/#locate-a-namespace-prefix - fn lookup_prefix(self, namespace: Namespace) -> Option { + pub fn lookup_prefix(&self, namespace: Namespace) -> Option { for node in NodeCast::from_ref(self).inclusive_ancestors() { match ElementCast::to_ref(node.r()) { Some(element) => { @@ -806,16 +785,9 @@ impl<'a> ElementHelpers<'a> for &'a Element { } } -pub trait FocusElementHelpers { - /// https://html.spec.whatwg.org/multipage/#focusable-area - fn is_focusable_area(self) -> bool; - /// https://html.spec.whatwg.org/multipage/#concept-element-disabled - fn is_actually_disabled(self) -> bool; -} - -impl<'a> FocusElementHelpers for &'a Element { - fn is_focusable_area(self) -> bool { +impl Element { + pub fn is_focusable_area(&self) -> bool { if self.is_actually_disabled() { return false; } @@ -836,7 +808,7 @@ impl<'a> FocusElementHelpers for &'a Element { } } - fn is_actually_disabled(self) -> bool { + pub fn is_actually_disabled(&self) -> bool { let node = NodeCast::from_ref(self); match node.type_id() { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) | @@ -855,58 +827,9 @@ impl<'a> FocusElementHelpers for &'a Element { } } -pub trait AttributeHandlers { - /// Returns the attribute with given namespace and case-sensitive local - /// name, if any. - fn get_attribute(self, namespace: &Namespace, local_name: &Atom) - -> Option>; - /// Returns the first attribute with any namespace and given case-sensitive - /// name, if any. - fn get_attribute_by_name(self, name: DOMString) -> Option>; - fn get_attributes(self, local_name: &Atom, attributes: &mut RootedVec>); - fn set_attribute_from_parser(self, - name: QualName, - value: DOMString, - prefix: Option); - fn set_attribute(self, name: &Atom, value: AttrValue); - fn set_custom_attribute(self, name: DOMString, value: DOMString) -> ErrorResult; - fn do_set_attribute(self, local_name: Atom, value: AttrValue, - name: Atom, namespace: Namespace, - prefix: Option, cb: F) - where F: Fn(&Attr) -> bool; - fn parse_attribute(self, namespace: &Namespace, local_name: &Atom, - value: DOMString) -> AttrValue; - /// Removes the first attribute with any given namespace and case-sensitive local - /// name, if any. - fn remove_attribute(self, namespace: &Namespace, local_name: &Atom) - -> Option>; - /// Removes the first attribute with any namespace and given case-sensitive name. - fn remove_attribute_by_name(self, name: &Atom) -> Option>; - /// Removes the first attribute that satisfies `find`. - fn do_remove_attribute(self, find: F) -> Option> - where F: Fn(&Attr) -> bool; - - fn has_class(self, name: &Atom) -> bool; - - fn set_atomic_attribute(self, local_name: &Atom, value: DOMString); - - // https://www.whatwg.org/html/#reflecting-content-attributes-in-idl-attributes - fn has_attribute(self, local_name: &Atom) -> bool; - fn set_bool_attribute(self, local_name: &Atom, value: bool); - fn get_url_attribute(self, local_name: &Atom) -> DOMString; - fn set_url_attribute(self, local_name: &Atom, value: DOMString); - fn get_string_attribute(self, local_name: &Atom) -> DOMString; - fn set_string_attribute(self, local_name: &Atom, value: DOMString); - fn get_tokenlist_attribute(self, local_name: &Atom) -> Vec; - fn set_tokenlist_attribute(self, local_name: &Atom, value: DOMString); - fn set_atomic_tokenlist_attribute(self, local_name: &Atom, tokens: Vec); - fn get_uint_attribute(self, local_name: &Atom, default: u32) -> u32; - fn set_uint_attribute(self, local_name: &Atom, value: u32); -} - -impl<'a> AttributeHandlers for &'a Element { - fn get_attribute(self, namespace: &Namespace, local_name: &Atom) -> Option> { +impl Element { + pub fn get_attribute(&self, namespace: &Namespace, local_name: &Atom) -> Option> { let mut attributes = RootedVec::new(); self.get_attributes(local_name, &mut attributes); attributes.r().iter() @@ -915,14 +838,14 @@ impl<'a> AttributeHandlers for &'a Element { } // https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name - fn get_attribute_by_name(self, name: DOMString) -> Option> { + pub fn get_attribute_by_name(&self, name: DOMString) -> Option> { let name = &self.parsed_name(name); self.attrs.borrow().iter().map(|attr| attr.root()) .find(|a| a.r().name() == name) } // https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name - fn get_attributes(self, local_name: &Atom, attributes: &mut RootedVec>) { + pub fn get_attributes(&self, local_name: &Atom, attributes: &mut RootedVec>) { for ref attr in self.attrs.borrow().iter() { let attr = attr.root(); if attr.r().local_name() == local_name { @@ -931,7 +854,7 @@ impl<'a> AttributeHandlers for &'a Element { } } - fn set_attribute_from_parser(self, + pub fn set_attribute_from_parser(&self, qname: QualName, value: DOMString, prefix: Option) { @@ -952,7 +875,7 @@ impl<'a> AttributeHandlers for &'a Element { self.do_set_attribute(qname.local, value, name, qname.ns, prefix, |_| false) } - fn set_attribute(self, name: &Atom, value: AttrValue) { + pub fn set_attribute(&self, name: &Atom, value: AttrValue) { assert!(&**name == name.to_ascii_lowercase()); assert!(!name.contains(":")); @@ -961,7 +884,7 @@ impl<'a> AttributeHandlers for &'a Element { } // https://html.spec.whatwg.org/multipage/#attr-data-* - fn set_custom_attribute(self, name: DOMString, value: DOMString) -> ErrorResult { + pub fn set_custom_attribute(&self, name: DOMString, value: DOMString) -> ErrorResult { // Step 1. match xml_name_type(&name) { InvalidXMLName => return Err(InvalidCharacter), @@ -977,7 +900,7 @@ impl<'a> AttributeHandlers for &'a Element { Ok(()) } - fn do_set_attribute(self, + pub fn do_set_attribute(&self, local_name: Atom, value: AttrValue, name: Atom, @@ -1003,7 +926,7 @@ impl<'a> AttributeHandlers for &'a Element { (*self.attrs.borrow())[idx].root().r().set_value(set_type, value, self); } - fn parse_attribute(self, namespace: &Namespace, local_name: &Atom, + pub fn parse_attribute(&self, namespace: &Namespace, local_name: &Atom, value: DOMString) -> AttrValue { if *namespace == ns!("") { vtable_for(&NodeCast::from_ref(self)) @@ -1013,18 +936,18 @@ impl<'a> AttributeHandlers for &'a Element { } } - fn remove_attribute(self, namespace: &Namespace, local_name: &Atom) + pub fn remove_attribute(&self, namespace: &Namespace, local_name: &Atom) -> Option> { self.do_remove_attribute(|attr| { attr.namespace() == namespace && attr.local_name() == local_name }) } - fn remove_attribute_by_name(self, name: &Atom) -> Option> { + pub fn remove_attribute_by_name(&self, name: &Atom) -> Option> { self.do_remove_attribute(|attr| attr.name() == name) } - fn do_remove_attribute(self, find: F) -> Option> + pub fn do_remove_attribute(&self, find: F) -> Option> where F: Fn(&Attr) -> bool { let idx = self.attrs.borrow().iter() @@ -1057,7 +980,7 @@ impl<'a> AttributeHandlers for &'a Element { }) } - fn has_class(self, name: &Atom) -> bool { + pub fn has_class(&self, name: &Atom) -> bool { let quirks_mode = { let node = NodeCast::from_ref(self); let owner_doc = node.owner_doc(); @@ -1074,20 +997,20 @@ impl<'a> AttributeHandlers for &'a Element { }).unwrap_or(false) } - fn set_atomic_attribute(self, local_name: &Atom, value: DOMString) { + pub fn set_atomic_attribute(&self, local_name: &Atom, value: DOMString) { assert!(&**local_name == local_name.to_ascii_lowercase()); let value = AttrValue::from_atomic(value); self.set_attribute(local_name, value); } - fn has_attribute(self, local_name: &Atom) -> bool { + pub fn has_attribute(&self, local_name: &Atom) -> bool { assert!(local_name.bytes().all(|b| b.to_ascii_lowercase() == b)); self.attrs.borrow().iter().map(|attr| attr.root()).any(|attr| { attr.r().local_name() == local_name && attr.r().namespace() == &ns!("") }) } - fn set_bool_attribute(self, local_name: &Atom, value: bool) { + pub fn set_bool_attribute(&self, local_name: &Atom, value: bool) { if self.has_attribute(local_name) == value { return; } if value { self.set_string_attribute(local_name, String::new()); @@ -1096,7 +1019,7 @@ impl<'a> AttributeHandlers for &'a Element { } } - fn get_url_attribute(self, local_name: &Atom) -> DOMString { + pub fn get_url_attribute(&self, local_name: &Atom) -> DOMString { assert!(&**local_name == local_name.to_ascii_lowercase()); if !self.has_attribute(local_name) { return "".to_owned(); @@ -1111,22 +1034,22 @@ impl<'a> AttributeHandlers for &'a Element { Err(_) => "".to_owned() } } - fn set_url_attribute(self, local_name: &Atom, value: DOMString) { + pub fn set_url_attribute(&self, local_name: &Atom, value: DOMString) { self.set_string_attribute(local_name, value); } - fn get_string_attribute(self, local_name: &Atom) -> DOMString { + pub fn get_string_attribute(&self, local_name: &Atom) -> DOMString { match self.get_attribute(&ns!(""), local_name) { Some(x) => x.r().Value(), None => "".to_owned() } } - fn set_string_attribute(self, local_name: &Atom, value: DOMString) { + pub fn set_string_attribute(&self, local_name: &Atom, value: DOMString) { assert!(&**local_name == local_name.to_ascii_lowercase()); self.set_attribute(local_name, AttrValue::String(value)); } - fn get_tokenlist_attribute(self, local_name: &Atom) -> Vec { + pub fn get_tokenlist_attribute(&self, local_name: &Atom) -> Vec { self.get_attribute(&ns!(""), local_name).map(|attr| { attr.r() .value() @@ -1136,17 +1059,17 @@ impl<'a> AttributeHandlers for &'a Element { }).unwrap_or(vec!()) } - fn set_tokenlist_attribute(self, local_name: &Atom, value: DOMString) { + pub fn set_tokenlist_attribute(&self, local_name: &Atom, value: DOMString) { assert!(&**local_name == local_name.to_ascii_lowercase()); self.set_attribute(local_name, AttrValue::from_serialized_tokenlist(value)); } - fn set_atomic_tokenlist_attribute(self, local_name: &Atom, tokens: Vec) { + pub fn set_atomic_tokenlist_attribute(&self, local_name: &Atom, tokens: Vec) { assert!(&**local_name == local_name.to_ascii_lowercase()); self.set_attribute(local_name, AttrValue::from_atomic_tokens(tokens)); } - fn get_uint_attribute(self, local_name: &Atom, default: u32) -> u32 { + pub fn get_uint_attribute(&self, local_name: &Atom, default: u32) -> u32 { assert!(local_name.chars().all(|ch| { !ch.is_ascii() || ch.to_ascii_lowercase() == ch })); @@ -1162,30 +1085,30 @@ impl<'a> AttributeHandlers for &'a Element { None => default, } } - fn set_uint_attribute(self, local_name: &Atom, value: u32) { + pub fn set_uint_attribute(&self, local_name: &Atom, value: u32) { assert!(&**local_name == local_name.to_ascii_lowercase()); self.set_attribute(local_name, AttrValue::UInt(value.to_string(), value)); } } -impl<'a> ElementMethods for &'a Element { +impl ElementMethods for Element { // https://dom.spec.whatwg.org/#dom-element-namespaceuri - fn GetNamespaceURI(self) -> Option { + fn GetNamespaceURI(&self) -> Option { Node::namespace_to_string(self.namespace.clone()) } // https://dom.spec.whatwg.org/#dom-element-localname - fn LocalName(self) -> DOMString { + fn LocalName(&self) -> DOMString { (*self.local_name).to_owned() } // https://dom.spec.whatwg.org/#dom-element-prefix - fn GetPrefix(self) -> Option { + fn GetPrefix(&self) -> Option { self.prefix.clone() } // https://dom.spec.whatwg.org/#dom-element-tagname - fn TagName(self) -> DOMString { + fn TagName(&self) -> DOMString { let qualified_name = match self.prefix { Some(ref prefix) => { Cow::Owned(format!("{}:{}", &**prefix, &*self.local_name)) @@ -1200,32 +1123,32 @@ impl<'a> ElementMethods for &'a Element { } // https://dom.spec.whatwg.org/#dom-element-id - fn Id(self) -> DOMString { + fn Id(&self) -> DOMString { self.get_string_attribute(&atom!("id")) } // https://dom.spec.whatwg.org/#dom-element-id - fn SetId(self, id: DOMString) { + fn SetId(&self, id: DOMString) { self.set_atomic_attribute(&atom!("id"), id); } // https://dom.spec.whatwg.org/#dom-element-classname - fn ClassName(self) -> DOMString { + fn ClassName(&self) -> DOMString { self.get_string_attribute(&atom!("class")) } // https://dom.spec.whatwg.org/#dom-element-classname - fn SetClassName(self, class: DOMString) { + fn SetClassName(&self, class: DOMString) { self.set_tokenlist_attribute(&atom!("class"), class); } // https://dom.spec.whatwg.org/#dom-element-classlist - fn ClassList(self) -> Root { + fn ClassList(&self) -> Root { self.class_list.or_init(|| DOMTokenList::new(self, &atom!("class"))) } // https://dom.spec.whatwg.org/#dom-element-attributes - fn Attributes(self) -> Root { + fn Attributes(&self) -> Root { self.attr_list.or_init(|| { let doc = { let node = NodeCast::from_ref(self); @@ -1237,13 +1160,13 @@ impl<'a> ElementMethods for &'a Element { } // https://dom.spec.whatwg.org/#dom-element-getattribute - fn GetAttribute(self, name: DOMString) -> Option { + fn GetAttribute(&self, name: DOMString) -> Option { self.get_attribute_by_name(name) .map(|s| s.r().Value()) } // https://dom.spec.whatwg.org/#dom-element-getattributens - fn GetAttributeNS(self, + fn GetAttributeNS(&self, namespace: Option, local_name: DOMString) -> Option { let namespace = &namespace_from_domstring(namespace); @@ -1252,7 +1175,7 @@ impl<'a> ElementMethods for &'a Element { } // https://dom.spec.whatwg.org/#dom-element-setattribute - fn SetAttribute(self, + fn SetAttribute(&self, name: DOMString, value: DOMString) -> ErrorResult { // Step 1. @@ -1272,7 +1195,7 @@ impl<'a> ElementMethods for &'a Element { } // https://dom.spec.whatwg.org/#dom-element-setattributens - fn SetAttributeNS(self, + fn SetAttributeNS(&self, namespace: Option, qualified_name: DOMString, value: DOMString) -> ErrorResult { @@ -1289,13 +1212,13 @@ impl<'a> ElementMethods for &'a Element { } // https://dom.spec.whatwg.org/#dom-element-removeattribute - fn RemoveAttribute(self, name: DOMString) { + fn RemoveAttribute(&self, name: DOMString) { let name = self.parsed_name(name); self.remove_attribute_by_name(&name); } // https://dom.spec.whatwg.org/#dom-element-removeattributens - fn RemoveAttributeNS(self, + fn RemoveAttributeNS(&self, namespace: Option, local_name: DOMString) { let namespace = namespace_from_domstring(namespace); @@ -1304,38 +1227,38 @@ impl<'a> ElementMethods for &'a Element { } // https://dom.spec.whatwg.org/#dom-element-hasattribute - fn HasAttribute(self, name: DOMString) -> bool { + fn HasAttribute(&self, name: DOMString) -> bool { self.GetAttribute(name).is_some() } // https://dom.spec.whatwg.org/#dom-element-hasattributens - fn HasAttributeNS(self, + fn HasAttributeNS(&self, namespace: Option, local_name: DOMString) -> bool { self.GetAttributeNS(namespace, local_name).is_some() } // https://dom.spec.whatwg.org/#dom-element-getelementsbytagname - fn GetElementsByTagName(self, localname: DOMString) -> Root { + fn GetElementsByTagName(&self, localname: DOMString) -> Root { let window = window_from_node(self); HTMLCollection::by_tag_name(window.r(), NodeCast::from_ref(self), localname) } // https://dom.spec.whatwg.org/#dom-element-getelementsbytagnamens - fn GetElementsByTagNameNS(self, maybe_ns: Option, + fn GetElementsByTagNameNS(&self, maybe_ns: Option, localname: DOMString) -> Root { let window = window_from_node(self); HTMLCollection::by_tag_name_ns(window.r(), NodeCast::from_ref(self), localname, maybe_ns) } // https://dom.spec.whatwg.org/#dom-element-getelementsbyclassname - fn GetElementsByClassName(self, classes: DOMString) -> Root { + fn GetElementsByClassName(&self, classes: DOMString) -> Root { let window = window_from_node(self); HTMLCollection::by_class_name(window.r(), NodeCast::from_ref(self), classes) } // https://drafts.csswg.org/cssom-view/#dom-element-getclientrects - fn GetClientRects(self) -> Root { + fn GetClientRects(&self) -> Root { let win = window_from_node(self); let node = NodeCast::from_ref(self); let raw_rects = node.get_content_boxes(); @@ -1348,7 +1271,7 @@ impl<'a> ElementMethods for &'a Element { } // https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect - fn GetBoundingClientRect(self) -> Root { + fn GetBoundingClientRect(&self) -> Root { let win = window_from_node(self); let node = NodeCast::from_ref(self); let rect = node.get_bounding_content_box(); @@ -1361,37 +1284,37 @@ impl<'a> ElementMethods for &'a Element { } // https://drafts.csswg.org/cssom-view/#dom-element-clienttop - fn ClientTop(self) -> i32 { + fn ClientTop(&self) -> i32 { let node = NodeCast::from_ref(self); node.get_client_rect().origin.y } // https://drafts.csswg.org/cssom-view/#dom-element-clientleft - fn ClientLeft(self) -> i32 { + fn ClientLeft(&self) -> i32 { let node = NodeCast::from_ref(self); node.get_client_rect().origin.x } // https://drafts.csswg.org/cssom-view/#dom-element-clientwidth - fn ClientWidth(self) -> i32 { + fn ClientWidth(&self) -> i32 { let node = NodeCast::from_ref(self); node.get_client_rect().size.width } // https://drafts.csswg.org/cssom-view/#dom-element-clientheight - fn ClientHeight(self) -> i32 { + fn ClientHeight(&self) -> i32 { let node = NodeCast::from_ref(self); node.get_client_rect().size.height } // https://dvcs.w3.org/hg/innerhtml/raw-file/tip/index.html#widl-Element-innerHTML - fn GetInnerHTML(self) -> Fallible { + fn GetInnerHTML(&self) -> Fallible { //XXX TODO: XML case self.serialize(ChildrenOnly) } // https://dvcs.w3.org/hg/innerhtml/raw-file/tip/index.html#widl-Element-innerHTML - fn SetInnerHTML(self, value: DOMString) -> Fallible<()> { + fn SetInnerHTML(&self, value: DOMString) -> Fallible<()> { let context_node = NodeCast::from_ref(self); // Step 1. let frag = try!(context_node.parse_fragment(value)); @@ -1401,12 +1324,12 @@ impl<'a> ElementMethods for &'a Element { } // https://dvcs.w3.org/hg/innerhtml/raw-file/tip/index.html#widl-Element-outerHTML - fn GetOuterHTML(self) -> Fallible { + fn GetOuterHTML(&self) -> Fallible { self.serialize(IncludeNode) } // https://dvcs.w3.org/hg/innerhtml/raw-file/tip/index.html#widl-Element-outerHTML - fn SetOuterHTML(self, value: DOMString) -> Fallible<()> { + fn SetOuterHTML(&self, value: DOMString) -> Fallible<()> { let context_document = document_from_node(self); let context_node = NodeCast::from_ref(self); // Step 1. @@ -1441,83 +1364,83 @@ impl<'a> ElementMethods for &'a Element { } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling - fn GetPreviousElementSibling(self) -> Option> { + fn GetPreviousElementSibling(&self) -> Option> { NodeCast::from_ref(self).preceding_siblings() .filter_map(ElementCast::to_root).next() } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling - fn GetNextElementSibling(self) -> Option> { + fn GetNextElementSibling(&self) -> Option> { NodeCast::from_ref(self).following_siblings() .filter_map(ElementCast::to_root).next() } // https://dom.spec.whatwg.org/#dom-parentnode-children - fn Children(self) -> Root { + fn Children(&self) -> Root { let window = window_from_node(self); HTMLCollection::children(window.r(), NodeCast::from_ref(self)) } // https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild - fn GetFirstElementChild(self) -> Option> { + fn GetFirstElementChild(&self) -> Option> { NodeCast::from_ref(self).child_elements().next() } // https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild - fn GetLastElementChild(self) -> Option> { + fn GetLastElementChild(&self) -> Option> { NodeCast::from_ref(self).rev_children().filter_map(ElementCast::to_root).next() } // https://dom.spec.whatwg.org/#dom-parentnode-childelementcount - fn ChildElementCount(self) -> u32 { + fn ChildElementCount(&self) -> u32 { NodeCast::from_ref(self).child_elements().count() as u32 } // https://dom.spec.whatwg.org/#dom-parentnode-prepend - fn Prepend(self, nodes: Vec) -> ErrorResult { + fn Prepend(&self, nodes: Vec) -> ErrorResult { NodeCast::from_ref(self).prepend(nodes) } // https://dom.spec.whatwg.org/#dom-parentnode-append - fn Append(self, nodes: Vec) -> ErrorResult { + fn Append(&self, nodes: Vec) -> ErrorResult { NodeCast::from_ref(self).append(nodes) } // https://dom.spec.whatwg.org/#dom-parentnode-queryselector - fn QuerySelector(self, selectors: DOMString) -> Fallible>> { + fn QuerySelector(&self, selectors: DOMString) -> Fallible>> { let root = NodeCast::from_ref(self); root.query_selector(selectors) } // https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall - fn QuerySelectorAll(self, selectors: DOMString) -> Fallible> { + fn QuerySelectorAll(&self, selectors: DOMString) -> Fallible> { let root = NodeCast::from_ref(self); root.query_selector_all(selectors) } // https://dom.spec.whatwg.org/#dom-childnode-before - fn Before(self, nodes: Vec) -> ErrorResult { + fn Before(&self, nodes: Vec) -> ErrorResult { NodeCast::from_ref(self).before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after - fn After(self, nodes: Vec) -> ErrorResult { + fn After(&self, nodes: Vec) -> ErrorResult { NodeCast::from_ref(self).after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith - fn ReplaceWith(self, nodes: Vec) -> ErrorResult { + fn ReplaceWith(&self, nodes: Vec) -> ErrorResult { NodeCast::from_ref(self).replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove - fn Remove(self) { + fn Remove(&self) { let node = NodeCast::from_ref(self); node.remove_self(); } // https://dom.spec.whatwg.org/#dom-element-matches - fn Matches(self, selectors: DOMString) -> Fallible { + fn Matches(&self, selectors: DOMString) -> Fallible { match parse_author_origin_selector_list_from_str(&selectors) { Err(()) => Err(Syntax), Ok(ref selectors) => { @@ -1527,7 +1450,7 @@ impl<'a> ElementMethods for &'a Element { } // https://dom.spec.whatwg.org/#dom-element-closest - fn Closest(self, selectors: DOMString) -> Fallible>> { + fn Closest(&self, selectors: DOMString) -> Fallible>> { match parse_author_origin_selector_list_from_str(&selectors) { Err(()) => Err(Syntax), Ok(ref selectors) => { @@ -1545,9 +1468,9 @@ impl<'a> ElementMethods for &'a Element { } } -impl<'a> VirtualMethods for &'a Element { +impl VirtualMethods for Element { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let node: &&Node = NodeCast::from_borrowed_ref(self); + let node: &Node = NodeCast::from_ref(self); Some(node as &VirtualMethods) } @@ -1556,11 +1479,11 @@ impl<'a> VirtualMethods for &'a Element { s.after_set_attr(attr); } - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); match attr.local_name() { &atom!("style") => { // Modifying the `style` attribute might change style. - let doc = document_from_node(*self); + let doc = document_from_node(self); let base_url = doc.r().base_url(); let value = attr.value(); let style = Some(parse_style_attribute(&value, &base_url)); @@ -1573,7 +1496,7 @@ impl<'a> VirtualMethods for &'a Element { &atom!("class") => { // Modifying a class can change style. if node.is_in_doc() { - let document = document_from_node(*self); + let document = document_from_node(self); document.r().content_changed(node, NodeDamage::NodeStyleDamaged); } } @@ -1581,10 +1504,10 @@ impl<'a> VirtualMethods for &'a Element { // Modifying an ID might change style. let value = attr.value(); if node.is_in_doc() { - let doc = document_from_node(*self); + let doc = document_from_node(self); if !value.is_empty() { let value = value.atom().unwrap().clone(); - doc.r().register_named_element(*self, value); + doc.r().register_named_element(self, value); } doc.r().content_changed(node, NodeDamage::NodeStyleDamaged); } @@ -1592,7 +1515,7 @@ impl<'a> VirtualMethods for &'a Element { _ => { // Modifying any other attribute might change arbitrary things. if node.is_in_doc() { - let document = document_from_node(*self); + let document = document_from_node(self); document.r().content_changed(node, NodeDamage::OtherNodeDamage); } } @@ -1604,14 +1527,14 @@ impl<'a> VirtualMethods for &'a Element { s.before_remove_attr(attr); } - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); match attr.local_name() { &atom!("style") => { // Modifying the `style` attribute might change style. *self.style_attribute.borrow_mut() = None; if node.is_in_doc() { - let doc = document_from_node(*self); + let doc = document_from_node(self); doc.r().content_changed(node, NodeDamage::NodeStyleDamaged); } } @@ -1619,10 +1542,10 @@ impl<'a> VirtualMethods for &'a Element { // Modifying an ID can change style. let value = attr.value(); if node.is_in_doc() { - let doc = document_from_node(*self); + let doc = document_from_node(self); if !value.is_empty() { let value = value.atom().unwrap().clone(); - doc.r().unregister_named_element(*self, value); + doc.r().unregister_named_element(self, value); } doc.r().content_changed(node, NodeDamage::NodeStyleDamaged); } @@ -1630,14 +1553,14 @@ impl<'a> VirtualMethods for &'a Element { &atom!("class") => { // Modifying a class can change style. if node.is_in_doc() { - let document = document_from_node(*self); + let document = document_from_node(self); document.r().content_changed(node, NodeDamage::NodeStyleDamaged); } } _ => { // Modifying any other attribute might change arbitrary things. if node.is_in_doc() { - let doc = document_from_node(*self); + let doc = document_from_node(self); doc.r().content_changed(node, NodeDamage::OtherNodeDamage); } } @@ -1660,11 +1583,11 @@ impl<'a> VirtualMethods for &'a Element { if !tree_in_doc { return; } if let Some(ref attr) = self.get_attribute(&ns!(""), &atom!("id")) { - let doc = document_from_node(*self); + let doc = document_from_node(self); let value = attr.r().Value(); if !value.is_empty() { let value = Atom::from_slice(&value); - doc.r().register_named_element(*self, value); + doc.r().register_named_element(self, value); } } } @@ -1677,11 +1600,11 @@ impl<'a> VirtualMethods for &'a Element { if !tree_in_doc { return; } if let Some(ref attr) = self.get_attribute(&ns!(""), &atom!("id")) { - let doc = document_from_node(*self); + let doc = document_from_node(self); let value = attr.r().Value(); if !value.is_empty() { let value = Atom::from_slice(&value); - doc.r().unregister_named_element(*self, value); + doc.r().unregister_named_element(self, value); } } } @@ -1747,7 +1670,7 @@ impl<'a> ::selectors::Element for Root { } fn get_local_name<'b>(&'b self) -> &'b Atom { - ElementHelpers::local_name(&**self) + self.local_name() } fn get_namespace<'b>(&'b self) -> &'b Namespace { self.namespace() @@ -1798,7 +1721,7 @@ impl<'a> ::selectors::Element for Root { } } fn has_class(&self, name: &Atom) -> bool { - AttributeHandlers::has_class(&**self, name) + Element::has_class(&**self, name) } fn each_class(&self, mut callback: F) where F: FnMut(&Atom) @@ -1859,24 +1782,17 @@ impl<'a> ::selectors::Element for Root { } } -pub trait ActivationElementHelpers<'a> { - fn as_maybe_activatable(&'a self) -> Option<&'a (Activatable + 'a)>; - fn click_in_progress(self) -> bool; - fn set_click_in_progress(self, click: bool); - fn nearest_activable_element(self) -> Option>; - fn authentic_click_activation<'b>(self, event: &'b Event); -} -impl<'a> ActivationElementHelpers<'a> for &'a Element { - fn as_maybe_activatable(&'a self) -> Option<&'a (Activatable + 'a)> { - let node = NodeCast::from_ref(*self); +impl Element { + pub fn as_maybe_activatable<'a>(&'a self) -> Option<&'a (Activatable + 'a)> { + let node = NodeCast::from_ref(self); let element = match node.type_id() { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => { - let element = HTMLInputElementCast::to_borrowed_ref(self).unwrap(); + let element = HTMLInputElementCast::to_ref(self).unwrap(); Some(element as &'a (Activatable + 'a)) }, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) => { - let element = HTMLAnchorElementCast::to_borrowed_ref(self).unwrap(); + let element = HTMLAnchorElementCast::to_ref(self).unwrap(); Some(element as &'a (Activatable + 'a)) }, _ => { @@ -1892,18 +1808,18 @@ impl<'a> ActivationElementHelpers<'a> for &'a Element { }) } - fn click_in_progress(self) -> bool { + pub fn click_in_progress(&self) -> bool { let node = NodeCast::from_ref(self); node.get_flag(CLICK_IN_PROGRESS) } - fn set_click_in_progress(self, click: bool) { + pub fn set_click_in_progress(&self, click: bool) { let node = NodeCast::from_ref(self); node.set_flag(CLICK_IN_PROGRESS, click) } // https://html.spec.whatwg.org/multipage/#nearest-activatable-element - fn nearest_activable_element(self) -> Option> { + pub fn nearest_activable_element(&self) -> Option> { match self.as_maybe_activatable() { Some(el) => Some(Root::from_ref(el.as_element())), None => { @@ -1926,7 +1842,7 @@ impl<'a> ActivationElementHelpers<'a> for &'a Element { /// /// Use an element's synthetic click activation (or handle_event) for any script-triggered clicks. /// If the spec says otherwise, check with Manishearth first - fn authentic_click_activation<'b>(self, event: &'b Event) { + pub fn authentic_click_activation<'b>(&self, event: &'b Event) { // Not explicitly part of the spec, however this helps enforce the invariants // required to save state between pre-activation and post-activation // since we cannot nest authentic clicks (unlike synthetic click activation, where @@ -1953,10 +1869,10 @@ impl<'a> ActivationElementHelpers<'a> for &'a Element { } } // Step 6 - None => {event.fire(target);} + None => { event.fire(target); } }, // Step 6 - None => {event.fire(target);} + None => { event.fire(target); } } // Step 7 self.set_click_in_progress(false); diff --git a/components/script/dom/errorevent.rs b/components/script/dom/errorevent.rs index 9fa8807972b..af28a44d0dc 100644 --- a/components/script/dom/errorevent.rs +++ b/components/script/dom/errorevent.rs @@ -22,7 +22,6 @@ use std::borrow::ToOwned; use std::cell::Cell; #[dom_struct] -#[derive(HeapSizeOf)] pub struct ErrorEvent { event: Event, message: DOMRefCell, @@ -115,29 +114,29 @@ impl ErrorEvent { } -impl<'a> ErrorEventMethods for &'a ErrorEvent { +impl ErrorEventMethods for ErrorEvent { // https://html.spec.whatwg.org/multipage/#dom-errorevent-lineno - fn Lineno(self) -> u32 { + fn Lineno(&self) -> u32 { self.lineno.get() } // https://html.spec.whatwg.org/multipage/#dom-errorevent-colno - fn Colno(self) -> u32 { + fn Colno(&self) -> u32 { self.colno.get() } // https://html.spec.whatwg.org/multipage/#dom-errorevent-message - fn Message(self) -> DOMString { + fn Message(&self) -> DOMString { self.message.borrow().clone() } // https://html.spec.whatwg.org/multipage/#dom-errorevent-filename - fn Filename(self) -> DOMString { + fn Filename(&self) -> DOMString { self.filename.borrow().clone() } // https://html.spec.whatwg.org/multipage/#dom-errorevent-error - fn Error(self, _cx: *mut JSContext) -> JSVal { + fn Error(&self, _cx: *mut JSContext) -> JSVal { self.error.get() } diff --git a/components/script/dom/event.rs b/components/script/dom/event.rs index 77f7f7aa595..58b45932cd8 100644 --- a/components/script/dom/event.rs +++ b/components/script/dom/event.rs @@ -9,7 +9,7 @@ use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::utils::{Reflector, reflect_dom_object}; -use dom::eventtarget::{EventTarget, EventTargetHelpers}; +use dom::eventtarget::EventTarget; use dom::uievent::{UIEventTypeId}; use util::str::DOMString; @@ -54,7 +54,6 @@ pub enum EventCancelable { } #[dom_struct] -#[derive(HeapSizeOf)] pub struct Event { reflector_: Reflector, type_id: EventTypeId, @@ -173,67 +172,67 @@ impl Event { } } -impl<'a> EventMethods for &'a Event { +impl EventMethods for Event { // https://dom.spec.whatwg.org/#dom-event-eventphase - fn EventPhase(self) -> u16 { + fn EventPhase(&self) -> u16 { self.phase.get() as u16 } // https://dom.spec.whatwg.org/#dom-event-type - fn Type(self) -> DOMString { + fn Type(&self) -> DOMString { self.type_.borrow().clone() } // https://dom.spec.whatwg.org/#dom-event-target - fn GetTarget(self) -> Option> { + fn GetTarget(&self) -> Option> { self.target.get().map(Root::from_rooted) } // https://dom.spec.whatwg.org/#dom-event-currenttarget - fn GetCurrentTarget(self) -> Option> { + fn GetCurrentTarget(&self) -> Option> { self.current_target.get().map(Root::from_rooted) } // https://dom.spec.whatwg.org/#dom-event-defaultprevented - fn DefaultPrevented(self) -> bool { + fn DefaultPrevented(&self) -> bool { self.canceled.get() } // https://dom.spec.whatwg.org/#dom-event-preventdefault - fn PreventDefault(self) { + fn PreventDefault(&self) { if self.cancelable.get() { self.canceled.set(true) } } // https://dom.spec.whatwg.org/#dom-event-stoppropagation - fn StopPropagation(self) { + fn StopPropagation(&self) { self.stop_propagation.set(true); } // https://dom.spec.whatwg.org/#dom-event-stopimmediatepropagation - fn StopImmediatePropagation(self) { + fn StopImmediatePropagation(&self) { self.stop_immediate.set(true); self.stop_propagation.set(true); } // https://dom.spec.whatwg.org/#dom-event-bubbles - fn Bubbles(self) -> bool { + fn Bubbles(&self) -> bool { self.bubbles.get() } // https://dom.spec.whatwg.org/#dom-event-cancelable - fn Cancelable(self) -> bool { + fn Cancelable(&self) -> bool { self.cancelable.get() } // https://dom.spec.whatwg.org/#dom-event-timestamp - fn TimeStamp(self) -> u64 { + fn TimeStamp(&self) -> u64 { self.timestamp } // https://dom.spec.whatwg.org/#dom-event-initevent - fn InitEvent(self, + fn InitEvent(&self, type_: DOMString, bubbles: bool, cancelable: bool) { @@ -253,23 +252,19 @@ impl<'a> EventMethods for &'a Event { } // https://dom.spec.whatwg.org/#dom-event-istrusted - fn IsTrusted(self) -> bool { + fn IsTrusted(&self) -> bool { self.trusted.get() } } -pub trait EventHelpers { - fn set_trusted(self, trusted: bool); - fn fire(self, target: &EventTarget) -> bool; -} -impl<'a> EventHelpers for &'a Event { - fn set_trusted(self, trusted: bool) { +impl Event { + pub fn set_trusted(&self, trusted: bool) { self.trusted.set(trusted); } // https://html.spec.whatwg.org/multipage/#fire-a-simple-event - fn fire(self, target: &EventTarget) -> bool { + pub fn fire(&self, target: &EventTarget) -> bool { self.set_trusted(true); target.dispatch_event(self) } diff --git a/components/script/dom/eventdispatcher.rs b/components/script/dom/eventdispatcher.rs index 0f6f5bda40e..024ba6a1350 100644 --- a/components/script/dom/eventdispatcher.rs +++ b/components/script/dom/eventdispatcher.rs @@ -9,7 +9,7 @@ use dom::bindings::js::JS; use dom::bindings::trace::RootedVec; use dom::event::{Event, EventPhase}; use dom::eventtarget::{EventTarget, ListenerPhase}; -use dom::node::{Node, NodeHelpers}; +use dom::node::Node; use dom::virtualmethods::vtable_for; // See https://dom.spec.whatwg.org/#concept-event-dispatch for the full dispatch algorithm diff --git a/components/script/dom/eventtarget.rs b/components/script/dom/eventtarget.rs index 8a73be8e11e..704ea280613 100644 --- a/components/script/dom/eventtarget.rs +++ b/components/script/dom/eventtarget.rs @@ -10,7 +10,7 @@ use dom::bindings::codegen::Bindings::EventTargetBinding::EventTargetMethods; use dom::bindings::error::Error::InvalidState; use dom::bindings::error::{Fallible, report_pending_exception}; use dom::bindings::utils::{Reflectable, Reflector}; -use dom::event::{Event, EventHelpers}; +use dom::event::Event; use dom::eventdispatcher::dispatch_event; use dom::node::NodeTypeId; use dom::virtualmethods::VirtualMethods; @@ -130,7 +130,6 @@ pub struct EventListenerEntry { } #[dom_struct] -#[derive(HeapSizeOf)] pub struct EventTarget { reflector_: Reflector, type_id: EventTargetTypeId, @@ -164,42 +163,18 @@ impl EventTarget { pub fn type_id<'a>(&'a self) -> &'a EventTargetTypeId { &self.type_id } -} -pub trait EventTargetHelpers { - fn dispatch_event_with_target(self, - target: &EventTarget, - event: &Event) -> bool; - fn dispatch_event(self, event: &Event) -> bool; - fn set_inline_event_listener(self, - ty: DOMString, - listener: Option>); - fn get_inline_event_listener(self, ty: DOMString) -> Option>; - fn set_event_handler_uncompiled(self, - cx: *mut JSContext, - url: Url, - scope: HandleObject, - ty: &str, - source: DOMString); - fn set_event_handler_common(self, ty: &str, - listener: Option>); - fn get_event_handler_common(self, ty: &str) -> Option>; - - fn has_handlers(self) -> bool; -} - -impl<'a> EventTargetHelpers for &'a EventTarget { - fn dispatch_event_with_target(self, + pub fn dispatch_event_with_target(&self, target: &EventTarget, event: &Event) -> bool { dispatch_event(self, Some(target), event) } - fn dispatch_event(self, event: &Event) -> bool { + pub fn dispatch_event(&self, event: &Event) -> bool { dispatch_event(self, None, event) } - fn set_inline_event_listener(self, + pub fn set_inline_event_listener(&self, ty: DOMString, listener: Option>) { let mut handlers = self.handlers.borrow_mut(); @@ -235,7 +210,7 @@ impl<'a> EventTargetHelpers for &'a EventTarget { } } - fn get_inline_event_listener(self, ty: DOMString) -> Option> { + pub fn get_inline_event_listener(&self, ty: DOMString) -> Option> { let handlers = self.handlers.borrow(); let entries = handlers.get(&ty); entries.and_then(|entries| entries.iter().filter_map(|entry| { @@ -247,7 +222,7 @@ impl<'a> EventTargetHelpers for &'a EventTarget { } #[allow(unsafe_code)] - fn set_event_handler_uncompiled(self, + pub fn set_event_handler_uncompiled(&self, cx: *mut JSContext, url: Url, scope: HandleObject, @@ -288,27 +263,27 @@ impl<'a> EventTargetHelpers for &'a EventTarget { self.set_event_handler_common(ty, Some(EventHandlerNonNull::new(funobj))); } - fn set_event_handler_common( - self, ty: &str, listener: Option>) + pub fn set_event_handler_common( + &self, ty: &str, listener: Option>) { let event_listener = listener.map(|listener| EventHandlerNonNull::new(listener.callback())); self.set_inline_event_listener(ty.to_owned(), event_listener); } - fn get_event_handler_common(self, ty: &str) -> Option> { + pub fn get_event_handler_common(&self, ty: &str) -> Option> { let listener = self.get_inline_event_listener(ty.to_owned()); listener.map(|listener| CallbackContainer::new(listener.parent.callback())) } - fn has_handlers(self) -> bool { + pub fn has_handlers(&self) -> bool { !self.handlers.borrow().is_empty() } } -impl<'a> EventTargetMethods for &'a EventTarget { +impl EventTargetMethods for EventTarget { // https://dom.spec.whatwg.org/#dom-eventtarget-addeventlistener - fn AddEventListener(self, + fn AddEventListener(&self, ty: DOMString, listener: Option>, capture: bool) { @@ -334,7 +309,7 @@ impl<'a> EventTargetMethods for &'a EventTarget { } // https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener - fn RemoveEventListener(self, + fn RemoveEventListener(&self, ty: DOMString, listener: Option>, capture: bool) { @@ -358,7 +333,7 @@ impl<'a> EventTargetMethods for &'a EventTarget { } // https://dom.spec.whatwg.org/#dom-eventtarget-dispatchevent - fn DispatchEvent(self, event: &Event) -> Fallible { + fn DispatchEvent(&self, event: &Event) -> Fallible { if event.dispatching() || !event.initialized() { return Err(InvalidState); } @@ -367,7 +342,7 @@ impl<'a> EventTargetMethods for &'a EventTarget { } } -impl<'a> VirtualMethods for &'a EventTarget { +impl VirtualMethods for EventTarget { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { None } diff --git a/components/script/dom/file.rs b/components/script/dom/file.rs index 563c60bc9b3..8da50b26b13 100644 --- a/components/script/dom/file.rs +++ b/components/script/dom/file.rs @@ -11,7 +11,6 @@ use dom::blob::{Blob, BlobTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct File { blob: Blob, name: DOMString, @@ -40,10 +39,9 @@ impl File { } } -impl<'a> FileMethods for &'a File { +impl FileMethods for File { // https://w3c.github.io/FileAPI/#dfn-name - fn Name(self) -> DOMString { + fn Name(&self) -> DOMString { self.name.clone() } } - diff --git a/components/script/dom/filelist.rs b/components/script/dom/filelist.rs index b6a650cee65..57542b0a51d 100644 --- a/components/script/dom/filelist.rs +++ b/components/script/dom/filelist.rs @@ -12,7 +12,6 @@ use dom::window::Window; // https://w3c.github.io/FileAPI/#dfn-filelist #[dom_struct] -#[derive(HeapSizeOf)] pub struct FileList { reflector_: Reflector, list: Vec> @@ -31,22 +30,21 @@ impl FileList { } } -impl<'a> FileListMethods for &'a FileList { +impl FileListMethods for FileList { // https://w3c.github.io/FileAPI/#dfn-length - fn Length(self) -> u32 { + fn Length(&self) -> u32 { self.list.len() as u32 } // https://w3c.github.io/FileAPI/#dfn-item - fn Item(self, index: u32) -> Option> { + fn Item(&self, index: u32) -> Option> { Some(self.list[index as usize].root()) } // check-tidy: no specs after this line - fn IndexedGetter(self, index: u32, found: &mut bool) -> Option> { + fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option> { let item = self.Item(index); *found = item.is_some(); item } } - diff --git a/components/script/dom/filereader.rs b/components/script/dom/filereader.rs index f23578a0535..ffd74806c04 100644 --- a/components/script/dom/filereader.rs +++ b/components/script/dom/filereader.rs @@ -12,16 +12,17 @@ use dom::bindings::global::{GlobalRef, GlobalField}; use dom::bindings::js::{Root, JS, MutNullableHeap}; use dom::bindings::refcounted::Trusted; use dom::bindings::utils::{reflect_dom_object, Reflectable}; -use dom::blob::{Blob, BlobHelpers}; +use dom::blob::Blob; use dom::domexception::{DOMException, DOMErrorName}; -use dom::event::{EventHelpers, EventCancelable, EventBubbles}; -use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; +use dom::event::{EventCancelable, EventBubbles}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::progressevent::ProgressEvent; use encoding::all::UTF_8; use encoding::label::encoding_from_whatwg_label; use encoding::types::{EncodingRef, DecoderTrap}; use hyper::mime::{Mime, Attr}; use rustc_serialize::base64::{Config, ToBase64, CharacterSet, Newline}; +use script_task::ScriptTaskEventCategory::FileRead; use script_task::{ScriptChan, Runnable, ScriptPort, CommonScriptMsg}; use std::cell::{Cell, RefCell}; use std::sync::mpsc; @@ -67,7 +68,6 @@ pub enum FileReaderReadyState { } #[dom_struct] -#[derive(HeapSizeOf)] pub struct FileReader { eventtarget: EventTarget, global: GlobalField, @@ -252,27 +252,38 @@ impl FileReader { } } -impl<'a> FileReaderMethods for &'a FileReader { +impl FileReaderMethods for FileReader { + // https://w3c.github.io/FileAPI/#dfn-onloadstart event_handler!(loadstart, GetOnloadstart, SetOnloadstart); + + // https://w3c.github.io/FileAPI/#dfn-onprogress event_handler!(progress, GetOnprogress, SetOnprogress); + + // https://w3c.github.io/FileAPI/#dfn-onload event_handler!(load, GetOnload, SetOnload); + + // https://w3c.github.io/FileAPI/#dfn-onabort event_handler!(abort, GetOnabort, SetOnabort); + + // https://w3c.github.io/FileAPI/#dfn-onerror event_handler!(error, GetOnerror, SetOnerror); + + // https://w3c.github.io/FileAPI/#dfn-onloadend event_handler!(loadend, GetOnloadend, SetOnloadend); //TODO https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer // https://w3c.github.io/FileAPI/#dfn-readAsDataURL - fn ReadAsDataURL(self, blob: &Blob) -> ErrorResult { + fn ReadAsDataURL(&self, blob: &Blob) -> ErrorResult { self.read(FileReaderFunction::ReadAsDataUrl, blob, None) } // https://w3c.github.io/FileAPI/#dfn-readAsText - fn ReadAsText(self, blob: &Blob, label: Option) -> ErrorResult { + fn ReadAsText(&self, blob: &Blob, label: Option) -> ErrorResult { self.read(FileReaderFunction::ReadAsText, blob, label) } // https://w3c.github.io/FileAPI/#dfn-abort - fn Abort(self) { + fn Abort(&self) { // Step 2 if self.ready_state.get() == FileReaderReadyState::Loading { self.change_ready_state(FileReaderReadyState::Done); @@ -291,30 +302,24 @@ impl<'a> FileReaderMethods for &'a FileReader { } // https://w3c.github.io/FileAPI/#dfn-error - fn GetError(self) -> Option> { + fn GetError(&self) -> Option> { self.error.get().map(|error| error.root()) } // https://w3c.github.io/FileAPI/#dfn-result - fn GetResult(self) -> Option { + fn GetResult(&self) -> Option { self.result.borrow().clone() } // https://w3c.github.io/FileAPI/#dfn-readyState - fn ReadyState(self) -> u16 { + fn ReadyState(&self) -> u16 { self.ready_state.get() as u16 } } -trait PrivateFileReaderHelpers { - fn dispatch_progress_event(self, type_: DOMString, loaded: u64, total: Option); - fn terminate_ongoing_reading(self); - fn read(self, function: FileReaderFunction, blob: &Blob, label: Option) -> ErrorResult; - fn change_ready_state(self, state: FileReaderReadyState); -} -impl<'a> PrivateFileReaderHelpers for &'a FileReader { - fn dispatch_progress_event(self, type_: DOMString, loaded: u64, total: Option) { +impl FileReader { + fn dispatch_progress_event(&self, type_: DOMString, loaded: u64, total: Option) { let global = self.global.root(); let progressevent = ProgressEvent::new(global.r(), @@ -326,12 +331,12 @@ impl<'a> PrivateFileReaderHelpers for &'a FileReader { event.fire(target); } - fn terminate_ongoing_reading(self) { + fn terminate_ongoing_reading(&self) { let GenerationId(prev_id) = self.generation_id.get(); self.generation_id.set(GenerationId(prev_id + 1)); } - fn read(self, function: FileReaderFunction, blob: &Blob, label: Option) -> ErrorResult { + fn read(&self, function: FileReaderFunction, blob: &Blob, label: Option) -> ErrorResult { let root = self.global.root(); let global = root.r(); // Step 1 @@ -369,7 +374,7 @@ impl<'a> PrivateFileReaderHelpers for &'a FileReader { Ok(()) } - fn change_ready_state(self, state: FileReaderReadyState) { + fn change_ready_state(&self, state: FileReaderReadyState) { self.ready_state.set(state); } } @@ -408,22 +413,22 @@ fn perform_annotated_read_operation(gen_id: GenerationId, data: ReadMetaData, bl let chan = &script_chan; // Step 4 let task = box FileReaderEvent::ProcessRead(filereader.clone(), gen_id); - chan.send(CommonScriptMsg::RunnableMsg(task)).unwrap(); + chan.send(CommonScriptMsg::RunnableMsg(FileRead, task)).unwrap(); let task = box FileReaderEvent::ProcessReadData(filereader.clone(), gen_id, DOMString::new()); - chan.send(CommonScriptMsg::RunnableMsg(task)).unwrap(); + chan.send(CommonScriptMsg::RunnableMsg(FileRead, task)).unwrap(); let bytes = match blob_contents.recv() { Ok(bytes) => bytes, Err(_) => { let task = box FileReaderEvent::ProcessReadError(filereader, gen_id, DOMErrorName::NotFoundError); - chan.send(CommonScriptMsg::RunnableMsg(task)).unwrap(); + chan.send(CommonScriptMsg::RunnableMsg(FileRead, task)).unwrap(); return; } }; let task = box FileReaderEvent::ProcessReadEOF(filereader, gen_id, data, bytes); - chan.send(CommonScriptMsg::RunnableMsg(task)).unwrap(); + chan.send(CommonScriptMsg::RunnableMsg(FileRead, task)).unwrap(); } diff --git a/components/script/dom/formdata.rs b/components/script/dom/formdata.rs index cd26613cb74..8631cefbd4a 100644 --- a/components/script/dom/formdata.rs +++ b/components/script/dom/formdata.rs @@ -30,7 +30,6 @@ pub enum FormDatum { } #[dom_struct] -#[derive(HeapSizeOf)] pub struct FormData { reflector_: Reflector, data: DOMRefCell>>, @@ -58,10 +57,10 @@ impl FormData { } } -impl<'a> FormDataMethods for &'a FormData { +impl FormDataMethods for FormData { #[allow(unrooted_must_root)] // https://xhr.spec.whatwg.org/#dom-formdata-append - fn Append(self, name: DOMString, value: &Blob, filename: Option) { + fn Append(&self, name: DOMString, value: &Blob, filename: Option) { let file = FormDatum::FileData(JS::from_rooted(&self.get_file_from_blob(value, filename))); let mut data = self.data.borrow_mut(); match data.entry(name) { @@ -73,7 +72,7 @@ impl<'a> FormDataMethods for &'a FormData { } // https://xhr.spec.whatwg.org/#dom-formdata-append - fn Append_(self, name: DOMString, value: DOMString) { + fn Append_(&self, name: DOMString, value: DOMString) { let mut data = self.data.borrow_mut(); match data.entry(name) { Occupied(entry) => entry.into_mut().push(FormDatum::StringData(value)), @@ -82,51 +81,41 @@ impl<'a> FormDataMethods for &'a FormData { } // https://xhr.spec.whatwg.org/#dom-formdata-delete - fn Delete(self, name: DOMString) { + fn Delete(&self, name: DOMString) { self.data.borrow_mut().remove(&name); } - #[allow(unsafe_code)] // https://xhr.spec.whatwg.org/#dom-formdata-get - fn Get(self, name: DOMString) -> Option { - // FIXME(https://github.com/rust-lang/rust/issues/23338) - let data = self.data.borrow(); - if data.contains_key(&name) { - match data[&name][0].clone() { - FormDatum::StringData(ref s) => Some(eString(s.clone())), - FormDatum::FileData(ref f) => { - Some(eFile(f.root())) - } - } - } else { - None - } + fn Get(&self, name: DOMString) -> Option { + self.data.borrow() + .get(&name) + .map(|entry| match entry[0] { + FormDatum::StringData(ref s) => eString(s.clone()), + FormDatum::FileData(ref f) => eFile(f.root()), + }) } // https://xhr.spec.whatwg.org/#dom-formdata-has - fn Has(self, name: DOMString) -> bool { + fn Has(&self, name: DOMString) -> bool { self.data.borrow().contains_key(&name) } // https://xhr.spec.whatwg.org/#dom-formdata-set - fn Set_(self, name: DOMString, value: DOMString) { + fn Set_(&self, name: DOMString, value: DOMString) { self.data.borrow_mut().insert(name, vec!(FormDatum::StringData(value))); } #[allow(unrooted_must_root)] // https://xhr.spec.whatwg.org/#dom-formdata-set - fn Set(self, name: DOMString, value: &Blob, filename: Option) { + fn Set(&self, name: DOMString, value: &Blob, filename: Option) { let file = FormDatum::FileData(JS::from_rooted(&self.get_file_from_blob(value, filename))); self.data.borrow_mut().insert(name, vec!(file)); } } -trait PrivateFormDataHelpers { - fn get_file_from_blob(self, value: &Blob, filename: Option) -> Root; -} -impl<'a> PrivateFormDataHelpers for &'a FormData { - fn get_file_from_blob(self, value: &Blob, filename: Option) -> Root { +impl FormData { + fn get_file_from_blob(&self, value: &Blob, filename: Option) -> Root { let global = self.global.root(); let f: Option<&File> = FileCast::to_ref(value); let name = filename.unwrap_or(f.map(|inner| inner.name().clone()).unwrap_or("blob".to_owned())); diff --git a/components/script/dom/htmlanchorelement.rs b/components/script/dom/htmlanchorelement.rs index c514a963bd5..67daf4e6df4 100644 --- a/components/script/dom/htmlanchorelement.rs +++ b/components/script/dom/htmlanchorelement.rs @@ -14,15 +14,14 @@ use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast}; use dom::bindings::codegen::InheritTypes::{HTMLAnchorElementDerived, HTMLImageElementDerived}; use dom::bindings::codegen::InheritTypes::{MouseEventCast, NodeCast}; use dom::bindings::js::{JS, MutNullableHeap, Root}; -use dom::document::{Document, DocumentHelpers}; +use dom::document::Document; use dom::domtokenlist::DOMTokenList; -use dom::element::{Element, AttributeHandlers, ElementTypeId}; +use dom::element::{Element, ElementTypeId}; use dom::event::Event; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; -use dom::node::{Node, NodeHelpers, NodeTypeId, document_from_node, window_from_node}; +use dom::node::{Node, NodeTypeId, document_from_node, window_from_node}; use dom::virtualmethods::VirtualMethods; -use dom::window::WindowHelpers; use util::str::DOMString; @@ -33,7 +32,6 @@ use url::UrlParser; use std::default::Default; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLAnchorElement { htmlelement: HTMLElement, rel_list: MutNullableHeap>, @@ -67,9 +65,9 @@ impl HTMLAnchorElement { } } -impl<'a> VirtualMethods for &'a HTMLAnchorElement { +impl VirtualMethods for HTMLAnchorElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -81,30 +79,30 @@ impl<'a> VirtualMethods for &'a HTMLAnchorElement { } } -impl<'a> HTMLAnchorElementMethods for &'a HTMLAnchorElement { +impl HTMLAnchorElementMethods for HTMLAnchorElement { // https://html.spec.whatwg.org/multipage/#dom-a-text - fn Text(self) -> DOMString { + fn Text(&self) -> DOMString { let node = NodeCast::from_ref(self); node.GetTextContent().unwrap() } // https://html.spec.whatwg.org/multipage/#dom-a-text - fn SetText(self, value: DOMString) { + fn SetText(&self, value: DOMString) { let node = NodeCast::from_ref(self); node.SetTextContent(Some(value)) } // https://html.spec.whatwg.org/multipage/#dom-a-rellist - fn RelList(self) -> Root { + fn RelList(&self) -> Root { self.rel_list.or_init(|| { DOMTokenList::new(ElementCast::from_ref(self), &atom!("rel")) }) } } -impl<'a> Activatable for &'a HTMLAnchorElement { +impl Activatable for HTMLAnchorElement { fn as_element<'b>(&'b self) -> &'b Element { - ElementCast::from_ref(*self) + ElementCast::from_ref(self) } fn is_instance_activatable(&self) -> bool { @@ -113,7 +111,7 @@ impl<'a> Activatable for &'a HTMLAnchorElement { // hyperlink" // https://html.spec.whatwg.org/multipage/#the-a-element // "The activation behaviour of a elements *that create hyperlinks*" - ElementCast::from_ref(*self).has_attribute(&atom!("href")) + ElementCast::from_ref(self).has_attribute(&atom!("href")) } @@ -129,13 +127,13 @@ impl<'a> Activatable for &'a HTMLAnchorElement { //https://html.spec.whatwg.org/multipage/#the-a-element:activation-behaviour fn activation_behavior(&self, event: &Event, target: &EventTarget) { //Step 1. If the node document is not fully active, abort. - let doc = document_from_node(*self); + let doc = document_from_node(self); if !doc.r().is_fully_active() { return; } //TODO: Step 2. Check if browsing context is specified and act accordingly. //Step 3. Handle . - let element = ElementCast::from_ref(*self); + let element = ElementCast::from_ref(self); let mouse_event = MouseEventCast::to_ref(event).unwrap(); let mut ismap_suffix = None; if let Some(element) = ElementCast::to_ref(target) { diff --git a/components/script/dom/htmlappletelement.rs b/components/script/dom/htmlappletelement.rs index ab9db6955dd..988aa36e9ee 100644 --- a/components/script/dom/htmlappletelement.rs +++ b/components/script/dom/htmlappletelement.rs @@ -10,7 +10,7 @@ use dom::bindings::codegen::InheritTypes::HTMLAppletElementDerived; use dom::bindings::codegen::InheritTypes::HTMLElementCast; use dom::bindings::js::Root; use dom::document::Document; -use dom::element::{AttributeHandlers, ElementTypeId}; +use dom::element::ElementTypeId; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{Node, NodeTypeId}; @@ -20,7 +20,6 @@ use string_cache::Atom; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLAppletElement { htmlelement: HTMLElement } @@ -52,15 +51,17 @@ impl HTMLAppletElement { } } -impl<'a> HTMLAppletElementMethods for &'a HTMLAppletElement { +impl HTMLAppletElementMethods for HTMLAppletElement { // https://html.spec.whatwg.org/#the-applet-element:dom-applet-name make_getter!(Name); + + // https://html.spec.whatwg.org/#the-applet-element:dom-applet-name make_atomic_setter!(SetName, "name"); } -impl<'a> VirtualMethods for &'a HTMLAppletElement { +impl VirtualMethods for HTMLAppletElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - Some(HTMLElementCast::from_borrowed_ref(self) as &VirtualMethods) + Some(HTMLElementCast::from_ref(self) as &VirtualMethods) } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { diff --git a/components/script/dom/htmlareaelement.rs b/components/script/dom/htmlareaelement.rs index c2241410fd9..02bd899c86c 100644 --- a/components/script/dom/htmlareaelement.rs +++ b/components/script/dom/htmlareaelement.rs @@ -14,7 +14,7 @@ use dom::domtokenlist::DOMTokenList; use dom::element::ElementTypeId; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; -use dom::node::{Node, NodeHelpers, NodeTypeId}; +use dom::node::{Node, NodeTypeId}; use dom::virtualmethods::VirtualMethods; use std::default::Default; @@ -22,7 +22,6 @@ use string_cache::Atom; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLAreaElement { htmlelement: HTMLElement, rel_list: MutNullableHeap>, @@ -53,9 +52,9 @@ impl HTMLAreaElement { } } -impl<'a> VirtualMethods for &'a HTMLAreaElement { +impl VirtualMethods for HTMLAreaElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -67,9 +66,9 @@ impl<'a> VirtualMethods for &'a HTMLAreaElement { } } -impl<'a> HTMLAreaElementMethods for &'a HTMLAreaElement { +impl HTMLAreaElementMethods for HTMLAreaElement { // https://html.spec.whatwg.org/multipage/#dom-area-rellist - fn RelList(self) -> Root { + fn RelList(&self) -> Root { self.rel_list.or_init(|| { DOMTokenList::new(ElementCast::from_ref(self), &atom!("rel")) }) diff --git a/components/script/dom/htmlaudioelement.rs b/components/script/dom/htmlaudioelement.rs index 10872b6e83b..0bb158836d6 100644 --- a/components/script/dom/htmlaudioelement.rs +++ b/components/script/dom/htmlaudioelement.rs @@ -14,7 +14,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLAudioElement { htmlmediaelement: HTMLMediaElement } @@ -46,4 +45,3 @@ impl HTMLAudioElement { Node::reflect_node(box element, document, HTMLAudioElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlbaseelement.rs b/components/script/dom/htmlbaseelement.rs index 202bfca992b..0a6e0ed8d0a 100644 --- a/components/script/dom/htmlbaseelement.rs +++ b/components/script/dom/htmlbaseelement.rs @@ -2,14 +2,14 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use dom::attr::{Attr, AttrHelpers}; +use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLBaseElementBinding; use dom::bindings::codegen::InheritTypes::ElementCast; use dom::bindings::codegen::InheritTypes::HTMLBaseElementDerived; use dom::bindings::codegen::InheritTypes::HTMLElementCast; use dom::bindings::js::Root; -use dom::document::{Document, DocumentHelpers}; -use dom::element::{ElementTypeId, AttributeHandlers}; +use dom::document::Document; +use dom::element::ElementTypeId; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{Node, NodeTypeId, document_from_node}; @@ -19,7 +19,6 @@ use util::str::DOMString; use url::{Url, UrlParser}; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLBaseElement { htmlelement: HTMLElement } @@ -80,9 +79,9 @@ impl HTMLBaseElement { } } -impl<'a> VirtualMethods for &'a HTMLBaseElement { +impl VirtualMethods for HTMLBaseElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - Some(HTMLElementCast::from_borrowed_ref(self) as &VirtualMethods) + Some(HTMLElementCast::from_ref(self) as &VirtualMethods) } fn after_set_attr(&self, attr: &Attr) { diff --git a/components/script/dom/htmlbodyelement.rs b/components/script/dom/htmlbodyelement.rs index 0b9412613e1..3016966fc10 100644 --- a/components/script/dom/htmlbodyelement.rs +++ b/components/script/dom/htmlbodyelement.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use dom::attr::{Attr, AttrHelpers}; +use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::HTMLBodyElementBinding::{self, HTMLBodyElementMethods}; @@ -11,13 +11,12 @@ use dom::bindings::codegen::InheritTypes::{EventTargetCast}; use dom::bindings::codegen::InheritTypes::{HTMLBodyElementDerived, HTMLElementCast}; use dom::bindings::js::Root; use dom::bindings::utils::Reflectable; -use dom::document::{Document, DocumentHelpers}; +use dom::document::Document; use dom::element::ElementTypeId; -use dom::eventtarget::{EventTarget, EventTargetTypeId, EventTargetHelpers}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{Node, NodeTypeId, window_from_node, document_from_node}; use dom::virtualmethods::VirtualMethods; -use dom::window::WindowHelpers; use msg::constellation_msg::ConstellationChan; use msg::constellation_msg::Msg as ConstellationMsg; @@ -35,7 +34,6 @@ use time; const INITIAL_REFLOW_DELAY: u64 = 200_000_000; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLBodyElement { htmlelement: HTMLElement, background_color: Cell>, @@ -70,45 +68,43 @@ impl HTMLBodyElement { } } -impl<'a> HTMLBodyElementMethods for &'a HTMLBodyElement { +impl HTMLBodyElementMethods for HTMLBodyElement { // https://html.spec.whatwg.org/multipage#dom-body-bgcolor make_getter!(BgColor, "bgcolor"); + + // https://html.spec.whatwg.org/multipage#dom-body-bgcolor make_setter!(SetBgColor, "bgcolor"); // https://html.spec.whatwg.org/multipage/#the-body-element - fn GetOnunload(self) -> Option> { + fn GetOnunload(&self) -> Option> { let win = window_from_node(self); win.r().GetOnunload() } // https://html.spec.whatwg.org/multipage/#the-body-element - fn SetOnunload(self, listener: Option>) { + fn SetOnunload(&self, listener: Option>) { let win = window_from_node(self); win.r().SetOnunload(listener) } } -pub trait HTMLBodyElementHelpers { - fn get_background_color(self) -> Option; - fn get_background(self) -> Option; -} -impl<'a> HTMLBodyElementHelpers for &'a HTMLBodyElement { - fn get_background_color(self) -> Option { +impl HTMLBodyElement { + pub fn get_background_color(&self) -> Option { self.background_color.get() } #[allow(unsafe_code)] - fn get_background(self) -> Option { + pub fn get_background(&self) -> Option { unsafe { self.background.borrow_for_layout().clone() } } } -impl<'a> VirtualMethods for &'a HTMLBodyElement { +impl VirtualMethods for HTMLBodyElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let element: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let element: &HTMLElement = HTMLElementCast::from_ref(self); Some(element as &VirtualMethods) } @@ -121,7 +117,7 @@ impl<'a> VirtualMethods for &'a HTMLBodyElement { return } - let window = window_from_node(*self); + let window = window_from_node(self); let document = window.r().Document(); document.r().set_reflow_timeout(time::precise_time_ns() + INITIAL_REFLOW_DELAY); let ConstellationChan(ref chan) = window.r().constellation_chan(); @@ -141,7 +137,7 @@ impl<'a> VirtualMethods for &'a HTMLBodyElement { "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onstorage", "onresize", "onunload", "onerror"]; - let window = window_from_node(*self); + let window = window_from_node(self); let (cx, url, reflector) = (window.r().get_cx(), window.r().get_url(), window.r().reflector().get_jsobject()); @@ -149,7 +145,7 @@ impl<'a> VirtualMethods for &'a HTMLBodyElement { if FORWARDED_EVENTS.iter().any(|&event| &**name == event) { EventTargetCast::from_ref(window.r()) } else { - EventTargetCast::from_ref(*self) + EventTargetCast::from_ref(self) }; evtarget.set_event_handler_uncompiled(cx, url, reflector, &name[2..], @@ -161,7 +157,7 @@ impl<'a> VirtualMethods for &'a HTMLBodyElement { self.background_color.set(str::parse_legacy_color(&attr.value()).ok()) } &atom!("background") => { - let doc = document_from_node(*self); + let doc = document_from_node(self); let base = doc.r().url(); *self.background.borrow_mut() = UrlParser::new().base_url(&base).parse(&attr.value()).ok(); @@ -183,4 +179,3 @@ impl<'a> VirtualMethods for &'a HTMLBodyElement { } } } - diff --git a/components/script/dom/htmlbrelement.rs b/components/script/dom/htmlbrelement.rs index 6330c15ddbb..a0a4b16d4d8 100644 --- a/components/script/dom/htmlbrelement.rs +++ b/components/script/dom/htmlbrelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLBRElement { htmlelement: HTMLElement, } @@ -41,4 +40,3 @@ impl HTMLBRElement { Node::reflect_node(box element, document, HTMLBRElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlbuttonelement.rs b/components/script/dom/htmlbuttonelement.rs index 54f6145b3b9..c7f3e71807e 100644 --- a/components/script/dom/htmlbuttonelement.rs +++ b/components/script/dom/htmlbuttonelement.rs @@ -4,21 +4,19 @@ use dom::activation::Activatable; use dom::attr::Attr; -use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLButtonElementBinding; use dom::bindings::codegen::Bindings::HTMLButtonElementBinding::HTMLButtonElementMethods; use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast, HTMLButtonElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{HTMLButtonElementDerived, HTMLFieldSetElementDerived}; use dom::bindings::js::Root; use dom::document::Document; -use dom::element::ActivationElementHelpers; -use dom::element::{AttributeHandlers, Element, ElementTypeId}; +use dom::element::{Element, ElementTypeId}; use dom::event::Event; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; -use dom::htmlformelement::{FormSubmitter, FormControl, HTMLFormElementHelpers}; +use dom::htmlformelement::{FormSubmitter, FormControl}; use dom::htmlformelement::{SubmittedFrom}; -use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId, document_from_node, window_from_node}; +use dom::node::{Node, NodeTypeId, document_from_node, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; @@ -38,7 +36,6 @@ enum ButtonType { } #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLButtonElement { htmlelement: HTMLElement, button_type: Cell @@ -73,9 +70,9 @@ impl HTMLButtonElement { } } -impl<'a> HTMLButtonElementMethods for &'a HTMLButtonElement { +impl HTMLButtonElementMethods for HTMLButtonElement { // https://html.spec.whatwg.org/multipage/#dom-cva-validity - fn Validity(self) -> Root { + fn Validity(&self) -> Root { let window = window_from_node(self); ValidityState::new(window.r()) } @@ -87,7 +84,7 @@ impl<'a> HTMLButtonElementMethods for &'a HTMLButtonElement { make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-button-type - fn Type(self) -> DOMString { + fn Type(&self) -> DOMString { let elem = ElementCast::from_ref(self); let mut ty = elem.get_string_attribute(&atom!("type")); ty.make_ascii_lowercase(); @@ -101,22 +98,29 @@ impl<'a> HTMLButtonElementMethods for &'a HTMLButtonElement { // https://html.spec.whatwg.org/multipage/#dom-button-type make_setter!(SetType, "type"); - // https://html.spec.whatwg.org/multipage/#htmlbuttonelement + // https://html.spec.whatwg.org/multipage/#dom-fs-formaction make_url_or_base_getter!(FormAction); + // https://html.spec.whatwg.org/multipage/#dom-fs-formaction make_setter!(SetFormAction, "formaction"); + // https://html.spec.whatwg.org/multipage/#dom-fs-formenctype make_enumerated_getter!( FormEnctype, "application/x-www-form-urlencoded", ("text/plain") | ("multipart/form-data")); + // https://html.spec.whatwg.org/multipage/#dom-fs-formenctype make_setter!(SetFormEnctype, "formenctype"); + // https://html.spec.whatwg.org/multipage/#dom-fs-formmethod make_enumerated_getter!(FormMethod, "get", ("post") | ("dialog")); + // https://html.spec.whatwg.org/multipage/#dom-fs-formmethod make_setter!(SetFormMethod, "formmethod"); + // https://html.spec.whatwg.org/multipage/#dom-fs-formtarget make_getter!(FormTarget); + // https://html.spec.whatwg.org/multipage/#dom-fs-formtarget make_setter!(SetFormTarget, "formtarget"); // https://html.spec.whatwg.org/multipage/#dom-fe-name @@ -132,9 +136,9 @@ impl<'a> HTMLButtonElementMethods for &'a HTMLButtonElement { make_setter!(SetValue, "value"); } -impl<'a> VirtualMethods for &'a HTMLButtonElement { +impl VirtualMethods for HTMLButtonElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -145,7 +149,7 @@ impl<'a> VirtualMethods for &'a HTMLButtonElement { match attr.local_name() { &atom!("disabled") => { - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.set_disabled_state(true); node.set_enabled_state(false); }, @@ -160,7 +164,7 @@ impl<'a> VirtualMethods for &'a HTMLButtonElement { match attr.local_name() { &atom!("disabled") => { - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.set_disabled_state(false); node.set_enabled_state(true); node.check_ancestors_disabled_state_for_form_control(); @@ -174,7 +178,7 @@ impl<'a> VirtualMethods for &'a HTMLButtonElement { s.bind_to_tree(tree_in_doc); } - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.check_ancestors_disabled_state_for_form_control(); } @@ -183,7 +187,7 @@ impl<'a> VirtualMethods for &'a HTMLButtonElement { s.unbind_from_tree(tree_in_doc); } - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); if node.ancestors().any(|ancestor| ancestor.r().is_htmlfieldsetelement()) { node.check_ancestors_disabled_state_for_form_control(); } else { @@ -253,4 +257,3 @@ impl<'a> Activatable for &'a HTMLButtonElement { } } } - diff --git a/components/script/dom/htmlcanvaselement.rs b/components/script/dom/htmlcanvaselement.rs index 83e8397d859..8da4c2cd155 100644 --- a/components/script/dom/htmlcanvaselement.rs +++ b/components/script/dom/htmlcanvaselement.rs @@ -3,7 +3,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; -use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding; use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding::HTMLCanvasElementMethods; use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLContextAttributes; @@ -15,7 +14,6 @@ use dom::bindings::js::{JS, LayoutJS, MutNullableHeap, HeapGCValue, Root}; use dom::bindings::utils::{Reflectable}; use dom::canvasrenderingcontext2d::{CanvasRenderingContext2D, LayoutCanvasRenderingContext2DHelpers}; use dom::document::Document; -use dom::element::AttributeHandlers; use dom::element::ElementTypeId; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; @@ -47,7 +45,6 @@ pub enum CanvasContext { impl HeapGCValue for CanvasContext {} #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLCanvasElement { htmlelement: HTMLElement, context: MutNullableHeap, @@ -154,17 +151,9 @@ impl LayoutHTMLCanvasElementHelpers for LayoutJS { } } -pub trait HTMLCanvasElementHelpers { - fn get_or_init_2d_context(self) -> Option>; - fn get_or_init_webgl_context(self, - cx: *mut JSContext, - attrs: Option) -> Option>; - fn is_valid(self) -> bool; -} - -impl<'a> HTMLCanvasElementHelpers for &'a HTMLCanvasElement { - fn get_or_init_2d_context(self) -> Option> { +impl HTMLCanvasElement { + pub fn get_or_init_2d_context(&self) -> Option> { if self.context.get().is_none() { let window = window_from_node(self); let size = self.get_size(); @@ -178,7 +167,7 @@ impl<'a> HTMLCanvasElementHelpers for &'a HTMLCanvasElement { } } - fn get_or_init_webgl_context(self, + pub fn get_or_init_webgl_context(&self, cx: *mut JSContext, attrs: Option) -> Option> { if self.context.get().is_none() { @@ -211,36 +200,36 @@ impl<'a> HTMLCanvasElementHelpers for &'a HTMLCanvasElement { } } - fn is_valid(self) -> bool { + pub fn is_valid(&self) -> bool { self.height.get() != 0 && self.width.get() != 0 } } -impl<'a> HTMLCanvasElementMethods for &'a HTMLCanvasElement { +impl HTMLCanvasElementMethods for HTMLCanvasElement { // https://html.spec.whatwg.org/multipage/#dom-canvas-width - fn Width(self) -> u32 { + fn Width(&self) -> u32 { self.width.get() } // https://html.spec.whatwg.org/multipage/#dom-canvas-width - fn SetWidth(self, width: u32) { + fn SetWidth(&self, width: u32) { let elem = ElementCast::from_ref(self); elem.set_uint_attribute(&atom!("width"), width) } // https://html.spec.whatwg.org/multipage/#dom-canvas-height - fn Height(self) -> u32 { + fn Height(&self) -> u32 { self.height.get() } // https://html.spec.whatwg.org/multipage/#dom-canvas-height - fn SetHeight(self, height: u32) { + fn SetHeight(&self, height: u32) { let elem = ElementCast::from_ref(self); elem.set_uint_attribute(&atom!("height"), height) } // https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext - fn GetContext(self, + fn GetContext(&self, cx: *mut JSContext, id: DOMString, attributes: Vec) @@ -261,9 +250,9 @@ impl<'a> HTMLCanvasElementMethods for &'a HTMLCanvasElement { } } -impl<'a> VirtualMethods for &'a HTMLCanvasElement { +impl VirtualMethods for HTMLCanvasElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let element: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let element: &HTMLElement = HTMLElementCast::from_ref(self); Some(element as &VirtualMethods) } @@ -340,4 +329,3 @@ pub mod utils { result.image_response } } - diff --git a/components/script/dom/htmlcollection.rs b/components/script/dom/htmlcollection.rs index f31dc1894d3..ad16e70afa2 100644 --- a/components/script/dom/htmlcollection.rs +++ b/components/script/dom/htmlcollection.rs @@ -9,8 +9,8 @@ use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::trace::JSTraceable; use dom::bindings::utils::{namespace_from_domstring, Reflector, reflect_dom_object}; -use dom::element::{Element, AttributeHandlers, ElementHelpers}; -use dom::node::{Node, NodeHelpers, TreeIterator}; +use dom::element::Element; +use dom::node::{Node, TreeIterator}; use dom::window::Window; use util::str::{DOMString, split_html_space_chars}; @@ -26,7 +26,6 @@ pub trait CollectionFilter : JSTraceable { pub struct Collection(JS, Box); #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLCollection { reflector_: Reflector, #[ignore_heap_size_of = "Contains a trait object; can't measure due to #6870"] @@ -45,9 +44,7 @@ impl HTMLCollection { reflect_dom_object(box HTMLCollection::new_inherited(collection), GlobalRef::Window(window), HTMLCollectionBinding::Wrap) } -} -impl HTMLCollection { pub fn create(window: &Window, root: &Node, filter: Box) -> Root { HTMLCollection::new(window, Collection(JS::from_ref(root), filter)) @@ -67,7 +64,7 @@ impl HTMLCollection { } } } - let filter = AllElementFilter {namespace_filter: namespace_filter}; + let filter = AllElementFilter { namespace_filter: namespace_filter }; HTMLCollection::create(window, root, box filter) } @@ -193,19 +190,19 @@ impl<'a> Iterator for HTMLCollectionElementsIter<'a> { } } -impl<'a> HTMLCollectionMethods for &'a HTMLCollection { +impl HTMLCollectionMethods for HTMLCollection { // https://dom.spec.whatwg.org/#dom-htmlcollection-length - fn Length(self) -> u32 { + fn Length(&self) -> u32 { self.elements_iter().count() as u32 } // https://dom.spec.whatwg.org/#dom-htmlcollection-item - fn Item(self, index: u32) -> Option> { + fn Item(&self, index: u32) -> Option> { self.elements_iter().nth(index as usize) } // https://dom.spec.whatwg.org/#dom-htmlcollection-nameditem - fn NamedItem(self, key: DOMString) -> Option> { + fn NamedItem(&self, key: DOMString) -> Option> { // Step 1. if key.is_empty() { return None; @@ -219,21 +216,21 @@ impl<'a> HTMLCollectionMethods for &'a HTMLCollection { } // https://dom.spec.whatwg.org/#dom-htmlcollection-item - fn IndexedGetter(self, index: u32, found: &mut bool) -> Option> { + fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option> { let maybe_elem = self.Item(index); *found = maybe_elem.is_some(); maybe_elem } // check-tidy: no specs after this line - fn NamedGetter(self, name: DOMString, found: &mut bool) -> Option> { + fn NamedGetter(&self, name: DOMString, found: &mut bool) -> Option> { let maybe_elem = self.NamedItem(name); *found = maybe_elem.is_some(); maybe_elem } // https://dom.spec.whatwg.org/#interface-htmlcollection - fn SupportedPropertyNames(self) -> Vec { + fn SupportedPropertyNames(&self) -> Vec { // Step 1 let mut result = vec![]; diff --git a/components/script/dom/htmldataelement.rs b/components/script/dom/htmldataelement.rs index 915f5d32b02..6e74d8fa9f9 100644 --- a/components/script/dom/htmldataelement.rs +++ b/components/script/dom/htmldataelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLDataElement { htmlelement: HTMLElement } @@ -43,4 +42,3 @@ impl HTMLDataElement { Node::reflect_node(box element, document, HTMLDataElementBinding::Wrap) } } - diff --git a/components/script/dom/htmldatalistelement.rs b/components/script/dom/htmldatalistelement.rs index 17b1f019ee8..93659612405 100644 --- a/components/script/dom/htmldatalistelement.rs +++ b/components/script/dom/htmldatalistelement.rs @@ -17,7 +17,6 @@ use dom::node::{Node, NodeTypeId, window_from_node}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLDataListElement { htmlelement: HTMLElement } @@ -49,9 +48,9 @@ impl HTMLDataListElement { } } -impl<'a> HTMLDataListElementMethods for &'a HTMLDataListElement { +impl HTMLDataListElementMethods for HTMLDataListElement { // https://html.spec.whatwg.org/multipage/#dom-datalist-options - fn Options(self) -> Root { + fn Options(&self) -> Root { #[derive(JSTraceable, HeapSizeOf)] struct HTMLDataListOptionsFilter; impl CollectionFilter for HTMLDataListOptionsFilter { @@ -65,4 +64,3 @@ impl<'a> HTMLDataListElementMethods for &'a HTMLDataListElement { HTMLCollection::create(window.r(), node, filter) } } - diff --git a/components/script/dom/htmldialogelement.rs b/components/script/dom/htmldialogelement.rs index e3003c25d0f..5754f5af114 100644 --- a/components/script/dom/htmldialogelement.rs +++ b/components/script/dom/htmldialogelement.rs @@ -18,7 +18,6 @@ use util::str::DOMString; use std::borrow::ToOwned; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLDialogElement { htmlelement: HTMLElement, return_value: DOMRefCell, @@ -52,7 +51,7 @@ impl HTMLDialogElement { } } -impl<'a> HTMLDialogElementMethods for &'a HTMLDialogElement { +impl HTMLDialogElementMethods for HTMLDialogElement { // https://html.spec.whatwg.org/multipage/#dom-dialog-open make_bool_getter!(Open); @@ -60,13 +59,13 @@ impl<'a> HTMLDialogElementMethods for &'a HTMLDialogElement { make_bool_setter!(SetOpen, "open"); // https://html.spec.whatwg.org/multipage/#dom-dialog-returnvalue - fn ReturnValue(self) -> DOMString { + fn ReturnValue(&self) -> DOMString { let return_value = self.return_value.borrow(); return_value.clone() } // https://html.spec.whatwg.org/multipage/#dom-dialog-returnvalue - fn SetReturnValue(self, return_value: DOMString) { + fn SetReturnValue(&self, return_value: DOMString) { *self.return_value.borrow_mut() = return_value; } } diff --git a/components/script/dom/htmldirectoryelement.rs b/components/script/dom/htmldirectoryelement.rs index 916868bf753..2b6a90d11a0 100644 --- a/components/script/dom/htmldirectoryelement.rs +++ b/components/script/dom/htmldirectoryelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLDirectoryElement { htmlelement: HTMLElement } @@ -44,4 +43,3 @@ impl HTMLDirectoryElement { Node::reflect_node(box element, document, HTMLDirectoryElementBinding::Wrap) } } - diff --git a/components/script/dom/htmldivelement.rs b/components/script/dom/htmldivelement.rs index 2c2edd0b0d0..d5979f2c16b 100644 --- a/components/script/dom/htmldivelement.rs +++ b/components/script/dom/htmldivelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLDivElement { htmlelement: HTMLElement } @@ -43,4 +42,3 @@ impl HTMLDivElement { Node::reflect_node(box element, document, HTMLDivElementBinding::Wrap) } } - diff --git a/components/script/dom/htmldlistelement.rs b/components/script/dom/htmldlistelement.rs index a582ebd75ce..d9b616dd15f 100644 --- a/components/script/dom/htmldlistelement.rs +++ b/components/script/dom/htmldlistelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLDListElement { htmlelement: HTMLElement } @@ -42,4 +41,3 @@ impl HTMLDListElement { Node::reflect_node(box element, document, HTMLDListElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlelement.rs b/components/script/dom/htmlelement.rs index 473cfa07db9..80e6f93d36e 100644 --- a/components/script/dom/htmlelement.rs +++ b/components/script/dom/htmlelement.rs @@ -3,7 +3,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; -use dom::attr::AttrHelpers; use dom::attr::AttrValue; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::HTMLElementBinding; @@ -18,16 +17,15 @@ use dom::bindings::error::ErrorResult; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::utils::Reflectable; use dom::cssstyledeclaration::{CSSStyleDeclaration, CSSModificationAccess}; -use dom::document::{Document, DocumentHelpers}; +use dom::document::Document; use dom::domstringmap::DOMStringMap; -use dom::element::{Element, ElementTypeId, ActivationElementHelpers, AttributeHandlers}; -use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; +use dom::element::{Element, ElementTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlinputelement::HTMLInputElement; use dom::htmlmediaelement::HTMLMediaElementTypeId; use dom::htmltablecellelement::HTMLTableCellElementTypeId; -use dom::node::{Node, NodeHelpers, NodeTypeId, document_from_node, window_from_node, SEQUENTIALLY_FOCUSABLE}; +use dom::node::{Node, NodeTypeId, document_from_node, window_from_node, SEQUENTIALLY_FOCUSABLE}; use dom::virtualmethods::VirtualMethods; -use dom::window::WindowHelpers; use msg::constellation_msg::FocusType; use util::str::DOMString; @@ -40,7 +38,6 @@ use std::intrinsics; use std::rc::Rc; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLElement { element: Element, style_decl: MutNullableHeap>, @@ -80,20 +77,13 @@ impl HTMLElement { let element = HTMLElement::new_inherited(HTMLElementTypeId::HTMLElement, localName, prefix, document); Node::reflect_node(box element, document, HTMLElementBinding::Wrap) } -} -trait PrivateHTMLElementHelpers { - fn is_body_or_frameset(self) -> bool; - fn update_sequentially_focusable_status(self); -} - -impl<'a> PrivateHTMLElementHelpers for &'a HTMLElement { - fn is_body_or_frameset(self) -> bool { + fn is_body_or_frameset(&self) -> bool { let eventtarget = EventTargetCast::from_ref(self); eventtarget.is_htmlbodyelement() || eventtarget.is_htmlframesetelement() } - fn update_sequentially_focusable_status(self) { + fn update_sequentially_focusable_status(&self) { let element = ElementCast::from_ref(self); let node = NodeCast::from_ref(self); if element.has_attribute(&atom!("tabindex")) { @@ -131,34 +121,40 @@ impl<'a> PrivateHTMLElementHelpers for &'a HTMLElement { } } -impl<'a> HTMLElementMethods for &'a HTMLElement { +impl HTMLElementMethods for HTMLElement { // https://html.spec.whatwg.org/multipage/#the-style-attribute - fn Style(self) -> Root { + fn Style(&self) -> Root { self.style_decl.or_init(|| { let global = window_from_node(self); CSSStyleDeclaration::new(global.r(), ElementCast::from_ref(self), None, CSSModificationAccess::ReadWrite) }) } + // https://html.spec.whatwg.org/multipage/#attr-title make_getter!(Title); + // https://html.spec.whatwg.org/multipage/#attr-title make_setter!(SetTitle, "title"); + // https://html.spec.whatwg.org/multipage/#attr-lang make_getter!(Lang); + // https://html.spec.whatwg.org/multipage/#attr-lang make_setter!(SetLang, "lang"); // https://html.spec.whatwg.org/multipage/#dom-hidden make_bool_getter!(Hidden); + // https://html.spec.whatwg.org/multipage/#dom-hidden make_bool_setter!(SetHidden, "hidden"); + // https://html.spec.whatwg.org/multipage/#globaleventhandlers global_event_handlers!(NoOnload); // https://html.spec.whatwg.org/multipage/#dom-dataset - fn Dataset(self) -> Root { + fn Dataset(&self) -> Root { self.dataset.or_init(|| DOMStringMap::new(self)) } // https://html.spec.whatwg.org/multipage/#handler-onload - fn GetOnload(self) -> Option> { + fn GetOnload(&self) -> Option> { if self.is_body_or_frameset() { let win = window_from_node(self); win.r().GetOnload() @@ -169,7 +165,7 @@ impl<'a> HTMLElementMethods for &'a HTMLElement { } // https://html.spec.whatwg.org/multipage/#handler-onload - fn SetOnload(self, listener: Option>) { + fn SetOnload(&self, listener: Option>) { if self.is_body_or_frameset() { let win = window_from_node(self); win.r().SetOnload(listener) @@ -180,7 +176,7 @@ impl<'a> HTMLElementMethods for &'a HTMLElement { } // https://html.spec.whatwg.org/multipage/#dom-click - fn Click(self) { + fn Click(&self) { let maybe_input: Option<&HTMLInputElement> = HTMLInputElementCast::to_ref(self); if let Some(i) = maybe_input { if i.Disabled() { @@ -193,7 +189,7 @@ impl<'a> HTMLElementMethods for &'a HTMLElement { } // https://html.spec.whatwg.org/multipage/#dom-focus - fn Focus(self) { + fn Focus(&self) { // TODO: Mark the element as locked for focus and run the focusing steps. // https://html.spec.whatwg.org/multipage/#focusing-steps let element = ElementCast::from_ref(self); @@ -205,7 +201,7 @@ impl<'a> HTMLElementMethods for &'a HTMLElement { } // https://html.spec.whatwg.org/multipage/#dom-blur - fn Blur(self) { + fn Blur(&self) { // TODO: Run the unfocusing steps. let node = NodeCast::from_ref(self); if !node.get_focus_state() { @@ -219,7 +215,7 @@ impl<'a> HTMLElementMethods for &'a HTMLElement { } // https://drafts.csswg.org/cssom-view/#extensions-to-the-htmlelement-interface - fn GetOffsetParent(self) -> Option> { + fn GetOffsetParent(&self) -> Option> { if self.is_htmlbodyelement() || self.is_htmlhtmlelement() { return None; } @@ -232,7 +228,7 @@ impl<'a> HTMLElementMethods for &'a HTMLElement { } // https://drafts.csswg.org/cssom-view/#extensions-to-the-htmlelement-interface - fn OffsetTop(self) -> i32 { + fn OffsetTop(&self) -> i32 { if self.is_htmlbodyelement() { return 0; } @@ -245,7 +241,7 @@ impl<'a> HTMLElementMethods for &'a HTMLElement { } // https://drafts.csswg.org/cssom-view/#extensions-to-the-htmlelement-interface - fn OffsetLeft(self) -> i32 { + fn OffsetLeft(&self) -> i32 { if self.is_htmlbodyelement() { return 0; } @@ -258,7 +254,7 @@ impl<'a> HTMLElementMethods for &'a HTMLElement { } // https://drafts.csswg.org/cssom-view/#extensions-to-the-htmlelement-interface - fn OffsetWidth(self) -> i32 { + fn OffsetWidth(&self) -> i32 { let node = NodeCast::from_ref(self); let window = window_from_node(self); let (_, rect) = window.offset_parent_query(node.to_trusted_node_address()); @@ -267,7 +263,7 @@ impl<'a> HTMLElementMethods for &'a HTMLElement { } // https://drafts.csswg.org/cssom-view/#extensions-to-the-htmlelement-interface - fn OffsetHeight(self) -> i32 { + fn OffsetHeight(&self) -> i32 { let node = NodeCast::from_ref(self); let window = window_from_node(self); let (_, rect) = window.offset_parent_query(node.to_trusted_node_address()); @@ -277,11 +273,6 @@ impl<'a> HTMLElementMethods for &'a HTMLElement { } // https://html.spec.whatwg.org/#attr-data-* -pub trait HTMLElementCustomAttributeHelpers { - fn set_custom_attr(self, name: DOMString, value: DOMString) -> ErrorResult; - fn get_custom_attr(self, name: DOMString) -> Option; - fn delete_custom_attr(self, name: DOMString); -} fn to_snake_case(name: DOMString) -> DOMString { let mut attr_name = "data-".to_owned(); @@ -296,8 +287,8 @@ fn to_snake_case(name: DOMString) -> DOMString { attr_name } -impl<'a> HTMLElementCustomAttributeHelpers for &'a HTMLElement { - fn set_custom_attr(self, name: DOMString, value: DOMString) -> ErrorResult { +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') { @@ -307,7 +298,7 @@ impl<'a> HTMLElementCustomAttributeHelpers for &'a HTMLElement { element.set_custom_attribute(to_snake_case(name), value) } - fn get_custom_attr(self, local_name: DOMString) -> Option { + pub fn get_custom_attr(&self, local_name: DOMString) -> Option { let element = ElementCast::from_ref(self); let local_name = Atom::from_slice(&to_snake_case(local_name)); element.get_attribute(&ns!(""), &local_name).map(|attr| { @@ -315,16 +306,16 @@ impl<'a> HTMLElementCustomAttributeHelpers for &'a HTMLElement { }) } - fn delete_custom_attr(self, local_name: DOMString) { + pub fn delete_custom_attr(&self, local_name: DOMString) { let element = ElementCast::from_ref(self); let local_name = Atom::from_slice(&to_snake_case(local_name)); element.remove_attribute(&ns!(""), &local_name); } } -impl<'a> VirtualMethods for &'a HTMLElement { +impl VirtualMethods for HTMLElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let element: &&Element = ElementCast::from_borrowed_ref(self); + let element: &Element = ElementCast::from_ref(self); Some(element as &VirtualMethods) } @@ -348,11 +339,11 @@ impl<'a> VirtualMethods for &'a HTMLElement { let name = attr.local_name(); if name.starts_with("on") { - let window = window_from_node(*self); + let window = window_from_node(self); let (cx, url, reflector) = (window.r().get_cx(), window.r().get_url(), window.r().reflector().get_jsobject()); - let evtarget = EventTargetCast::from_ref(*self); + let evtarget = EventTargetCast::from_ref(self); evtarget.set_event_handler_uncompiled(cx, url, reflector, &name[2..], (**attr.value()).to_owned()); diff --git a/components/script/dom/htmlembedelement.rs b/components/script/dom/htmlembedelement.rs index 9855702e2e5..bd741de54fa 100644 --- a/components/script/dom/htmlembedelement.rs +++ b/components/script/dom/htmlembedelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLEmbedElement { htmlelement: HTMLElement } @@ -41,4 +40,3 @@ impl HTMLEmbedElement { Node::reflect_node(box element, document, HTMLEmbedElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlfieldsetelement.rs b/components/script/dom/htmlfieldsetelement.rs index de94e16b192..13ba6c17e76 100644 --- a/components/script/dom/htmlfieldsetelement.rs +++ b/components/script/dom/htmlfieldsetelement.rs @@ -3,26 +3,23 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; -use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding::HTMLFieldSetElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLLegendElementDerived}; use dom::bindings::codegen::InheritTypes::{HTMLFieldSetElementDerived, NodeCast}; use dom::bindings::js::{Root, RootedReference}; use dom::document::Document; -use dom::element::ElementTypeId; -use dom::element::{AttributeHandlers, Element, ElementHelpers}; +use dom::element::{Element, ElementTypeId}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlcollection::{HTMLCollection, CollectionFilter}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; -use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId, window_from_node}; +use dom::node::{Node, NodeTypeId, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use util::str::{DOMString, StaticStringVec}; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLFieldSetElement { htmlelement: HTMLElement } @@ -54,9 +51,9 @@ impl HTMLFieldSetElement { } } -impl<'a> HTMLFieldSetElementMethods for &'a HTMLFieldSetElement { +impl HTMLFieldSetElementMethods for HTMLFieldSetElement { // https://www.whatwg.org/html/#dom-fieldset-elements - fn Elements(self) -> Root { + fn Elements(&self) -> Root { #[derive(JSTraceable, HeapSizeOf)] struct ElementsFilter; impl CollectionFilter for ElementsFilter { @@ -73,7 +70,7 @@ impl<'a> HTMLFieldSetElementMethods for &'a HTMLFieldSetElement { } // https://html.spec.whatwg.org/multipage/#dom-cva-validity - fn Validity(self) -> Root { + fn Validity(&self) -> Root { let window = window_from_node(self); ValidityState::new(window.r()) } @@ -85,9 +82,9 @@ impl<'a> HTMLFieldSetElementMethods for &'a HTMLFieldSetElement { make_bool_setter!(SetDisabled, "disabled"); } -impl<'a> VirtualMethods for &'a HTMLFieldSetElement { +impl VirtualMethods for HTMLFieldSetElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -98,7 +95,7 @@ impl<'a> VirtualMethods for &'a HTMLFieldSetElement { match attr.local_name() { &atom!("disabled") => { - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.set_disabled_state(true); node.set_enabled_state(false); let maybe_legend = node.children() @@ -138,7 +135,7 @@ impl<'a> VirtualMethods for &'a HTMLFieldSetElement { match attr.local_name() { &atom!("disabled") => { - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.set_disabled_state(false); node.set_enabled_state(true); let maybe_legend = node.children() @@ -171,4 +168,3 @@ impl<'a> VirtualMethods for &'a HTMLFieldSetElement { } } } - diff --git a/components/script/dom/htmlfontelement.rs b/components/script/dom/htmlfontelement.rs index 11825e78c06..6b745617b94 100644 --- a/components/script/dom/htmlfontelement.rs +++ b/components/script/dom/htmlfontelement.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use dom::attr::{Attr, AttrHelpers}; +use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLFontElementBinding; use dom::bindings::codegen::Bindings::HTMLFontElementBinding::HTMLFontElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLFontElementDerived}; @@ -19,7 +19,6 @@ use cssparser::RGBA; use std::cell::Cell; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLFontElement { htmlelement: HTMLElement, color: Cell>, @@ -50,14 +49,17 @@ impl HTMLFontElement { } } -impl<'a> HTMLFontElementMethods for &'a HTMLFontElement { +impl HTMLFontElementMethods for HTMLFontElement { + // https://html.spec.whatwg.org/multipage/#dom-font-color make_getter!(Color, "color"); + + // https://html.spec.whatwg.org/multipage/#dom-font-color make_setter!(SetColor, "color"); } -impl<'a> VirtualMethods for &'a HTMLFontElement { +impl VirtualMethods for HTMLFontElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -86,13 +88,9 @@ impl<'a> VirtualMethods for &'a HTMLFontElement { } } -pub trait HTMLFontElementHelpers { - fn get_color(&self) -> Option; -} -impl HTMLFontElementHelpers for HTMLFontElement { - fn get_color(&self) -> Option { +impl HTMLFontElement { + pub fn get_color(&self) -> Option { self.color.get() } } - diff --git a/components/script/dom/htmlformelement.rs b/components/script/dom/htmlformelement.rs index d015c8eb4e1..05f7442bbcc 100644 --- a/components/script/dom/htmlformelement.rs +++ b/components/script/dom/htmlformelement.rs @@ -18,16 +18,14 @@ use dom::bindings::codegen::InheritTypes::HTMLInputElementCast; use dom::bindings::codegen::InheritTypes::{HTMLTextAreaElementCast, NodeCast}; use dom::bindings::global::GlobalRef; use dom::bindings::js::{Root}; -use dom::document::{Document, DocumentHelpers}; -use dom::element::ElementTypeId; -use dom::element::{Element, AttributeHandlers}; -use dom::event::{Event, EventHelpers, EventBubbles, EventCancelable}; +use dom::document::Document; +use dom::element::{Element, ElementTypeId}; +use dom::event::{Event, EventBubbles, EventCancelable}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlbuttonelement::{HTMLButtonElement}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; -use dom::htmlinputelement::{HTMLInputElement, HTMLInputElementHelpers}; -use dom::htmltextareaelement::HTMLTextAreaElementHelpers; -use dom::node::{Node, NodeHelpers, NodeTypeId, document_from_node, window_from_node}; +use dom::htmlinputelement::HTMLInputElement; +use dom::node::{Node, NodeTypeId, document_from_node, window_from_node}; use dom::virtualmethods::VirtualMethods; use hyper::header::ContentType; use hyper::method::Method; @@ -43,7 +41,6 @@ use std::borrow::ToOwned; use std::cell::Cell; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLFormElement { htmlelement: HTMLElement, marked_for_reset: Cell, @@ -82,7 +79,7 @@ impl HTMLFormElement { } } -impl<'a> HTMLFormElementMethods for &'a HTMLFormElement { +impl HTMLFormElementMethods for HTMLFormElement { // https://html.spec.whatwg.org/multipage/#dom-form-acceptcharset make_getter!(AcceptCharset, "accept-charset"); @@ -108,12 +105,12 @@ impl<'a> HTMLFormElementMethods for &'a HTMLFormElement { make_setter!(SetEnctype, "enctype"); // https://html.spec.whatwg.org/multipage/#dom-fs-encoding - fn Encoding(self) -> DOMString { + fn Encoding(&self) -> DOMString { self.Enctype() } // https://html.spec.whatwg.org/multipage/#dom-fs-encoding - fn SetEncoding(self, value: DOMString) { + fn SetEncoding(&self, value: DOMString) { self.SetEnctype(value) } @@ -125,6 +122,8 @@ impl<'a> HTMLFormElementMethods for &'a HTMLFormElement { // https://html.spec.whatwg.org/multipage/#dom-form-name make_getter!(Name); + + // https://html.spec.whatwg.org/multipage/#dom-form-name make_atomic_setter!(SetName, "name"); // https://html.spec.whatwg.org/multipage/#dom-fs-novalidate @@ -140,12 +139,12 @@ impl<'a> HTMLFormElementMethods for &'a HTMLFormElement { make_setter!(SetTarget, "target"); // https://html.spec.whatwg.org/multipage/#the-form-element:concept-form-submit - fn Submit(self) { + fn Submit(&self) { self.submit(SubmittedFrom::FromFormSubmitMethod, FormSubmitter::FormElement(self)); } // https://html.spec.whatwg.org/multipage/#dom-form-reset - fn Reset(self) { + fn Reset(&self) { self.reset(ResetFrom::FromFormResetMethod); } } @@ -162,17 +161,9 @@ pub enum ResetFrom { NotFromFormResetMethod } -pub trait HTMLFormElementHelpers { - // https://html.spec.whatwg.org/multipage/#concept-form-submit - fn submit(self, submit_method_flag: SubmittedFrom, submitter: FormSubmitter); - // https://html.spec.whatwg.org/multipage/#constructing-the-form-data-set - fn get_form_dataset(self, submitter: Option) -> Vec; - // https://html.spec.whatwg.org/multipage/#dom-form-reset - fn reset(self, submit_method_flag: ResetFrom); -} -impl<'a> HTMLFormElementHelpers for &'a HTMLFormElement { - fn submit(self, _submit_method_flag: SubmittedFrom, submitter: FormSubmitter) { +impl HTMLFormElement { + pub fn submit(&self, _submit_method_flag: SubmittedFrom, submitter: FormSubmitter) { // Step 1 let doc = document_from_node(self); let win = window_from_node(self); @@ -236,7 +227,7 @@ impl<'a> HTMLFormElementHelpers for &'a HTMLFormElement { win.r().pipeline(), load_data)).unwrap(); } - fn get_form_dataset<'b>(self, submitter: Option>) -> Vec { + pub fn get_form_dataset<'b>(&self, submitter: Option>) -> Vec { fn clean_crlf(s: &str) -> DOMString { // https://html.spec.whatwg.org/multipage/#constructing-the-form-data-set // Step 4 @@ -363,7 +354,7 @@ impl<'a> HTMLFormElementHelpers for &'a HTMLFormElement { ret } - fn reset(self, _reset_method_flag: ResetFrom) { + pub fn reset(&self, _reset_method_flag: ResetFrom) { // https://html.spec.whatwg.org/multipage/#locked-for-reset if self.marked_for_reset.get() { return; @@ -571,9 +562,9 @@ pub trait FormControl<'a> : Copy + Sized { fn to_element(self) -> &'a Element; } -impl<'a> VirtualMethods for &'a HTMLFormElement { +impl VirtualMethods for HTMLFormElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - Some(HTMLElementCast::from_borrowed_ref(self) as &VirtualMethods) + Some(HTMLElementCast::from_ref(self) as &VirtualMethods) } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { diff --git a/components/script/dom/htmlframeelement.rs b/components/script/dom/htmlframeelement.rs index 7d60ccc6352..30acbd99797 100644 --- a/components/script/dom/htmlframeelement.rs +++ b/components/script/dom/htmlframeelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLFrameElement { htmlelement: HTMLElement } @@ -41,4 +40,3 @@ impl HTMLFrameElement { Node::reflect_node(box element, document, HTMLFrameElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlframesetelement.rs b/components/script/dom/htmlframesetelement.rs index 5a42343f76f..d665efa13ff 100644 --- a/components/script/dom/htmlframesetelement.rs +++ b/components/script/dom/htmlframesetelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLFrameSetElement { htmlelement: HTMLElement } @@ -44,4 +43,3 @@ impl HTMLFrameSetElement { Node::reflect_node(box element, document, HTMLFrameSetElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlheadelement.rs b/components/script/dom/htmlheadelement.rs index 0353ace6436..699821241f1 100644 --- a/components/script/dom/htmlheadelement.rs +++ b/components/script/dom/htmlheadelement.rs @@ -15,7 +15,6 @@ use dom::virtualmethods::VirtualMethods; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLHeadElement { htmlelement: HTMLElement } @@ -46,12 +45,12 @@ impl HTMLHeadElement { } } -impl<'a> VirtualMethods for &'a HTMLHeadElement { +impl VirtualMethods for HTMLHeadElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } fn bind_to_tree(&self, _tree_in_doc: bool) { - load_script(*self); + load_script(self); } } diff --git a/components/script/dom/htmlheadingelement.rs b/components/script/dom/htmlheadingelement.rs index 3b01900688d..f3c8aed9746 100644 --- a/components/script/dom/htmlheadingelement.rs +++ b/components/script/dom/htmlheadingelement.rs @@ -23,7 +23,6 @@ pub enum HeadingLevel { } #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLHeadingElement { htmlelement: HTMLElement, level: HeadingLevel, @@ -58,4 +57,3 @@ impl HTMLHeadingElement { Node::reflect_node(box element, document, HTMLHeadingElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlhrelement.rs b/components/script/dom/htmlhrelement.rs index ffbe53fadb2..0bd8a9a9ffa 100644 --- a/components/script/dom/htmlhrelement.rs +++ b/components/script/dom/htmlhrelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLHRElement { htmlelement: HTMLElement, } @@ -41,4 +40,3 @@ impl HTMLHRElement { Node::reflect_node(box element, document, HTMLHRElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlhtmlelement.rs b/components/script/dom/htmlhtmlelement.rs index 4e5250063a7..94b4e58c696 100644 --- a/components/script/dom/htmlhtmlelement.rs +++ b/components/script/dom/htmlhtmlelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLHtmlElement { htmlelement: HTMLElement } @@ -41,4 +40,3 @@ impl HTMLHtmlElement { Node::reflect_node(box element, document, HTMLHtmlElementBinding::Wrap) } } - diff --git a/components/script/dom/htmliframeelement.rs b/components/script/dom/htmliframeelement.rs index 213db677812..e4665847468 100644 --- a/components/script/dom/htmliframeelement.rs +++ b/components/script/dom/htmliframeelement.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use dom::attr::{Attr, AttrHelpers, AttrHelpersForLayout, AttrValue}; +use dom::attr::{Attr, AttrHelpersForLayout, AttrValue}; use dom::bindings::codegen::Bindings::HTMLIFrameElementBinding; use dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElementMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; @@ -17,22 +17,20 @@ use dom::bindings::js::{Root}; use dom::bindings::utils::Reflectable; use dom::customevent::CustomEvent; use dom::document::Document; -use dom::element::ElementTypeId; -use dom::element::{self, AttributeHandlers}; -use dom::event::EventHelpers; +use dom::element::{ElementTypeId, self}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; -use dom::node::{Node, NodeHelpers, NodeTypeId, window_from_node}; +use dom::node::{Node, NodeTypeId, window_from_node}; use dom::urlhelper::UrlHelper; use dom::virtualmethods::VirtualMethods; -use dom::window::{Window, WindowHelpers}; +use dom::window::Window; use page::IterablePage; use msg::constellation_msg::IFrameSandboxState::{IFrameSandboxed, IFrameUnsandboxed}; use msg::constellation_msg::Msg as ConstellationMsg; use msg::constellation_msg::{PipelineId, SubpageId, ConstellationChan, MozBrowserEvent, NavigationDirection}; use string_cache::Atom; -use util::opts; +use util::prefs; use util::str::DOMString; use js::jsapi::{RootedValue, JSAutoRequest, JSAutoCompartment}; @@ -43,6 +41,10 @@ use std::cell::Cell; use url::{Url, UrlParser}; use util::str::{self, LengthOrPercentageOrAuto}; +pub fn mozbrowser_enabled() -> bool { + prefs::get_pref("dom.mozbrowser.enabled", false) +} + #[derive(HeapSizeOf)] enum SandboxAllowance { AllowNothing = 0x00, @@ -55,7 +57,6 @@ enum SandboxAllowance { } #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLIFrameElement { htmlelement: HTMLElement, subpage_id: Cell>, @@ -71,28 +72,14 @@ impl HTMLIFrameElementDerived for EventTarget { } } -pub trait HTMLIFrameElementHelpers { - fn is_sandboxed(self) -> bool; - fn get_url(self) -> Option; - /// https://www.whatwg.org/html/#process-the-iframe-attributes - fn process_the_iframe_attributes(self); - fn generate_new_subpage_id(self) -> (SubpageId, Option); - fn navigate_child_browsing_context(self, url: Url); - fn dispatch_mozbrowser_event(self, event: MozBrowserEvent); - fn update_subpage_id(self, new_subpage_id: SubpageId); -} -pub trait RawHTMLIFrameElementHelpers { - fn get_width(&self) -> LengthOrPercentageOrAuto; - fn get_height(&self) -> LengthOrPercentageOrAuto; -} -impl<'a> HTMLIFrameElementHelpers for &'a HTMLIFrameElement { - fn is_sandboxed(self) -> bool { +impl HTMLIFrameElement { + pub fn is_sandboxed(&self) -> bool { self.sandbox.get().is_some() } - fn get_url(self) -> Option { + pub fn get_url(&self) -> Option { let element = ElementCast::from_ref(self); element.get_attribute(&ns!(""), &atom!("src")).and_then(|src| { let url = src.r().value(); @@ -106,7 +93,7 @@ impl<'a> HTMLIFrameElementHelpers for &'a HTMLIFrameElement { }) } - fn generate_new_subpage_id(self) -> (SubpageId, Option) { + pub fn generate_new_subpage_id(&self) -> (SubpageId, Option) { let old_subpage_id = self.subpage_id.get(); let win = window_from_node(self); let subpage_id = win.r().get_next_subpage_id(); @@ -114,7 +101,7 @@ impl<'a> HTMLIFrameElementHelpers for &'a HTMLIFrameElement { (subpage_id, old_subpage_id) } - fn navigate_child_browsing_context(self, url: Url) { + pub fn navigate_child_browsing_context(&self, url: Url) { let sandboxed = if self.is_sandboxed() { IFrameSandboxed } else { @@ -134,13 +121,13 @@ impl<'a> HTMLIFrameElementHelpers for &'a HTMLIFrameElement { old_subpage_id, sandboxed)).unwrap(); - if opts::experimental_enabled() { + if mozbrowser_enabled() { // https://developer.mozilla.org/en-US/docs/Web/Events/mozbrowserloadstart self.dispatch_mozbrowser_event(MozBrowserEvent::LoadStart); } } - fn process_the_iframe_attributes(self) { + pub fn process_the_iframe_attributes(&self) { let url = match self.get_url() { Some(url) => url.clone(), None => Url::parse("about:blank").unwrap(), @@ -149,11 +136,11 @@ impl<'a> HTMLIFrameElementHelpers for &'a HTMLIFrameElement { self.navigate_child_browsing_context(url); } - fn dispatch_mozbrowser_event(self, event: MozBrowserEvent) { + pub fn dispatch_mozbrowser_event(&self, event: MozBrowserEvent) { // TODO(gw): Support mozbrowser event types that have detail which is not a string. // See https://developer.mozilla.org/en-US/docs/Web/API/Using_the_Browser_API // for a list of mozbrowser events. - assert!(opts::experimental_enabled()); + assert!(mozbrowser_enabled()); if self.Mozbrowser() { let window = window_from_node(self); @@ -173,14 +160,12 @@ impl<'a> HTMLIFrameElementHelpers for &'a HTMLIFrameElement { } } - fn update_subpage_id(self, new_subpage_id: SubpageId) { + pub fn update_subpage_id(&self, new_subpage_id: SubpageId) { self.subpage_id.set(Some(new_subpage_id)); } -} -impl RawHTMLIFrameElementHelpers for HTMLIFrameElement { #[allow(unsafe_code)] - fn get_width(&self) -> LengthOrPercentageOrAuto { + pub fn get_width(&self) -> LengthOrPercentageOrAuto { unsafe { element::get_attr_for_layout(ElementCast::from_ref(&*self), &ns!(""), @@ -191,7 +176,7 @@ impl RawHTMLIFrameElementHelpers for HTMLIFrameElement { } #[allow(unsafe_code)] - fn get_height(&self) -> LengthOrPercentageOrAuto { + pub fn get_height(&self) -> LengthOrPercentageOrAuto { unsafe { element::get_attr_for_layout(ElementCast::from_ref(&*self), &ns!(""), @@ -200,9 +185,7 @@ impl RawHTMLIFrameElementHelpers for HTMLIFrameElement { }).unwrap_or(LengthOrPercentageOrAuto::Auto) } } -} -impl HTMLIFrameElement { fn new_inherited(localName: DOMString, prefix: Option, document: &Document) -> HTMLIFrameElement { @@ -255,33 +238,33 @@ pub fn Navigate(iframe: &HTMLIFrameElement, direction: NavigationDirection) -> F } } -impl<'a> HTMLIFrameElementMethods for &'a HTMLIFrameElement { +impl HTMLIFrameElementMethods for HTMLIFrameElement { // https://html.spec.whatwg.org/multipage/#dom-iframe-src - fn Src(self) -> DOMString { + fn Src(&self) -> DOMString { let element = ElementCast::from_ref(self); element.get_string_attribute(&atom!("src")) } // https://html.spec.whatwg.org/multipage/#dom-iframe-src - fn SetSrc(self, src: DOMString) { + fn SetSrc(&self, src: DOMString) { let element = ElementCast::from_ref(self); element.set_url_attribute(&atom!("src"), src) } // https://html.spec.whatwg.org/multipage/#dom-iframe-sandbox - fn Sandbox(self) -> DOMString { + fn Sandbox(&self) -> DOMString { let element = ElementCast::from_ref(self); element.get_string_attribute(&atom!("sandbox")) } // https://html.spec.whatwg.org/multipage/#dom-iframe-sandbox - fn SetSandbox(self, sandbox: DOMString) { + fn SetSandbox(&self, sandbox: DOMString) { let element = ElementCast::from_ref(self); element.set_tokenlist_attribute(&atom!("sandbox"), sandbox); } // https://html.spec.whatwg.org/multipage/#dom-iframe-contentwindow - fn GetContentWindow(self) -> Option> { + fn GetContentWindow(&self) -> Option> { self.subpage_id.get().and_then(|subpage_id| { let window = window_from_node(self); let window = window.r(); @@ -294,7 +277,7 @@ impl<'a> HTMLIFrameElementMethods for &'a HTMLIFrameElement { } // https://html.spec.whatwg.org/multipage/#dom-iframe-contentdocument - fn GetContentDocument(self) -> Option> { + fn GetContentDocument(&self) -> Option> { self.GetContentWindow().and_then(|window| { let self_url = match self.get_url() { Some(self_url) => self_url, @@ -318,8 +301,8 @@ impl<'a> HTMLIFrameElementMethods for &'a HTMLIFrameElement { // exposing these APIs. See https://github.com/servo/servo/issues/5264. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-mozbrowser - fn Mozbrowser(self) -> bool { - if opts::experimental_enabled() { + fn Mozbrowser(&self) -> bool { + if mozbrowser_enabled() { let element = ElementCast::from_ref(self); element.has_attribute(&Atom::from_slice("mozbrowser")) } else { @@ -328,8 +311,8 @@ impl<'a> HTMLIFrameElementMethods for &'a HTMLIFrameElement { } // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-mozbrowser - fn SetMozbrowser(self, value: bool) -> ErrorResult { - if opts::experimental_enabled() { + fn SetMozbrowser(&self, value: bool) -> ErrorResult { + if mozbrowser_enabled() { let element = ElementCast::from_ref(self); element.set_bool_attribute(&Atom::from_slice("mozbrowser"), value); } @@ -337,37 +320,39 @@ impl<'a> HTMLIFrameElementMethods for &'a HTMLIFrameElement { } // https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/goBack - fn GoBack(self) -> Fallible<()> { + fn GoBack(&self) -> Fallible<()> { Navigate(self, NavigationDirection::Back) } // https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/goForward - fn GoForward(self) -> Fallible<()> { + fn GoForward(&self) -> Fallible<()> { Navigate(self, NavigationDirection::Forward) } // https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/reload - fn Reload(self, _hardReload: bool) -> Fallible<()> { + fn Reload(&self, _hardReload: bool) -> Fallible<()> { Err(NotSupported) } // https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/stop - fn Stop(self) -> Fallible<()> { + fn Stop(&self) -> Fallible<()> { Err(NotSupported) } + // https://html.spec.whatwg.org/multipage/#dom-dim-width make_getter!(Width); - + // https://html.spec.whatwg.org/multipage/#dom-dim-width make_setter!(SetWidth, "width"); + // https://html.spec.whatwg.org/multipage/#dom-dim-height make_getter!(Height); - + // https://html.spec.whatwg.org/multipage/#dom-dim-height make_setter!(SetHeight, "height"); } -impl<'a> VirtualMethods for &'a HTMLIFrameElement { +impl VirtualMethods for HTMLIFrameElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -395,7 +380,7 @@ impl<'a> VirtualMethods for &'a HTMLIFrameElement { self.sandbox.set(Some(modes)); } &atom!("src") => { - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); if node.is_in_doc() { self.process_the_iframe_attributes() } @@ -440,7 +425,7 @@ impl<'a> VirtualMethods for &'a HTMLIFrameElement { // https://html.spec.whatwg.org/multipage/#a-browsing-context-is-discarded match (self.containing_page_pipeline_id(), self.subpage_id()) { (Some(containing_pipeline_id), Some(subpage_id)) => { - let window = window_from_node(*self); + let window = window_from_node(self); let window = window.r(); let ConstellationChan(ref chan) = window.constellation_chan(); diff --git a/components/script/dom/htmlimageelement.rs b/components/script/dom/htmlimageelement.rs index 88a73907324..bfd6ca2fdd8 100644 --- a/components/script/dom/htmlimageelement.rs +++ b/components/script/dom/htmlimageelement.rs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; -use dom::attr::{AttrHelpers, AttrValue}; +use dom::attr::AttrValue; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLImageElementBinding; use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods; @@ -14,15 +14,14 @@ use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{LayoutJS, Root}; use dom::bindings::refcounted::Trusted; -use dom::document::{Document, DocumentHelpers}; -use dom::element::AttributeHandlers; +use dom::document::Document; use dom::element::ElementTypeId; -use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers}; +use dom::event::{Event, EventBubbles, EventCancelable}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; -use dom::node::{document_from_node, Node, NodeTypeId, NodeHelpers, NodeDamage, window_from_node}; +use dom::node::{document_from_node, Node, NodeTypeId, NodeDamage, window_from_node}; use dom::virtualmethods::VirtualMethods; -use dom::window::WindowHelpers; +use script_task::ScriptTaskEventCategory::UpdateReplacedElement; use script_task::{Runnable, ScriptChan, CommonScriptMsg}; use string_cache::Atom; use util::str::DOMString; @@ -37,7 +36,6 @@ use std::borrow::ToOwned; use std::sync::Arc; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLImageElement { htmlelement: HTMLElement, url: DOMRefCell>, @@ -52,19 +50,13 @@ impl HTMLImageElementDerived for EventTarget { } } -pub trait HTMLImageElementHelpers { - fn get_url(&self) -> Option; -} -impl<'a> HTMLImageElementHelpers for &'a HTMLImageElement { - fn get_url(&self) -> Option{ +impl HTMLImageElement { + pub fn get_url(&self) -> Option{ self.url.borrow().clone() } } -trait PrivateHTMLImageElementHelpers { - fn update_image(self, value: Option<(DOMString, &Url)>); -} struct ImageResponseHandlerRunnable { element: Trusted, @@ -113,10 +105,10 @@ impl Runnable for ImageResponseHandlerRunnable { } } -impl<'a> PrivateHTMLImageElementHelpers for &'a HTMLImageElement { +impl HTMLImageElement { /// Makes the local `image` member match the status of the `src` attribute and starts /// prefetching the image. This method must be called after `src` is changed. - fn update_image(self, value: Option<(DOMString, &Url)>) { + fn update_image(&self, value: Option<(DOMString, &Url)>) { let node = NodeCast::from_ref(self); let document = node.owner_doc(); let window = document.r().window(); @@ -140,7 +132,7 @@ impl<'a> PrivateHTMLImageElementHelpers for &'a HTMLImageElement { // Return the image via a message to the script task, which marks the element // as dirty and triggers a reflow. let image_response = message.to().unwrap(); - script_chan.send(CommonScriptMsg::RunnableMsg( + script_chan.send(CommonScriptMsg::RunnableMsg(UpdateReplacedElement, box ImageResponseHandlerRunnable::new( trusted_node.clone(), image_response))).unwrap(); }); @@ -151,9 +143,7 @@ impl<'a> PrivateHTMLImageElementHelpers for &'a HTMLImageElement { } } } -} -impl HTMLImageElement { fn new_inherited(localName: DOMString, prefix: Option, document: &Document) -> HTMLImageElement { HTMLImageElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLImageElement, localName, prefix, document), @@ -206,55 +196,59 @@ impl LayoutHTMLImageElementHelpers for LayoutJS { } } -impl<'a> HTMLImageElementMethods for &'a HTMLImageElement { +impl HTMLImageElementMethods for HTMLImageElement { + // https://html.spec.whatwg.org/multipage/#dom-img-alt make_getter!(Alt); - + // https://html.spec.whatwg.org/multipage/#dom-img-alt make_setter!(SetAlt, "alt"); + // https://html.spec.whatwg.org/multipage/#dom-img-src make_url_getter!(Src); - + // https://html.spec.whatwg.org/multipage/#dom-img-src make_setter!(SetSrc, "src"); + // https://html.spec.whatwg.org/multipage/#dom-img-usemap make_getter!(UseMap); - + // https://html.spec.whatwg.org/multipage/#dom-img-usemap make_setter!(SetUseMap, "usemap"); + // https://html.spec.whatwg.org/multipage/#dom-img-ismap make_bool_getter!(IsMap); // https://html.spec.whatwg.org/multipage/#dom-img-ismap - fn SetIsMap(self, is_map: bool) { + fn SetIsMap(&self, is_map: bool) { let element = ElementCast::from_ref(self); element.set_string_attribute(&atom!("ismap"), is_map.to_string()) } // https://html.spec.whatwg.org/multipage/#dom-img-width - fn Width(self) -> u32 { + fn Width(&self) -> u32 { let node = NodeCast::from_ref(self); let rect = node.get_bounding_content_box(); rect.size.width.to_px() as u32 } // https://html.spec.whatwg.org/multipage/#dom-img-width - fn SetWidth(self, width: u32) { + fn SetWidth(&self, width: u32) { let elem = ElementCast::from_ref(self); elem.set_uint_attribute(&atom!("width"), width) } // https://html.spec.whatwg.org/multipage/#dom-img-height - fn Height(self) -> u32 { + fn Height(&self) -> u32 { let node = NodeCast::from_ref(self); let rect = node.get_bounding_content_box(); rect.size.height.to_px() as u32 } // https://html.spec.whatwg.org/multipage/#dom-img-height - fn SetHeight(self, height: u32) { + fn SetHeight(&self, height: u32) { let elem = ElementCast::from_ref(self); elem.set_uint_attribute(&atom!("height"), height) } // https://html.spec.whatwg.org/multipage/#dom-img-naturalwidth - fn NaturalWidth(self) -> u32 { + fn NaturalWidth(&self) -> u32 { let image = self.image.borrow(); match *image { @@ -264,7 +258,7 @@ impl<'a> HTMLImageElementMethods for &'a HTMLImageElement { } // https://html.spec.whatwg.org/multipage/#dom-img-naturalheight - fn NaturalHeight(self) -> u32 { + fn NaturalHeight(&self) -> u32 { let image = self.image.borrow(); match *image { @@ -274,39 +268,51 @@ impl<'a> HTMLImageElementMethods for &'a HTMLImageElement { } // https://html.spec.whatwg.org/multipage/#dom-img-complete - fn Complete(self) -> bool { + fn Complete(&self) -> bool { let image = self.image.borrow(); image.is_some() } - // https://html.spec.whatwg.org/#dom-img-name + // https://html.spec.whatwg.org/multipage/#dom-img-name make_getter!(Name); + + // https://html.spec.whatwg.org/multipage/#dom-img-name make_atomic_setter!(SetName, "name"); + // https://html.spec.whatwg.org/multipage/#dom-img-align make_getter!(Align); + // https://html.spec.whatwg.org/multipage/#dom-img-align make_setter!(SetAlign, "align"); + // https://html.spec.whatwg.org/multipage/#dom-img-hspace make_uint_getter!(Hspace); + // https://html.spec.whatwg.org/multipage/#dom-img-hspace make_uint_setter!(SetHspace, "hspace"); + // https://html.spec.whatwg.org/multipage/#dom-img-vspace make_uint_getter!(Vspace); + // https://html.spec.whatwg.org/multipage/#dom-img-vspace make_uint_setter!(SetVspace, "vspace"); + // https://html.spec.whatwg.org/multipage/#dom-img-longdesc make_getter!(LongDesc); + // https://html.spec.whatwg.org/multipage/#dom-img-longdesc make_setter!(SetLongDesc, "longdesc"); + // https://html.spec.whatwg.org/multipage/#dom-img-border make_getter!(Border); + // https://html.spec.whatwg.org/multipage/#dom-img-border make_setter!(SetBorder, "border"); } -impl<'a> VirtualMethods for &'a HTMLImageElement { +impl VirtualMethods for HTMLImageElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -317,7 +323,7 @@ impl<'a> VirtualMethods for &'a HTMLImageElement { match attr.local_name() { &atom!("src") => { - let window = window_from_node(*self); + let window = window_from_node(self); let url = window.r().get_url(); self.update_image(Some(((**attr.value()).to_owned(), &url))); }, diff --git a/components/script/dom/htmlinputelement.rs b/components/script/dom/htmlinputelement.rs index 1985c905220..9204e20ab22 100644 --- a/components/script/dom/htmlinputelement.rs +++ b/components/script/dom/htmlinputelement.rs @@ -3,7 +3,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::activation::Activatable; -use dom::attr::AttrHelpers; use dom::attr::{Attr, AttrValue}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; @@ -16,20 +15,17 @@ use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast, HTMLInp use dom::bindings::codegen::InheritTypes::{HTMLInputElementDerived, HTMLFieldSetElementDerived, EventTargetCast}; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, LayoutJS, Root, RootedReference}; -use dom::document::{Document, DocumentHelpers}; -use dom::element::ElementTypeId; -use dom::element::{AttributeHandlers, Element}; -use dom::element::{RawLayoutElementHelpers, ActivationElementHelpers}; -use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers}; +use dom::document::Document; +use dom::element::{Element, ElementTypeId, RawLayoutElementHelpers}; +use dom::event::{Event, EventBubbles, EventCancelable}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; -use dom::htmlformelement::{FormSubmitter, FormControl, HTMLFormElement, HTMLFormElementHelpers}; +use dom::htmlformelement::{FormSubmitter, FormControl, HTMLFormElement}; use dom::htmlformelement::{SubmittedFrom, ResetFrom}; use dom::keyboardevent::KeyboardEvent; -use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeDamage, NodeTypeId}; +use dom::node::{Node, NodeDamage, NodeTypeId}; use dom::node::{document_from_node, window_from_node}; use dom::virtualmethods::VirtualMethods; -use dom::window::WindowHelpers; use msg::constellation_msg::ConstellationChan; use textinput::KeyReaction::{TriggerDefaultAction, DispatchInput, Nothing}; use textinput::Lines::Single; @@ -60,7 +56,6 @@ enum InputType { } #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLInputElement { htmlelement: HTMLElement, input_type: Cell, @@ -221,7 +216,7 @@ impl RawLayoutHTMLInputElementHelpers for HTMLInputElement { } } -impl<'a> HTMLInputElementMethods for &'a HTMLInputElement { +impl HTMLInputElementMethods for HTMLInputElement { // https://www.whatwg.org/html/#dom-fe-disabled make_bool_getter!(Disabled); @@ -235,12 +230,12 @@ impl<'a> HTMLInputElementMethods for &'a HTMLInputElement { make_bool_setter!(SetDefaultChecked, "checked"); // https://html.spec.whatwg.org/multipage/#dom-input-checked - fn Checked(self) -> bool { + fn Checked(&self) -> bool { self.checked.get() } // https://html.spec.whatwg.org/multipage/#dom-input-checked - fn SetChecked(self, checked: bool) { + fn SetChecked(&self, checked: bool) { self.update_checked_state(checked, true); } @@ -252,6 +247,8 @@ impl<'a> HTMLInputElementMethods for &'a HTMLInputElement { // https://html.spec.whatwg.org/multipage/#dom-input-size make_uint_getter!(Size, "size", DEFAULT_INPUT_SIZE); + + // https://html.spec.whatwg.org/multipage/#dom-input-size make_limited_uint_setter!(SetSize, "size", DEFAULT_INPUT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-input-type @@ -267,12 +264,12 @@ impl<'a> HTMLInputElementMethods for &'a HTMLInputElement { make_setter!(SetType, "type"); // https://html.spec.whatwg.org/multipage/#dom-input-value - fn Value(self) -> DOMString { + fn Value(&self) -> DOMString { self.textinput.borrow().get_content() } // https://html.spec.whatwg.org/multipage/#dom-input-value - fn SetValue(self, value: DOMString) { + fn SetValue(&self, value: DOMString) { self.textinput.borrow_mut().set_content(value); self.value_changed.set(true); self.force_relayout(); @@ -322,26 +319,16 @@ impl<'a> HTMLInputElementMethods for &'a HTMLInputElement { make_setter!(SetFormTarget, "formtarget"); // https://html.spec.whatwg.org/multipage/#dom-input-indeterminate - fn Indeterminate(self) -> bool { + fn Indeterminate(&self) -> bool { self.indeterminate.get() } // https://html.spec.whatwg.org/multipage/#dom-input-indeterminate - fn SetIndeterminate(self, val: bool) { + fn SetIndeterminate(&self, val: bool) { self.indeterminate.set(val) } } -pub trait HTMLInputElementHelpers { - fn force_relayout(self); - fn radio_group_updated(self, group: Option<&str>); - fn get_radio_group_name(self) -> Option; - fn update_checked_state(self, checked: bool, dirty: bool); - fn get_size(self) -> u32; - fn get_indeterminate_state(self) -> bool; - fn mutable(self) -> bool; - fn reset(self); -} #[allow(unsafe_code)] fn broadcast_radio_checked(broadcaster: &HTMLInputElement, group: Option<&str>) { @@ -385,27 +372,27 @@ fn in_same_group<'a,'b>(other: &'a HTMLInputElement, } } -impl<'a> HTMLInputElementHelpers for &'a HTMLInputElement { - fn force_relayout(self) { +impl HTMLInputElement { + pub fn force_relayout(&self) { let doc = document_from_node(self); let node = NodeCast::from_ref(self); doc.r().content_changed(node, NodeDamage::OtherNodeDamage) } - fn radio_group_updated(self, group: Option<&str>) { + pub fn radio_group_updated(&self, group: Option<&str>) { if self.Checked() { broadcast_radio_checked(self, group); } } - fn get_radio_group_name(self) -> Option { + pub fn get_radio_group_name(&self) -> Option { //TODO: determine form owner let elem = ElementCast::from_ref(self); elem.get_attribute(&ns!(""), &atom!("name")) .map(|name| name.r().Value()) } - fn update_checked_state(self, checked: bool, dirty: bool) { + pub fn update_checked_state(&self, checked: bool, dirty: bool) { self.checked.set(checked); if dirty { @@ -423,16 +410,16 @@ impl<'a> HTMLInputElementHelpers for &'a HTMLInputElement { //TODO: dispatch change event } - fn get_size(self) -> u32 { + pub fn get_size(&self) -> u32 { self.size.get() } - fn get_indeterminate_state(self) -> bool { + pub fn get_indeterminate_state(&self) -> bool { self.indeterminate.get() } // https://html.spec.whatwg.org/multipage/#concept-fe-mutable - fn mutable(self) -> bool { + pub fn mutable(&self) -> bool { // https://html.spec.whatwg.org/multipage/#the-input-element:concept-fe-mutable // https://html.spec.whatwg.org/multipage/#the-readonly-attribute:concept-fe-mutable let node = NodeCast::from_ref(self); @@ -440,7 +427,7 @@ impl<'a> HTMLInputElementHelpers for &'a HTMLInputElement { } // https://html.spec.whatwg.org/multipage/#the-input-element:concept-form-reset-control - fn reset(self) { + pub fn reset(&self) { match self.input_type.get() { InputType::InputRadio | InputType::InputCheckbox => { self.update_checked_state(self.DefaultChecked(), false); @@ -456,9 +443,9 @@ impl<'a> HTMLInputElementHelpers for &'a HTMLInputElement { } } -impl<'a> VirtualMethods for &'a HTMLInputElement { +impl VirtualMethods for HTMLInputElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -469,7 +456,7 @@ impl<'a> VirtualMethods for &'a HTMLInputElement { match attr.local_name() { &atom!("disabled") => { - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.set_disabled_state(true); node.set_enabled_state(false); } @@ -532,7 +519,7 @@ impl<'a> VirtualMethods for &'a HTMLInputElement { match attr.local_name() { &atom!("disabled") => { - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.set_disabled_state(false); node.set_enabled_state(true); node.check_ancestors_disabled_state_for_form_control(); @@ -548,7 +535,7 @@ impl<'a> VirtualMethods for &'a HTMLInputElement { } &atom!("type") => { if self.input_type.get() == InputType::InputRadio { - broadcast_radio_checked(*self, + broadcast_radio_checked(self, self.get_radio_group_name() .as_ref() .map(|group| &**group)); @@ -584,7 +571,7 @@ impl<'a> VirtualMethods for &'a HTMLInputElement { s.bind_to_tree(tree_in_doc); } - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.check_ancestors_disabled_state_for_form_control(); } @@ -593,7 +580,7 @@ impl<'a> VirtualMethods for &'a HTMLInputElement { s.unbind_from_tree(tree_in_doc); } - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); if node.ancestors().any(|ancestor| ancestor.r().is_htmlfieldsetelement()) { node.check_ancestors_disabled_state_for_form_control(); } else { @@ -617,8 +604,8 @@ impl<'a> VirtualMethods for &'a HTMLInputElement { //TODO: set the editing position for text inputs - let doc = document_from_node(*self); - doc.r().request_focus(ElementCast::from_ref(*self)); + let doc = document_from_node(self); + doc.r().request_focus(ElementCast::from_ref(self)); } else if &*event.Type() == "keydown" && !event.DefaultPrevented() && (self.input_type.get() == InputType::InputText || self.input_type.get() == InputType::InputPassword) { @@ -652,9 +639,9 @@ impl<'a> FormControl<'a> for &'a HTMLInputElement { } } -impl<'a> Activatable for &'a HTMLInputElement { +impl Activatable for HTMLInputElement { fn as_element<'b>(&'b self) -> &'b Element { - ElementCast::from_ref(*self) + ElementCast::from_ref(self) } fn is_instance_activatable(&self) -> bool { @@ -698,7 +685,7 @@ impl<'a> Activatable for &'a HTMLInputElement { InputType::InputRadio => { //TODO: if not in document, use root ancestor instead of document let owner = self.form_owner(); - let doc = document_from_node(*self); + let doc = document_from_node(self); let doc_node = NodeCast::from_ref(doc.r()); let group = self.get_radio_group_name();; @@ -803,19 +790,19 @@ impl<'a> Activatable for &'a HTMLInputElement { // https://html.spec.whatwg.org/multipage/#checkbox-state-(type=checkbox):activation-behavior // https://html.spec.whatwg.org/multipage/#radio-button-state-(type=radio):activation-behavior if self.mutable() { - let win = window_from_node(*self); + let win = window_from_node(self); let event = Event::new(GlobalRef::Window(win.r()), "input".to_owned(), EventBubbles::Bubbles, EventCancelable::NotCancelable); - let target = EventTargetCast::from_ref(*self); + let target = EventTargetCast::from_ref(self); event.r().fire(target); let event = Event::new(GlobalRef::Window(win.r()), "change".to_owned(), EventBubbles::Bubbles, EventCancelable::NotCancelable); - let target = EventTargetCast::from_ref(*self); + let target = EventTargetCast::from_ref(self); event.r().fire(target); } }, @@ -826,7 +813,7 @@ impl<'a> Activatable for &'a HTMLInputElement { // https://html.spec.whatwg.org/multipage/#implicit-submission #[allow(unsafe_code)] fn implicit_submission(&self, ctrlKey: bool, shiftKey: bool, altKey: bool, metaKey: bool) { - let doc = document_from_node(*self); + let doc = document_from_node(self); let node = NodeCast::from_ref(doc.r()); let owner = self.form_owner(); let form = match owner { @@ -834,7 +821,7 @@ impl<'a> Activatable for &'a HTMLInputElement { Some(ref f) => f }; - let elem = ElementCast::from_ref(*self); + let elem = ElementCast::from_ref(self); if elem.click_in_progress() { return; } diff --git a/components/script/dom/htmllabelelement.rs b/components/script/dom/htmllabelelement.rs index 479f85d9660..5e7da7dfbff 100644 --- a/components/script/dom/htmllabelelement.rs +++ b/components/script/dom/htmllabelelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLLabelElement { htmlelement: HTMLElement, } @@ -44,4 +43,3 @@ impl HTMLLabelElement { Node::reflect_node(box element, document, HTMLLabelElementBinding::Wrap) } } - diff --git a/components/script/dom/htmllegendelement.rs b/components/script/dom/htmllegendelement.rs index 0b992092f6f..492615d4421 100644 --- a/components/script/dom/htmllegendelement.rs +++ b/components/script/dom/htmllegendelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLLegendElement { htmlelement: HTMLElement, } @@ -44,4 +43,3 @@ impl HTMLLegendElement { Node::reflect_node(box element, document, HTMLLegendElementBinding::Wrap) } } - diff --git a/components/script/dom/htmllielement.rs b/components/script/dom/htmllielement.rs index ca552e0b405..fd10a954787 100644 --- a/components/script/dom/htmllielement.rs +++ b/components/script/dom/htmllielement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLLIElement { htmlelement: HTMLElement, } @@ -41,4 +40,3 @@ impl HTMLLIElement { Node::reflect_node(box element, document, HTMLLIElementBinding::Wrap) } } - diff --git a/components/script/dom/htmllinkelement.rs b/components/script/dom/htmllinkelement.rs index 7ae868bae51..b9e3d0e081b 100644 --- a/components/script/dom/htmllinkelement.rs +++ b/components/script/dom/htmllinkelement.rs @@ -4,7 +4,6 @@ use cssparser::Parser as CssParser; use document_loader::LoadType; -use dom::attr::AttrHelpers; use dom::attr::{Attr, AttrValue}; use dom::bindings::codegen::Bindings::HTMLLinkElementBinding; use dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods; @@ -15,16 +14,14 @@ use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::js::{RootedReference}; use dom::bindings::refcounted::Trusted; -use dom::document::{Document, DocumentHelpers}; +use dom::document::Document; use dom::domtokenlist::DOMTokenList; -use dom::element::ElementTypeId; -use dom::element::{AttributeHandlers, Element}; -use dom::event::{EventBubbles, EventCancelable, Event, EventHelpers}; +use dom::element::{Element, ElementTypeId}; +use dom::event::{EventBubbles, EventCancelable, Event}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; -use dom::node::{Node, NodeHelpers, NodeTypeId, window_from_node}; +use dom::node::{Node, NodeTypeId, window_from_node}; use dom::virtualmethods::VirtualMethods; -use dom::window::WindowHelpers; use layout_interface::{LayoutChan, Msg}; use msg::constellation_msg::ConstellationChan; use msg::constellation_msg::Msg as ConstellationMsg; @@ -39,7 +36,6 @@ use string_cache::Atom; use url::UrlParser; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLLinkElement { htmlelement: HTMLElement, rel_list: MutNullableHeap>, @@ -101,9 +97,9 @@ fn is_favicon(value: &Option) -> bool { } } -impl<'a> VirtualMethods for &'a HTMLLinkElement { +impl VirtualMethods for HTMLLinkElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -112,12 +108,12 @@ impl<'a> VirtualMethods for &'a HTMLLinkElement { s.after_set_attr(attr); } - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); if !node.is_in_doc() { return; } - let element = ElementCast::from_ref(*self); + let element = ElementCast::from_ref(self); let rel = get_attr(element, &atom!("rel")); match (rel, attr.local_name()) { @@ -150,7 +146,7 @@ impl<'a> VirtualMethods for &'a HTMLLinkElement { } if tree_in_doc { - let element = ElementCast::from_ref(*self); + let element = ElementCast::from_ref(self); let rel = get_attr(element, &atom!("rel")); let href = get_attr(element, &atom!("href")); @@ -168,13 +164,9 @@ impl<'a> VirtualMethods for &'a HTMLLinkElement { } } -trait PrivateHTMLLinkElementHelpers { - fn handle_stylesheet_url(self, href: &str); - fn handle_favicon_url(self, href: &str); -} -impl<'a> PrivateHTMLLinkElementHelpers for &'a HTMLLinkElement { - fn handle_stylesheet_url(self, href: &str) { +impl HTMLLinkElement { + fn handle_stylesheet_url(&self, href: &str) { let window = window_from_node(self); let window = window.r(); match UrlParser::new().base_url(&window.get_url()).parse(href) { @@ -202,7 +194,7 @@ impl<'a> PrivateHTMLLinkElementHelpers for &'a HTMLLinkElement { } } - fn handle_favicon_url(self, href: &str) { + fn handle_favicon_url(&self, href: &str) { let window = window_from_node(self); let window = window.r(); match UrlParser::new().base_url(&window.get_url()).parse(href) { @@ -216,24 +208,39 @@ impl<'a> PrivateHTMLLinkElementHelpers for &'a HTMLLinkElement { } } -impl<'a> HTMLLinkElementMethods for &'a HTMLLinkElement { +impl HTMLLinkElementMethods for HTMLLinkElement { + // https://html.spec.whatwg.org/multipage/#dom-link-href make_url_getter!(Href); + + // https://html.spec.whatwg.org/multipage/#dom-link-href make_setter!(SetHref, "href"); + // https://html.spec.whatwg.org/multipage/#dom-link-rel make_getter!(Rel); + + // https://html.spec.whatwg.org/multipage/#dom-link-rel make_setter!(SetRel, "rel"); + // https://html.spec.whatwg.org/multipage/#dom-link-media make_getter!(Media); + + // https://html.spec.whatwg.org/multipage/#dom-link-media make_setter!(SetMedia, "media"); + // https://html.spec.whatwg.org/multipage/#dom-link-hreflang make_getter!(Hreflang); + + // https://html.spec.whatwg.org/multipage/#dom-link-hreflang make_setter!(SetHreflang, "hreflang"); + // https://html.spec.whatwg.org/multipage/#dom-link-type make_getter!(Type); + + // https://html.spec.whatwg.org/multipage/#dom-link-type make_setter!(SetType, "type"); // https://html.spec.whatwg.org/multipage/#dom-link-rellist - fn RelList(self) -> Root { + fn RelList(&self) -> Root { self.rel_list.or_init(|| { DOMTokenList::new(ElementCast::from_ref(self), &atom!("rel")) }) diff --git a/components/script/dom/htmlmapelement.rs b/components/script/dom/htmlmapelement.rs index e79bd1db4c3..e060a7bf48e 100644 --- a/components/script/dom/htmlmapelement.rs +++ b/components/script/dom/htmlmapelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLMapElement { htmlelement: HTMLElement } @@ -43,4 +42,3 @@ impl HTMLMapElement { Node::reflect_node(box element, document, HTMLMapElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlmediaelement.rs b/components/script/dom/htmlmediaelement.rs index 227f298d96d..bef4dcd93e0 100644 --- a/components/script/dom/htmlmediaelement.rs +++ b/components/script/dom/htmlmediaelement.rs @@ -11,7 +11,6 @@ use dom::node::NodeTypeId; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLMediaElement { htmlelement: HTMLElement, } @@ -54,4 +53,3 @@ impl PartialEq for HTMLMediaElementTypeId { (*self as u8) == (*other as u8) } } - diff --git a/components/script/dom/htmlmetaelement.rs b/components/script/dom/htmlmetaelement.rs index 55561c81fc0..1bf78c66c8e 100644 --- a/components/script/dom/htmlmetaelement.rs +++ b/components/script/dom/htmlmetaelement.rs @@ -14,7 +14,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLMetaElement { htmlelement: HTMLElement, } @@ -45,7 +44,7 @@ impl HTMLMetaElement { } } -impl<'a> HTMLMetaElementMethods for &'a HTMLMetaElement { +impl HTMLMetaElementMethods for HTMLMetaElement { // https://html.spec.whatwg.org/multipage/#dom-meta-name make_getter!(Name, "name"); diff --git a/components/script/dom/htmlmeterelement.rs b/components/script/dom/htmlmeterelement.rs index d91be36f600..8ea70b2ffdd 100644 --- a/components/script/dom/htmlmeterelement.rs +++ b/components/script/dom/htmlmeterelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLMeterElement { htmlelement: HTMLElement } @@ -43,4 +42,3 @@ impl HTMLMeterElement { Node::reflect_node(box element, document, HTMLMeterElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlmodelement.rs b/components/script/dom/htmlmodelement.rs index eed06692bce..90f0ebe5103 100644 --- a/components/script/dom/htmlmodelement.rs +++ b/components/script/dom/htmlmodelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLModElement { htmlelement: HTMLElement } @@ -44,4 +43,3 @@ impl HTMLModElement { Node::reflect_node(box element, document, HTMLModElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlobjectelement.rs b/components/script/dom/htmlobjectelement.rs index ba0784ab7fb..5f0520fd763 100644 --- a/components/script/dom/htmlobjectelement.rs +++ b/components/script/dom/htmlobjectelement.rs @@ -3,7 +3,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; -use dom::attr::AttrHelpers; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; use dom::bindings::codegen::Bindings::HTMLObjectElementBinding; @@ -12,11 +11,10 @@ use dom::bindings::codegen::InheritTypes::HTMLObjectElementDerived; use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast}; use dom::bindings::js::Root; use dom::document::Document; -use dom::element::AttributeHandlers; use dom::element::ElementTypeId; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; -use dom::node::{Node, NodeTypeId, NodeHelpers, window_from_node}; +use dom::node::{Node, NodeTypeId, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; @@ -25,7 +23,6 @@ use std::sync::Arc; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLObjectElement { htmlelement: HTMLElement, image: DOMRefCell>>, @@ -85,9 +82,9 @@ pub fn is_image_data(uri: &str) -> bool { TYPES.iter().any(|&type_| uri.starts_with(type_)) } -impl<'a> HTMLObjectElementMethods for &'a HTMLObjectElement { +impl HTMLObjectElementMethods for HTMLObjectElement { // https://html.spec.whatwg.org/multipage/#dom-cva-validity - fn Validity(self) -> Root { + fn Validity(&self) -> Root { let window = window_from_node(self); ValidityState::new(window.r()) } @@ -99,9 +96,9 @@ impl<'a> HTMLObjectElementMethods for &'a HTMLObjectElement { make_setter!(SetType, "type"); } -impl<'a> VirtualMethods for &'a HTMLObjectElement { +impl VirtualMethods for HTMLObjectElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -118,4 +115,3 @@ impl<'a> VirtualMethods for &'a HTMLObjectElement { } } } - diff --git a/components/script/dom/htmlolistelement.rs b/components/script/dom/htmlolistelement.rs index ec27e04ab0a..9b1ce403d88 100644 --- a/components/script/dom/htmlolistelement.rs +++ b/components/script/dom/htmlolistelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLOListElement { htmlelement: HTMLElement, } @@ -43,4 +42,3 @@ impl HTMLOListElement { Node::reflect_node(box element, document, HTMLOListElementBinding::Wrap) } } - diff --git a/components/script/dom/htmloptgroupelement.rs b/components/script/dom/htmloptgroupelement.rs index 9993f9576b2..547136cf931 100644 --- a/components/script/dom/htmloptgroupelement.rs +++ b/components/script/dom/htmloptgroupelement.rs @@ -3,24 +3,21 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; -use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLOptGroupElementBinding; use dom::bindings::codegen::Bindings::HTMLOptGroupElementBinding::HTMLOptGroupElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{HTMLOptGroupElementDerived, HTMLOptionElementDerived}; use dom::bindings::js::Root; use dom::document::Document; -use dom::element::AttributeHandlers; use dom::element::ElementTypeId; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; -use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId}; +use dom::node::{Node, NodeTypeId}; use dom::virtualmethods::VirtualMethods; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLOptGroupElement { htmlelement: HTMLElement } @@ -52,7 +49,7 @@ impl HTMLOptGroupElement { } } -impl<'a> HTMLOptGroupElementMethods for &'a HTMLOptGroupElement { +impl HTMLOptGroupElementMethods for HTMLOptGroupElement { // https://www.whatwg.org/html#dom-optgroup-disabled make_bool_getter!(Disabled); @@ -60,9 +57,9 @@ impl<'a> HTMLOptGroupElementMethods for &'a HTMLOptGroupElement { make_bool_setter!(SetDisabled, "disabled"); } -impl<'a> VirtualMethods for &'a HTMLOptGroupElement { +impl VirtualMethods for HTMLOptGroupElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -73,7 +70,7 @@ impl<'a> VirtualMethods for &'a HTMLOptGroupElement { match attr.local_name() { &atom!("disabled") => { - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.set_disabled_state(true); node.set_enabled_state(false); for child in node.children() { @@ -94,7 +91,7 @@ impl<'a> VirtualMethods for &'a HTMLOptGroupElement { match attr.local_name() { &atom!("disabled") => { - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.set_disabled_state(false); node.set_enabled_state(true); for child in node.children() { @@ -107,4 +104,3 @@ impl<'a> VirtualMethods for &'a HTMLOptGroupElement { } } } - diff --git a/components/script/dom/htmloptionelement.rs b/components/script/dom/htmloptionelement.rs index 55685d6527f..f830cc61cc1 100644 --- a/components/script/dom/htmloptionelement.rs +++ b/components/script/dom/htmloptionelement.rs @@ -3,7 +3,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; -use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods; @@ -14,16 +13,14 @@ use dom::bindings::codegen::InheritTypes::{HTMLScriptElementDerived}; use dom::bindings::js::Root; use dom::document::Document; use dom::element::ElementTypeId; -use dom::element::{AttributeHandlers, ElementHelpers}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; -use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId}; +use dom::node::{Node, NodeTypeId}; use dom::virtualmethods::VirtualMethods; use util::str::{DOMString, split_html_space_chars}; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLOptionElement { htmlelement: HTMLElement } @@ -73,18 +70,18 @@ fn collect_text(node: &&Node, value: &mut DOMString) { } } -impl<'a> HTMLOptionElementMethods for &'a HTMLOptionElement { +impl HTMLOptionElementMethods for HTMLOptionElement { // https://www.whatwg.org/html/#dom-option-disabled make_bool_getter!(Disabled); // https://www.whatwg.org/html/#dom-option-disabled - fn SetDisabled(self, disabled: bool) { + fn SetDisabled(&self, disabled: bool) { let elem = ElementCast::from_ref(self); elem.set_bool_attribute(&atom!("disabled"), disabled) } // https://www.whatwg.org/html/#dom-option-text - fn Text(self) -> DOMString { + fn Text(&self) -> DOMString { let node = NodeCast::from_ref(self); let mut content = String::new(); collect_text(&node, &mut content); @@ -93,13 +90,13 @@ impl<'a> HTMLOptionElementMethods for &'a HTMLOptionElement { } // https://www.whatwg.org/html/#dom-option-text - fn SetText(self, value: DOMString) { + fn SetText(&self, value: DOMString) { let node = NodeCast::from_ref(self); node.SetTextContent(Some(value)) } // https://html.spec.whatwg.org/multipage/#attr-option-value - fn Value(self) -> DOMString { + fn Value(&self) -> DOMString { let element = ElementCast::from_ref(self); let attr = &atom!("value"); if element.has_attribute(attr) { @@ -113,7 +110,7 @@ impl<'a> HTMLOptionElementMethods for &'a HTMLOptionElement { make_setter!(SetValue, "value"); // https://html.spec.whatwg.org/multipage/#attr-option-label - fn Label(self) -> DOMString { + fn Label(&self) -> DOMString { let element = ElementCast::from_ref(self); let attr = &atom!("label"); if element.has_attribute(attr) { @@ -128,9 +125,9 @@ impl<'a> HTMLOptionElementMethods for &'a HTMLOptionElement { } -impl<'a> VirtualMethods for &'a HTMLOptionElement { +impl VirtualMethods for HTMLOptionElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -141,7 +138,7 @@ impl<'a> VirtualMethods for &'a HTMLOptionElement { match attr.local_name() { &atom!("disabled") => { - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.set_disabled_state(true); node.set_enabled_state(false); }, @@ -156,7 +153,7 @@ impl<'a> VirtualMethods for &'a HTMLOptionElement { match attr.local_name() { &atom!("disabled") => { - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.set_disabled_state(false); node.set_enabled_state(true); node.check_parent_disabled_state_for_option(); @@ -170,7 +167,7 @@ impl<'a> VirtualMethods for &'a HTMLOptionElement { s.bind_to_tree(tree_in_doc); } - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.check_parent_disabled_state_for_option(); } @@ -179,7 +176,7 @@ impl<'a> VirtualMethods for &'a HTMLOptionElement { s.unbind_from_tree(tree_in_doc); } - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); if node.GetParentNode().is_some() { node.check_parent_disabled_state_for_option(); } else { @@ -187,4 +184,3 @@ impl<'a> VirtualMethods for &'a HTMLOptionElement { } } } - diff --git a/components/script/dom/htmloutputelement.rs b/components/script/dom/htmloutputelement.rs index 48a8dd40ff6..0b69f99ce0a 100644 --- a/components/script/dom/htmloutputelement.rs +++ b/components/script/dom/htmloutputelement.rs @@ -15,7 +15,6 @@ use dom::validitystate::ValidityState; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLOutputElement { htmlelement: HTMLElement } @@ -47,11 +46,10 @@ impl HTMLOutputElement { } } -impl<'a> HTMLOutputElementMethods for &'a HTMLOutputElement { +impl HTMLOutputElementMethods for HTMLOutputElement { // https://html.spec.whatwg.org/multipage/#dom-cva-validity - fn Validity(self) -> Root { + fn Validity(&self) -> Root { let window = window_from_node(self); ValidityState::new(window.r()) } } - diff --git a/components/script/dom/htmlparagraphelement.rs b/components/script/dom/htmlparagraphelement.rs index 3c39eb42925..abda9483aef 100644 --- a/components/script/dom/htmlparagraphelement.rs +++ b/components/script/dom/htmlparagraphelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLParagraphElement { htmlelement: HTMLElement } @@ -44,4 +43,3 @@ impl HTMLParagraphElement { Node::reflect_node(box element, document, HTMLParagraphElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlparamelement.rs b/components/script/dom/htmlparamelement.rs index e1c5a2deea6..d8a18d3d152 100644 --- a/components/script/dom/htmlparamelement.rs +++ b/components/script/dom/htmlparamelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLParamElement { htmlelement: HTMLElement } @@ -44,4 +43,3 @@ impl HTMLParamElement { Node::reflect_node(box element, document, HTMLParamElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlpreelement.rs b/components/script/dom/htmlpreelement.rs index bb5000b895b..a105f1fd559 100644 --- a/components/script/dom/htmlpreelement.rs +++ b/components/script/dom/htmlpreelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLPreElement { htmlelement: HTMLElement, } @@ -44,4 +43,3 @@ impl HTMLPreElement { Node::reflect_node(box element, document, HTMLPreElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlprogresselement.rs b/components/script/dom/htmlprogresselement.rs index ea507d36fbc..373d914c97f 100644 --- a/components/script/dom/htmlprogresselement.rs +++ b/components/script/dom/htmlprogresselement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLProgressElement { htmlelement: HTMLElement, } @@ -44,4 +43,3 @@ impl HTMLProgressElement { Node::reflect_node(box element, document, HTMLProgressElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlquoteelement.rs b/components/script/dom/htmlquoteelement.rs index 8162bcb5244..49b5f0853a5 100644 --- a/components/script/dom/htmlquoteelement.rs +++ b/components/script/dom/htmlquoteelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLQuoteElement { htmlelement: HTMLElement, } @@ -44,4 +43,3 @@ impl HTMLQuoteElement { Node::reflect_node(box element, document, HTMLQuoteElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlscriptelement.rs b/components/script/dom/htmlscriptelement.rs index d38930d4d54..97cd6573fda 100644 --- a/components/script/dom/htmlscriptelement.rs +++ b/components/script/dom/htmlscriptelement.rs @@ -6,7 +6,6 @@ use std::ascii::AsciiExt; use document_loader::LoadType; use dom::attr::Attr; -use dom::attr::AttrHelpers; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; @@ -21,20 +20,19 @@ use dom::bindings::js::RootedReference; use dom::bindings::js::{JS, Root}; use dom::bindings::refcounted::Trusted; use dom::bindings::trace::JSTraceable; -use dom::document::{Document, DocumentHelpers}; -use dom::element::ElementTypeId; -use dom::element::{AttributeHandlers, ElementCreator}; -use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers}; +use dom::document::Document; +use dom::element::{ElementCreator, ElementTypeId}; +use dom::event::{Event, EventBubbles, EventCancelable}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; -use dom::node::{ChildrenMutation, CloneChildrenFlag, Node, NodeHelpers}; +use dom::node::{ChildrenMutation, CloneChildrenFlag, Node}; use dom::node::{NodeTypeId, document_from_node, window_from_node}; -use dom::servohtmlparser::ServoHTMLParserHelpers; use dom::virtualmethods::VirtualMethods; -use dom::window::{WindowHelpers, ScriptHelpers}; +use dom::window::ScriptHelpers; use js::jsapi::RootedValue; use js::jsval::UndefinedValue; use network_listener::{NetworkListener, PreInvoke}; +use script_task::ScriptTaskEventCategory::ScriptEvent; use script_task::{ScriptChan, Runnable, CommonScriptMsg}; use encoding::all::UTF_8; @@ -52,7 +50,6 @@ use url::{Url, UrlParser}; use util::str::{DOMString, HTML_SPACE_CHARACTERS, StaticStringVec}; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLScriptElement { htmlelement: HTMLElement, @@ -111,35 +108,6 @@ impl HTMLScriptElement { } } -pub trait HTMLScriptElementHelpers { - /// Prepare a script () - fn prepare(self) -> NextParserState; - - /// [Execute a script block] - /// (https://html.spec.whatwg.org/multipage/#execute-the-script-block) - fn execute(self, load: ScriptOrigin); - - /// Prepare a script, steps 6 and 7. - fn is_javascript(self) -> bool; - - /// Set the "already started" flag () - fn mark_already_started(self); - - // Queues error event - fn queue_error_event(self); - - /// Dispatch beforescriptexecute event. - fn dispatch_before_script_execute_event(self) -> bool; - - /// Dispatch afterscriptexecute event. - fn dispatch_after_script_execute_event(self); - - /// Dispatch load event. - fn dispatch_load_event(self); - - /// Dispatch error event. - fn dispatch_error_event(self); -} /// Supported script types as defined by /// . @@ -213,8 +181,8 @@ impl AsyncResponseListener for ScriptContext { impl PreInvoke for ScriptContext {} -impl<'a> HTMLScriptElementHelpers for &'a HTMLScriptElement { - fn prepare(self) -> NextParserState { +impl HTMLScriptElement { + pub fn prepare(&self) -> NextParserState { // https://html.spec.whatwg.org/multipage/#prepare-a-script // Step 1. if self.already_started.get() { @@ -366,7 +334,7 @@ impl<'a> HTMLScriptElementHelpers for &'a HTMLScriptElement { NextParserState::Continue } - fn execute(self, load: ScriptOrigin) { + pub fn execute(&self, load: ScriptOrigin) { // Step 1. // TODO: If the element is flagged as "parser-inserted", but the // element's node document is not the Document of the parser that @@ -459,11 +427,11 @@ impl<'a> HTMLScriptElementHelpers for &'a HTMLScriptElement { element: handler, is_error: false, }; - chan.send(CommonScriptMsg::RunnableMsg(dispatcher)).unwrap(); + chan.send(CommonScriptMsg::RunnableMsg(ScriptEvent, dispatcher)).unwrap(); } } - fn queue_error_event(self) { + pub fn queue_error_event(&self) { let window = window_from_node(self); let window = window.r(); let chan = window.script_chan(); @@ -472,34 +440,34 @@ impl<'a> HTMLScriptElementHelpers for &'a HTMLScriptElement { element: handler, is_error: true, }; - chan.send(CommonScriptMsg::RunnableMsg(dispatcher)).unwrap(); + chan.send(CommonScriptMsg::RunnableMsg(ScriptEvent, dispatcher)).unwrap(); } - fn dispatch_before_script_execute_event(self) -> bool { + pub fn dispatch_before_script_execute_event(&self) -> bool { self.dispatch_event("beforescriptexecute".to_owned(), EventBubbles::Bubbles, EventCancelable::Cancelable) } - fn dispatch_after_script_execute_event(self) { + pub fn dispatch_after_script_execute_event(&self) { self.dispatch_event("afterscriptexecute".to_owned(), EventBubbles::Bubbles, EventCancelable::NotCancelable); } - fn dispatch_load_event(self) { + pub fn dispatch_load_event(&self) { self.dispatch_event("load".to_owned(), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable); } - fn dispatch_error_event(self) { + pub fn dispatch_error_event(&self) { self.dispatch_event("error".to_owned(), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable); } - fn is_javascript(self) -> bool { + pub fn is_javascript(&self) -> bool { let element = ElementCast::from_ref(self); match element.get_attribute(&ns!(""), &atom!("type")).map(|s| s.r().Value()) { Some(ref s) if s.is_empty() => { @@ -532,20 +500,11 @@ impl<'a> HTMLScriptElementHelpers for &'a HTMLScriptElement { } } - fn mark_already_started(self) { + pub fn mark_already_started(&self) { self.already_started.set(true); } -} -trait PrivateHTMLScriptElementHelpers { - fn dispatch_event(self, - type_: DOMString, - bubbles: EventBubbles, - cancelable: EventCancelable) -> bool; -} - -impl<'a> PrivateHTMLScriptElementHelpers for &'a HTMLScriptElement { - fn dispatch_event(self, + fn dispatch_event(&self, type_: DOMString, bubbles: EventBubbles, cancelable: EventCancelable) -> bool { @@ -561,9 +520,9 @@ impl<'a> PrivateHTMLScriptElementHelpers for &'a HTMLScriptElement { } } -impl<'a> VirtualMethods for &'a HTMLScriptElement { +impl VirtualMethods for HTMLScriptElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -571,7 +530,7 @@ impl<'a> VirtualMethods for &'a HTMLScriptElement { if let Some(ref s) = self.super_type() { s.after_set_attr(attr); } - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); if attr.local_name() == &atom!("src") && !self.parser_inserted.get() && node.is_in_doc() { self.prepare(); } @@ -581,7 +540,7 @@ impl<'a> VirtualMethods for &'a HTMLScriptElement { if let Some(ref s) = self.super_type() { s.children_changed(mutation); } - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); if !self.parser_inserted.get() && node.is_in_doc() { self.prepare(); } @@ -611,18 +570,19 @@ impl<'a> VirtualMethods for &'a HTMLScriptElement { } } -impl<'a> HTMLScriptElementMethods for &'a HTMLScriptElement { +impl HTMLScriptElementMethods for HTMLScriptElement { + // https://html.spec.whatwg.org/multipage/#dom-script-src make_url_getter!(Src); - + // https://html.spec.whatwg.org/multipage/#dom-script-src make_setter!(SetSrc, "src"); // https://www.whatwg.org/html/#dom-script-text - fn Text(self) -> DOMString { + fn Text(&self) -> DOMString { Node::collect_text_contents(NodeCast::from_ref(self).children()) } // https://www.whatwg.org/html/#dom-script-text - fn SetText(self, value: DOMString) { + fn SetText(&self, value: DOMString) { let node = NodeCast::from_ref(self); node.SetTextContent(Some(value)) } diff --git a/components/script/dom/htmlselectelement.rs b/components/script/dom/htmlselectelement.rs index 6b5027f39da..bed90a07c6e 100644 --- a/components/script/dom/htmlselectelement.rs +++ b/components/script/dom/htmlselectelement.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use dom::attr::{Attr, AttrHelpers, AttrValue}; +use dom::attr::{Attr, AttrValue}; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; @@ -11,11 +11,10 @@ use dom::bindings::codegen::UnionTypes::HTMLElementOrLong; use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement; use dom::bindings::js::Root; use dom::document::Document; -use dom::element::AttributeHandlers; use dom::element::ElementTypeId; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; -use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId, window_from_node}; +use dom::node::{Node, NodeTypeId, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; @@ -25,7 +24,6 @@ use util::str::DOMString; use std::borrow::ToOwned; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLSelectElement { htmlelement: HTMLElement } @@ -59,16 +57,16 @@ impl HTMLSelectElement { } } -impl<'a> HTMLSelectElementMethods for &'a HTMLSelectElement { +impl HTMLSelectElementMethods for HTMLSelectElement { // https://html.spec.whatwg.org/multipage/#dom-cva-validity - fn Validity(self) -> Root { + fn Validity(&self) -> Root { let window = window_from_node(self); ValidityState::new(window.r()) } // Note: this function currently only exists for test_union.html. // https://html.spec.whatwg.org/multipage/#dom-select-add - fn Add(self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option) { + fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option) { } // https://www.whatwg.org/html/#dom-fe-disabled @@ -96,7 +94,7 @@ impl<'a> HTMLSelectElementMethods for &'a HTMLSelectElement { make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-select-type - fn Type(self) -> DOMString { + fn Type(&self) -> DOMString { if self.Multiple() { "select-multiple".to_owned() } else { @@ -105,9 +103,9 @@ impl<'a> HTMLSelectElementMethods for &'a HTMLSelectElement { } } -impl<'a> VirtualMethods for &'a HTMLSelectElement { +impl VirtualMethods for HTMLSelectElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -118,7 +116,7 @@ impl<'a> VirtualMethods for &'a HTMLSelectElement { match attr.local_name() { &atom!("disabled") => { - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.set_disabled_state(true); node.set_enabled_state(false); }, @@ -133,7 +131,7 @@ impl<'a> VirtualMethods for &'a HTMLSelectElement { match attr.local_name() { &atom!("disabled") => { - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.set_disabled_state(false); node.set_enabled_state(true); node.check_ancestors_disabled_state_for_form_control(); @@ -147,7 +145,7 @@ impl<'a> VirtualMethods for &'a HTMLSelectElement { s.bind_to_tree(tree_in_doc); } - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.check_ancestors_disabled_state_for_form_control(); } @@ -156,7 +154,7 @@ impl<'a> VirtualMethods for &'a HTMLSelectElement { s.unbind_from_tree(tree_in_doc); } - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); if node.ancestors().any(|ancestor| ancestor.r().is_htmlfieldsetelement()) { node.check_ancestors_disabled_state_for_form_control(); } else { @@ -171,4 +169,3 @@ impl<'a> VirtualMethods for &'a HTMLSelectElement { } } } - diff --git a/components/script/dom/htmlsourceelement.rs b/components/script/dom/htmlsourceelement.rs index 1d1294883f4..ea6b163c539 100644 --- a/components/script/dom/htmlsourceelement.rs +++ b/components/script/dom/htmlsourceelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLSourceElement { htmlelement: HTMLElement } @@ -44,4 +43,3 @@ impl HTMLSourceElement { Node::reflect_node(box element, document, HTMLSourceElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlspanelement.rs b/components/script/dom/htmlspanelement.rs index 2cb3f766767..e6e2a1f4bcd 100644 --- a/components/script/dom/htmlspanelement.rs +++ b/components/script/dom/htmlspanelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLSpanElement { htmlelement: HTMLElement } @@ -41,4 +40,3 @@ impl HTMLSpanElement { Node::reflect_node(box element, document, HTMLSpanElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlstyleelement.rs b/components/script/dom/htmlstyleelement.rs index fb87535fa3a..91b22e40478 100644 --- a/components/script/dom/htmlstyleelement.rs +++ b/components/script/dom/htmlstyleelement.rs @@ -3,26 +3,23 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::Parser as CssParser; -use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast, HTMLStyleElementDerived, NodeCast}; use dom::bindings::js::Root; use dom::document::Document; -use dom::element::{ElementTypeId, AttributeHandlers}; +use dom::element::ElementTypeId; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::window_from_node; -use dom::node::{ChildrenMutation, Node, NodeHelpers, NodeTypeId}; +use dom::node::{ChildrenMutation, Node, NodeTypeId}; use dom::virtualmethods::VirtualMethods; -use dom::window::WindowHelpers; use layout_interface::{LayoutChan, Msg}; use style::media_queries::parse_media_query_list; use style::stylesheets::{Origin, Stylesheet}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLStyleElement { htmlelement: HTMLElement, } @@ -51,14 +48,8 @@ impl HTMLStyleElement { let element = HTMLStyleElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLStyleElementBinding::Wrap) } -} -pub trait StyleElementHelpers { - fn parse_own_css(self); -} - -impl<'a> StyleElementHelpers for &'a HTMLStyleElement { - fn parse_own_css(self) { + pub fn parse_own_css(&self) { let node = NodeCast::from_ref(self); let element = ElementCast::from_ref(self); assert!(node.is_in_doc()); @@ -82,9 +73,9 @@ impl<'a> StyleElementHelpers for &'a HTMLStyleElement { } } -impl<'a> VirtualMethods for &'a HTMLStyleElement { +impl VirtualMethods for HTMLStyleElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -92,7 +83,7 @@ impl<'a> VirtualMethods for &'a HTMLStyleElement { if let Some(ref s) = self.super_type() { s.children_changed(mutation); } - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); if node.is_in_doc() { self.parse_own_css(); } @@ -108,4 +99,3 @@ impl<'a> VirtualMethods for &'a HTMLStyleElement { } } } - diff --git a/components/script/dom/htmltablecaptionelement.rs b/components/script/dom/htmltablecaptionelement.rs index 80d643e338a..8c74e526756 100644 --- a/components/script/dom/htmltablecaptionelement.rs +++ b/components/script/dom/htmltablecaptionelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLTableCaptionElement { htmlelement: HTMLElement } @@ -44,4 +43,3 @@ impl HTMLTableCaptionElement { Node::reflect_node(box element, document, HTMLTableCaptionElementBinding::Wrap) } } - diff --git a/components/script/dom/htmltablecellelement.rs b/components/script/dom/htmltablecellelement.rs index 29cf8eaaebd..db4a08a00c5 100644 --- a/components/script/dom/htmltablecellelement.rs +++ b/components/script/dom/htmltablecellelement.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use dom::attr::{Attr, AttrHelpers, AttrValue}; +use dom::attr::{Attr, AttrValue}; use dom::bindings::codegen::Bindings::HTMLTableCellElementBinding::HTMLTableCellElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLTableCellElementDerived}; use dom::document::Document; @@ -36,7 +36,6 @@ impl PartialEq for HTMLTableCellElementTypeId { } #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLTableCellElement { htmlelement: HTMLElement, background_color: Cell>, @@ -75,35 +74,32 @@ impl HTMLTableCellElement { } } -impl<'a> HTMLTableCellElementMethods for &'a HTMLTableCellElement { +impl HTMLTableCellElementMethods for HTMLTableCellElement { // https://html.spec.whatwg.org/multipage/#dom-tdth-colspan make_uint_getter!(ColSpan, "colspan", DEFAULT_COLSPAN); + + // https://html.spec.whatwg.org/multipage/#dom-tdth-colspan make_uint_setter!(SetColSpan, "colspan"); } -pub trait HTMLTableCellElementHelpers { - fn get_background_color(self) -> Option; - fn get_colspan(self) -> Option; - fn get_width(self) -> LengthOrPercentageOrAuto; -} -impl<'a> HTMLTableCellElementHelpers for &'a HTMLTableCellElement { - fn get_background_color(self) -> Option { +impl HTMLTableCellElement { + pub fn get_background_color(&self) -> Option { self.background_color.get() } - fn get_colspan(self) -> Option { + pub fn get_colspan(&self) -> Option { self.colspan.get() } - fn get_width(self) -> LengthOrPercentageOrAuto { + pub fn get_width(&self) -> LengthOrPercentageOrAuto { self.width.get() } } -impl<'a> VirtualMethods for &'a HTMLTableCellElement { +impl VirtualMethods for HTMLTableCellElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -149,4 +145,3 @@ impl<'a> VirtualMethods for &'a HTMLTableCellElement { } } } - diff --git a/components/script/dom/htmltablecolelement.rs b/components/script/dom/htmltablecolelement.rs index 24cbd7ae335..45e94518f65 100644 --- a/components/script/dom/htmltablecolelement.rs +++ b/components/script/dom/htmltablecolelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLTableColElement { htmlelement: HTMLElement, } @@ -44,4 +43,3 @@ impl HTMLTableColElement { Node::reflect_node(box element, document, HTMLTableColElementBinding::Wrap) } } - diff --git a/components/script/dom/htmltabledatacellelement.rs b/components/script/dom/htmltabledatacellelement.rs index 248374948fc..691aad8644a 100644 --- a/components/script/dom/htmltabledatacellelement.rs +++ b/components/script/dom/htmltabledatacellelement.rs @@ -14,7 +14,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLTableDataCellElement { htmltablecellelement: HTMLTableCellElement, } @@ -49,4 +48,3 @@ impl HTMLTableDataCellElement { HTMLTableDataCellElementBinding::Wrap) } } - diff --git a/components/script/dom/htmltableelement.rs b/components/script/dom/htmltableelement.rs index 1d05cf70060..b55f9ac341f 100644 --- a/components/script/dom/htmltableelement.rs +++ b/components/script/dom/htmltableelement.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use dom::attr::{Attr, AttrHelpers, AttrValue}; +use dom::attr::{Attr, AttrValue}; use dom::bindings::codegen::Bindings::HTMLTableElementBinding; use dom::bindings::codegen::Bindings::HTMLTableElementBinding::HTMLTableElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; @@ -11,12 +11,12 @@ use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast, HTMLTab use dom::bindings::codegen::InheritTypes::{HTMLTableElementDerived, NodeCast}; use dom::bindings::js::{Root, RootedReference}; use dom::document::Document; -use dom::element::{ElementHelpers, ElementTypeId}; +use dom::element::ElementTypeId; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::htmltablecaptionelement::HTMLTableCaptionElement; use dom::htmltablesectionelement::HTMLTableSectionElement; -use dom::node::{Node, NodeHelpers, NodeTypeId, document_from_node}; +use dom::node::{Node, NodeTypeId, document_from_node}; use dom::virtualmethods::VirtualMethods; use util::str::{self, DOMString, LengthOrPercentageOrAuto}; @@ -27,7 +27,6 @@ use string_cache::Atom; use std::cell::Cell; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLTableElement { htmlelement: HTMLElement, background_color: Cell>, @@ -67,9 +66,9 @@ impl HTMLTableElement { } } -impl<'a> HTMLTableElementMethods for &'a HTMLTableElement { +impl HTMLTableElementMethods for HTMLTableElement { // https://html.spec.whatwg.org/multipage/#dom-table-caption - fn GetCaption(self) -> Option> { + fn GetCaption(&self) -> Option> { let node = NodeCast::from_ref(self); node.children() .filter_map(|c| { @@ -79,7 +78,7 @@ impl<'a> HTMLTableElementMethods for &'a HTMLTableElement { } // https://html.spec.whatwg.org/multipage/#dom-table-caption - fn SetCaption(self, new_caption: Option<&HTMLTableCaptionElement>) { + fn SetCaption(&self, new_caption: Option<&HTMLTableCaptionElement>) { let node = NodeCast::from_ref(self); if let Some(ref caption) = self.GetCaption() { @@ -93,7 +92,7 @@ impl<'a> HTMLTableElementMethods for &'a HTMLTableElement { } // https://html.spec.whatwg.org/multipage/#dom-table-createcaption - fn CreateCaption(self) -> Root { + fn CreateCaption(&self) -> Root { let caption = match self.GetCaption() { Some(caption) => caption, None => { @@ -108,14 +107,14 @@ impl<'a> HTMLTableElementMethods for &'a HTMLTableElement { } // https://html.spec.whatwg.org/multipage/#dom-table-deletecaption - fn DeleteCaption(self) { + fn DeleteCaption(&self) { if let Some(caption) = self.GetCaption() { NodeCast::from_ref(caption.r()).remove_self(); } } // https://html.spec.whatwg.org/multipage/#dom-table-createtbody - fn CreateTBody(self) -> Root { + fn CreateTBody(&self) -> Root { let tbody = HTMLTableSectionElement::new("tbody".to_owned(), None, document_from_node(self).r()); @@ -133,34 +132,28 @@ impl<'a> HTMLTableElementMethods for &'a HTMLTableElement { } } -pub trait HTMLTableElementHelpers { - fn get_background_color(self) -> Option; - fn get_border(self) -> Option; - fn get_cellspacing(self) -> Option; - fn get_width(self) -> LengthOrPercentageOrAuto; -} -impl<'a> HTMLTableElementHelpers for &'a HTMLTableElement { - fn get_background_color(self) -> Option { +impl HTMLTableElement { + pub fn get_background_color(&self) -> Option { self.background_color.get() } - fn get_border(self) -> Option { + pub fn get_border(&self) -> Option { self.border.get() } - fn get_cellspacing(self) -> Option { + pub fn get_cellspacing(&self) -> Option { self.cellspacing.get() } - fn get_width(self) -> LengthOrPercentageOrAuto { + pub fn get_width(&self) -> LengthOrPercentageOrAuto { self.width.get() } } -impl<'a> VirtualMethods for &'a HTMLTableElement { +impl VirtualMethods for HTMLTableElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -207,4 +200,3 @@ impl<'a> VirtualMethods for &'a HTMLTableElement { } } } - diff --git a/components/script/dom/htmltableheadercellelement.rs b/components/script/dom/htmltableheadercellelement.rs index 8b5cc867354..579167ebd0b 100644 --- a/components/script/dom/htmltableheadercellelement.rs +++ b/components/script/dom/htmltableheadercellelement.rs @@ -14,7 +14,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLTableHeaderCellElement { htmltablecellelement: HTMLTableCellElement, } @@ -46,4 +45,3 @@ impl HTMLTableHeaderCellElement { Node::reflect_node(box element, document, HTMLTableHeaderCellElementBinding::Wrap) } } - diff --git a/components/script/dom/htmltablerowelement.rs b/components/script/dom/htmltablerowelement.rs index d93a4462bd8..160b9a3833b 100644 --- a/components/script/dom/htmltablerowelement.rs +++ b/components/script/dom/htmltablerowelement.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use dom::attr::{Attr, AttrHelpers}; +use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLTableRowElementBinding; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLTableRowElementDerived}; use dom::bindings::js::Root; @@ -18,7 +18,6 @@ use std::cell::Cell; use util::str::{self, DOMString}; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLTableRowElement { htmlelement: HTMLElement, background_color: Cell>, @@ -51,22 +50,15 @@ impl HTMLTableRowElement { document, HTMLTableRowElementBinding::Wrap) } -} - -pub trait HTMLTableRowElementHelpers { - fn get_background_color(self) -> Option; -} - -impl<'a> HTMLTableRowElementHelpers for &'a HTMLTableRowElement { - fn get_background_color(self) -> Option { + pub fn get_background_color(&self) -> Option { self.background_color.get() } } -impl<'a> VirtualMethods for &'a HTMLTableRowElement { +impl VirtualMethods for HTMLTableRowElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } diff --git a/components/script/dom/htmltablesectionelement.rs b/components/script/dom/htmltablesectionelement.rs index d0f1b8dd60d..5922ffd4b42 100644 --- a/components/script/dom/htmltablesectionelement.rs +++ b/components/script/dom/htmltablesectionelement.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use dom::attr::{Attr, AttrHelpers}; +use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLTableSectionElementBinding; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLTableSectionElementDerived}; use dom::bindings::js::Root; @@ -18,7 +18,6 @@ use std::cell::Cell; use util::str::{self, DOMString}; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLTableSectionElement { htmlelement: HTMLElement, background_color: Cell>, @@ -50,21 +49,15 @@ impl HTMLTableSectionElement { let element = HTMLTableSectionElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLTableSectionElementBinding::Wrap) } -} -pub trait HTMLTableSectionElementHelpers { - fn get_background_color(self) -> Option; -} - -impl<'a> HTMLTableSectionElementHelpers for &'a HTMLTableSectionElement { - fn get_background_color(self) -> Option { + pub fn get_background_color(&self) -> Option { self.background_color.get() } } -impl<'a> VirtualMethods for &'a HTMLTableSectionElement { +impl VirtualMethods for HTMLTableSectionElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } diff --git a/components/script/dom/htmltemplateelement.rs b/components/script/dom/htmltemplateelement.rs index 099e0f2975c..86e69b31a64 100644 --- a/components/script/dom/htmltemplateelement.rs +++ b/components/script/dom/htmltemplateelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLTemplateElement { htmlelement: HTMLElement, } @@ -44,4 +43,3 @@ impl HTMLTemplateElement { Node::reflect_node(box element, document, HTMLTemplateElementBinding::Wrap) } } - diff --git a/components/script/dom/htmltextareaelement.rs b/components/script/dom/htmltextareaelement.rs index f92f797a4d5..a0a0c12b705 100644 --- a/components/script/dom/htmltextareaelement.rs +++ b/components/script/dom/htmltextareaelement.rs @@ -2,7 +2,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use dom::attr::AttrHelpers; use dom::attr::{Attr, AttrValue}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventBinding::EventMethods; @@ -15,19 +14,18 @@ use dom::bindings::codegen::InheritTypes::{HTMLTextAreaElementDerived, HTMLField use dom::bindings::global::GlobalRef; use dom::bindings::js::{LayoutJS, Root}; use dom::bindings::refcounted::Trusted; -use dom::document::{Document, DocumentHelpers}; -use dom::element::ElementTypeId; -use dom::element::{Element, AttributeHandlers}; +use dom::document::Document; +use dom::element::{Element, ElementTypeId}; use dom::event::{Event, EventBubbles, EventCancelable}; -use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::htmlformelement::FormControl; use dom::keyboardevent::KeyboardEvent; -use dom::node::{ChildrenMutation, DisabledStateHelpers, Node, NodeDamage}; -use dom::node::{NodeHelpers, NodeTypeId, document_from_node, window_from_node}; +use dom::node::{ChildrenMutation, Node, NodeDamage}; +use dom::node::{NodeTypeId, document_from_node, window_from_node}; use dom::virtualmethods::VirtualMethods; -use dom::window::WindowHelpers; use msg::constellation_msg::ConstellationChan; +use script_task::ScriptTaskEventCategory::InputEvent; use script_task::{Runnable, CommonScriptMsg}; use textinput::{TextInput, Lines, KeyReaction}; @@ -38,7 +36,6 @@ use std::borrow::ToOwned; use std::cell::Cell; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLTextAreaElement { htmlelement: HTMLElement, #[ignore_heap_size_of = "#7193"] @@ -118,12 +115,14 @@ impl HTMLTextAreaElement { } } -impl<'a> HTMLTextAreaElementMethods for &'a HTMLTextAreaElement { +impl HTMLTextAreaElementMethods for HTMLTextAreaElement { // TODO A few of these attributes have default values and additional // constraints // https://html.spec.whatwg.org/multipage/#dom-textarea-cols make_uint_getter!(Cols, "cols", DEFAULT_COLS); + + // https://html.spec.whatwg.org/multipage/#dom-textarea-cols make_limited_uint_setter!(SetCols, "cols", DEFAULT_COLS); // https://www.whatwg.org/html/#dom-fe-disabled @@ -158,6 +157,8 @@ impl<'a> HTMLTextAreaElementMethods for &'a HTMLTextAreaElement { // https://html.spec.whatwg.org/multipage/#dom-textarea-rows make_uint_getter!(Rows, "rows", DEFAULT_ROWS); + + // https://html.spec.whatwg.org/multipage/#dom-textarea-rows make_limited_uint_setter!(SetRows, "rows", DEFAULT_ROWS); // https://html.spec.whatwg.org/multipage/#dom-textarea-wrap @@ -167,18 +168,18 @@ impl<'a> HTMLTextAreaElementMethods for &'a HTMLTextAreaElement { make_setter!(SetWrap, "wrap"); // https://html.spec.whatwg.org/multipage/#dom-textarea-type - fn Type(self) -> DOMString { + fn Type(&self) -> DOMString { "textarea".to_owned() } // https://html.spec.whatwg.org/multipage/#dom-textarea-defaultvalue - fn DefaultValue(self) -> DOMString { + fn DefaultValue(&self) -> DOMString { let node = NodeCast::from_ref(self); node.GetTextContent().unwrap() } // https://html.spec.whatwg.org/multipage/#dom-textarea-defaultvalue - fn SetDefaultValue(self, value: DOMString) { + fn SetDefaultValue(&self, value: DOMString) { let node = NodeCast::from_ref(self); node.SetTextContent(Some(value)); @@ -190,12 +191,12 @@ impl<'a> HTMLTextAreaElementMethods for &'a HTMLTextAreaElement { } // https://html.spec.whatwg.org/multipage/#dom-textarea-value - fn Value(self) -> DOMString { + fn Value(&self) -> DOMString { self.textinput.borrow().get_content() } // https://html.spec.whatwg.org/multipage/#dom-textarea-value - fn SetValue(self, value: DOMString) { + fn SetValue(&self, value: DOMString) { // TODO move the cursor to the end of the field self.textinput.borrow_mut().set_content(value); self.value_changed.set(true); @@ -204,37 +205,29 @@ impl<'a> HTMLTextAreaElementMethods for &'a HTMLTextAreaElement { } } -pub trait HTMLTextAreaElementHelpers { - fn mutable(self) -> bool; - fn reset(self); -} -impl<'a> HTMLTextAreaElementHelpers for &'a HTMLTextAreaElement { +impl HTMLTextAreaElement { // https://html.spec.whatwg.org/multipage/#concept-fe-mutable - fn mutable(self) -> bool { + pub fn mutable(&self) -> bool { // https://html.spec.whatwg.org/multipage/#the-textarea-element:concept-fe-mutable !(self.Disabled() || self.ReadOnly()) } - fn reset(self) { + pub fn reset(&self) { // https://html.spec.whatwg.org/multipage/#the-textarea-element:concept-form-reset-control self.SetValue(self.DefaultValue()); self.value_changed.set(false); } } -trait PrivateHTMLTextAreaElementHelpers { - fn force_relayout(self); - fn dispatch_change_event(self); -} -impl<'a> PrivateHTMLTextAreaElementHelpers for &'a HTMLTextAreaElement { - fn force_relayout(self) { +impl HTMLTextAreaElement { + fn force_relayout(&self) { let doc = document_from_node(self); let node = NodeCast::from_ref(self); doc.r().content_changed(node, NodeDamage::OtherNodeDamage) } - fn dispatch_change_event(self) { + fn dispatch_change_event(&self) { let window = window_from_node(self); let window = window.r(); let event = Event::new(GlobalRef::Window(window), @@ -247,9 +240,9 @@ impl<'a> PrivateHTMLTextAreaElementHelpers for &'a HTMLTextAreaElement { } } -impl<'a> VirtualMethods for &'a HTMLTextAreaElement { +impl VirtualMethods for HTMLTextAreaElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -260,7 +253,7 @@ impl<'a> VirtualMethods for &'a HTMLTextAreaElement { match attr.local_name() { &atom!("disabled") => { - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.set_disabled_state(true); node.set_enabled_state(false); }, @@ -287,7 +280,7 @@ impl<'a> VirtualMethods for &'a HTMLTextAreaElement { match attr.local_name() { &atom!("disabled") => { - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.set_disabled_state(false); node.set_enabled_state(true); node.check_ancestors_disabled_state_for_form_control(); @@ -307,7 +300,7 @@ impl<'a> VirtualMethods for &'a HTMLTextAreaElement { s.bind_to_tree(tree_in_doc); } - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); node.check_ancestors_disabled_state_for_form_control(); } @@ -324,7 +317,7 @@ impl<'a> VirtualMethods for &'a HTMLTextAreaElement { s.unbind_from_tree(tree_in_doc); } - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); if node.ancestors().any(|ancestor| ancestor.r().is_htmlfieldsetelement()) { node.check_ancestors_disabled_state_for_form_control(); } else { @@ -350,8 +343,8 @@ impl<'a> VirtualMethods for &'a HTMLTextAreaElement { if &*event.Type() == "click" && !event.DefaultPrevented() { //TODO: set the editing position for text inputs - let doc = document_from_node(*self); - doc.r().request_focus(ElementCast::from_ref(*self)); + let doc = document_from_node(self); + doc.r().request_focus(ElementCast::from_ref(self)); } else if &*event.Type() == "keydown" && !event.DefaultPrevented() { let keyevent: Option<&KeyboardEvent> = KeyboardEventCast::to_ref(event); keyevent.map(|kevent| { @@ -361,14 +354,14 @@ impl<'a> VirtualMethods for &'a HTMLTextAreaElement { self.value_changed.set(true); if event.IsTrusted() { - let window = window_from_node(*self); + let window = window_from_node(self); let window = window.r(); let chan = window.script_chan(); - let handler = Trusted::new(window.get_cx(), *self, chan.clone()); + let handler = Trusted::new(window.get_cx(), self, chan.clone()); let dispatcher = ChangeEventRunnable { element: handler, }; - let _ = chan.send(CommonScriptMsg::RunnableMsg(box dispatcher)); + let _ = chan.send(CommonScriptMsg::RunnableMsg(InputEvent, box dispatcher)); } self.force_relayout(); diff --git a/components/script/dom/htmltimeelement.rs b/components/script/dom/htmltimeelement.rs index 4a94581a386..2f1bf7bb5a1 100644 --- a/components/script/dom/htmltimeelement.rs +++ b/components/script/dom/htmltimeelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLTimeElement { htmlelement: HTMLElement } @@ -41,4 +40,3 @@ impl HTMLTimeElement { Node::reflect_node(box element, document, HTMLTimeElementBinding::Wrap) } } - diff --git a/components/script/dom/htmltitleelement.rs b/components/script/dom/htmltitleelement.rs index 99aebc3e978..0640a121f5d 100644 --- a/components/script/dom/htmltitleelement.rs +++ b/components/script/dom/htmltitleelement.rs @@ -8,18 +8,16 @@ use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataCast, TextCast}; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLTitleElementDerived, NodeCast}; use dom::bindings::js::Root; -use dom::characterdata::CharacterDataHelpers; -use dom::document::{Document, DocumentHelpers}; +use dom::document::Document; use dom::element::ElementTypeId; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; -use dom::node::{ChildrenMutation, Node, NodeHelpers, NodeTypeId}; +use dom::node::{ChildrenMutation, Node, NodeTypeId}; use dom::text::Text; use dom::virtualmethods::VirtualMethods; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLTitleElement { htmlelement: HTMLElement, } @@ -48,9 +46,9 @@ impl HTMLTitleElement { } } -impl<'a> HTMLTitleElementMethods for &'a HTMLTitleElement { +impl HTMLTitleElementMethods for HTMLTitleElement { // https://www.whatwg.org/html/#dom-title-text - fn Text(self) -> DOMString { + fn Text(&self) -> DOMString { let node = NodeCast::from_ref(self); let mut content = String::new(); for child in node.children() { @@ -64,15 +62,15 @@ impl<'a> HTMLTitleElementMethods for &'a HTMLTitleElement { } // https://www.whatwg.org/html/#dom-title-text - fn SetText(self, value: DOMString) { + fn SetText(&self, value: DOMString) { let node = NodeCast::from_ref(self); node.SetTextContent(Some(value)) } } -impl<'a> VirtualMethods for &'a HTMLTitleElement { +impl VirtualMethods for HTMLTitleElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { - let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self); + let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } @@ -80,14 +78,14 @@ impl<'a> VirtualMethods for &'a HTMLTitleElement { if let Some(ref s) = self.super_type() { s.children_changed(mutation); } - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); if node.is_in_doc() { node.owner_doc().title_changed(); } } fn bind_to_tree(&self, is_in_doc: bool) { - let node = NodeCast::from_ref(*self); + let node = NodeCast::from_ref(self); if is_in_doc { let document = node.owner_doc(); document.r().title_changed(); diff --git a/components/script/dom/htmltrackelement.rs b/components/script/dom/htmltrackelement.rs index df3582483ec..63d7efbc630 100644 --- a/components/script/dom/htmltrackelement.rs +++ b/components/script/dom/htmltrackelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLTrackElement { htmlelement: HTMLElement, } @@ -41,4 +40,3 @@ impl HTMLTrackElement { Node::reflect_node(box element, document, HTMLTrackElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlulistelement.rs b/components/script/dom/htmlulistelement.rs index 0ec7be9d5ca..a8c6102e5ae 100644 --- a/components/script/dom/htmlulistelement.rs +++ b/components/script/dom/htmlulistelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLUListElement { htmlelement: HTMLElement } @@ -41,4 +40,3 @@ impl HTMLUListElement { Node::reflect_node(box element, document, HTMLUListElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlunknownelement.rs b/components/script/dom/htmlunknownelement.rs index a4f35a35534..43b0c2834b8 100644 --- a/components/script/dom/htmlunknownelement.rs +++ b/components/script/dom/htmlunknownelement.rs @@ -13,7 +13,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLUnknownElement { htmlelement: HTMLElement } @@ -44,4 +43,3 @@ impl HTMLUnknownElement { Node::reflect_node(box element, document, HTMLUnknownElementBinding::Wrap) } } - diff --git a/components/script/dom/htmlvideoelement.rs b/components/script/dom/htmlvideoelement.rs index 1ccd7f8eb0c..b97d853b700 100644 --- a/components/script/dom/htmlvideoelement.rs +++ b/components/script/dom/htmlvideoelement.rs @@ -14,7 +14,6 @@ use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct HTMLVideoElement { htmlmediaelement: HTMLMediaElement } @@ -44,4 +43,3 @@ impl HTMLVideoElement { Node::reflect_node(box element, document, HTMLVideoElementBinding::Wrap) } } - diff --git a/components/script/dom/imagedata.rs b/components/script/dom/imagedata.rs index 88ed652f752..18c6f25ff8e 100644 --- a/components/script/dom/imagedata.rs +++ b/components/script/dom/imagedata.rs @@ -18,7 +18,6 @@ use std::vec::Vec; #[dom_struct] #[allow(raw_pointer_derive)] -#[derive(HeapSizeOf)] pub struct ImageData { reflector_: Reflector, width: u32, @@ -50,16 +49,9 @@ impl ImageData { reflect_dom_object(imagedata, global, ImageDataBinding::Wrap) } -} -pub trait ImageDataHelpers { - fn get_data_array(self, global: &GlobalRef) -> Vec; - fn get_size(self) -> Size2D; -} - -impl<'a> ImageDataHelpers for &'a ImageData { #[allow(unsafe_code)] - fn get_data_array(self, global: &GlobalRef) -> Vec { + pub fn get_data_array(&self, global: &GlobalRef) -> Vec { unsafe { let cx = global.get_cx(); let data: *const uint8_t = JS_GetUint8ClampedArrayData(self.Data(cx), ptr::null()) as *const uint8_t; @@ -68,24 +60,24 @@ impl<'a> ImageDataHelpers for &'a ImageData { } } - fn get_size(self) -> Size2D { + pub fn get_size(&self) -> Size2D { Size2D::new(self.Width() as i32, self.Height() as i32) } } -impl<'a> ImageDataMethods for &'a ImageData { +impl ImageDataMethods for ImageData { // https://html.spec.whatwg.org/multipage/#dom-imagedata-width - fn Width(self) -> u32 { + fn Width(&self) -> u32 { self.width } // https://html.spec.whatwg.org/multipage/#dom-imagedata-height - fn Height(self) -> u32 { + fn Height(&self) -> u32 { self.height } // https://html.spec.whatwg.org/multipage/#dom-imagedata-data - fn Data(self, _: *mut JSContext) -> *mut JSObject { + fn Data(&self, _: *mut JSContext) -> *mut JSObject { self.data.get() } } diff --git a/components/script/dom/keyboardevent.rs b/components/script/dom/keyboardevent.rs index 1dbbcb97a2b..1aed28da355 100644 --- a/components/script/dom/keyboardevent.rs +++ b/components/script/dom/keyboardevent.rs @@ -24,7 +24,6 @@ use std::cell::{RefCell, Cell}; no_jsmanaged_fields!(Key); #[dom_struct] -#[derive(HeapSizeOf)] pub struct KeyboardEvent { uievent: UIEvent, key: Cell>, @@ -136,17 +135,13 @@ impl KeyboardEvent { } } -pub trait KeyboardEventHelpers { - fn get_key(self) -> Option; - fn get_key_modifiers(self) -> KeyModifiers; -} -impl<'a> KeyboardEventHelpers for &'a KeyboardEvent { - fn get_key(self) -> Option { +impl KeyboardEvent { + pub fn get_key(&self) -> Option { self.key.get().clone() } - fn get_key_modifiers(self) -> KeyModifiers { + pub fn get_key_modifiers(&self) -> KeyModifiers { let mut result = KeyModifiers::empty(); if self.shift.get() { result = result | constellation_msg::SHIFT; @@ -762,9 +757,9 @@ impl KeyEventProperties { } } -impl<'a> KeyboardEventMethods for &'a KeyboardEvent { +impl KeyboardEventMethods for KeyboardEvent { // https://w3c.github.io/uievents/#widl-KeyboardEvent-initKeyboardEvent - fn InitKeyboardEvent(self, + fn InitKeyboardEvent(&self, typeArg: DOMString, canBubbleArg: bool, cancelableArg: bool, @@ -787,52 +782,52 @@ impl<'a> KeyboardEventMethods for &'a KeyboardEvent { } // https://w3c.github.io/uievents/#widl-KeyboardEvent-key - fn Key(self) -> DOMString { + fn Key(&self) -> DOMString { self.key_string.borrow().clone() } // https://w3c.github.io/uievents/#widl-KeyboardEvent-code - fn Code(self) -> DOMString { + fn Code(&self) -> DOMString { self.code.borrow().clone() } // https://w3c.github.io/uievents/#widl-KeyboardEvent-location - fn Location(self) -> u32 { + fn Location(&self) -> u32 { self.location.get() } // https://w3c.github.io/uievents/#widl-KeyboardEvent-ctrlKey - fn CtrlKey(self) -> bool { + fn CtrlKey(&self) -> bool { self.ctrl.get() } // https://w3c.github.io/uievents/#widl-KeyboardEvent-shiftKey - fn ShiftKey(self) -> bool { + fn ShiftKey(&self) -> bool { self.shift.get() } // https://w3c.github.io/uievents/#widl-KeyboardEvent-altKey - fn AltKey(self) -> bool { + fn AltKey(&self) -> bool { self.alt.get() } // https://w3c.github.io/uievents/#widl-KeyboardEvent-metaKey - fn MetaKey(self) -> bool { + fn MetaKey(&self) -> bool { self.meta.get() } // https://w3c.github.io/uievents/#widl-KeyboardEvent-repeat - fn Repeat(self) -> bool { + fn Repeat(&self) -> bool { self.repeat.get() } // https://w3c.github.io/uievents/#widl-KeyboardEvent-isComposing - fn IsComposing(self) -> bool { + fn IsComposing(&self) -> bool { self.is_composing.get() } // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#widl-KeyboardEvent-getModifierState - fn GetModifierState(self, keyArg: DOMString) -> bool { + fn GetModifierState(&self, keyArg: DOMString) -> bool { match &*keyArg { "Ctrl" => self.CtrlKey(), "Alt" => self.AltKey(), @@ -845,17 +840,17 @@ impl<'a> KeyboardEventMethods for &'a KeyboardEvent { } // https://w3c.github.io/uievents/#widl-KeyboardEvent-charCode - fn CharCode(self) -> u32 { + fn CharCode(&self) -> u32 { self.char_code.get().unwrap_or(0) } // https://w3c.github.io/uievents/#widl-KeyboardEvent-keyCode - fn KeyCode(self) -> u32 { + fn KeyCode(&self) -> u32 { self.key_code.get() } // https://w3c.github.io/uievents/#widl-KeyboardEvent-which - fn Which(self) -> u32 { + fn Which(&self) -> u32 { self.char_code.get().unwrap_or(self.KeyCode()) } } diff --git a/components/script/dom/location.rs b/components/script/dom/location.rs index e17bd16a513..8b5cf37965e 100644 --- a/components/script/dom/location.rs +++ b/components/script/dom/location.rs @@ -4,19 +4,18 @@ use dom::bindings::codegen::Bindings::LocationBinding; use dom::bindings::codegen::Bindings::LocationBinding::LocationMethods; +use dom::bindings::error::ErrorResult; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::str::USVString; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::urlhelper::UrlHelper; use dom::window::Window; -use dom::window::WindowHelpers; use url::{Url, UrlParser}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct Location { reflector_: Reflector, window: JS, @@ -35,11 +34,23 @@ impl Location { GlobalRef::Window(window), LocationBinding::Wrap) } + + fn get_url(&self) -> Url { + self.window.root().get_url() + } + + fn set_url_component(&self, value: USVString, + setter: fn(&mut Url, USVString)) { + let window = self.window.root(); + let mut url = window.get_url(); + setter(&mut url, value); + window.load_url(url); + } } -impl<'a> LocationMethods for &'a Location { +impl LocationMethods for Location { // https://html.spec.whatwg.org/multipage/#dom-location-assign - fn Assign(self, url: DOMString) { + fn Assign(&self, url: DOMString) { let window = self.window.root(); // TODO: per spec, we should use the _API base URL_ specified by the // _entry settings object_. @@ -50,68 +61,111 @@ impl<'a> LocationMethods for &'a Location { } // https://url.spec.whatwg.org/#dom-urlutils-hash - fn Hash(self) -> USVString { + fn Hash(&self) -> USVString { UrlHelper::Hash(&self.get_url()) } - // https://url.spec.whatwg.org/#dom-urlutils-href - fn Href(self) -> USVString { - UrlHelper::Href(&self.get_url()) + // https://url.spec.whatwg.org/#dom-urlutils-hash + fn SetHash(&self, value: USVString) { + self.set_url_component(value, UrlHelper::SetHash); } // https://url.spec.whatwg.org/#dom-urlutils-host - fn Host(self) -> USVString { + fn Host(&self) -> USVString { UrlHelper::Host(&self.get_url()) } + // https://url.spec.whatwg.org/#dom-urlutils-host + fn SetHost(&self, value: USVString) { + self.set_url_component(value, UrlHelper::SetHost); + } + // https://url.spec.whatwg.org/#dom-urlutils-hostname - fn Hostname(self) -> USVString { + fn Hostname(&self) -> USVString { UrlHelper::Hostname(&self.get_url()) } + // https://url.spec.whatwg.org/#dom-urlutils-hostname + fn SetHostname(&self, value: USVString) { + self.set_url_component(value, UrlHelper::SetHostname); + } + + // https://url.spec.whatwg.org/#dom-urlutils-href + fn Href(&self) -> USVString { + UrlHelper::Href(&self.get_url()) + } + + // https://url.spec.whatwg.org/#dom-urlutils-href + fn SetHref(&self, value: USVString) -> ErrorResult { + let window = self.window.root(); + if let Ok(url) = UrlParser::new().base_url(&window.get_url()).parse(&value.0) { + window.load_url(url); + }; + Ok(()) + } + // https://url.spec.whatwg.org/#dom-urlutils-password - fn Password(self) -> USVString { + fn Password(&self) -> USVString { UrlHelper::Password(&self.get_url()) } + // https://url.spec.whatwg.org/#dom-urlutils-password + fn SetPassword(&self, value: USVString) { + self.set_url_component(value, UrlHelper::SetPassword); + } + // https://url.spec.whatwg.org/#dom-urlutils-pathname - fn Pathname(self) -> USVString { + fn Pathname(&self) -> USVString { UrlHelper::Pathname(&self.get_url()) } + // https://url.spec.whatwg.org/#dom-urlutils-pathname + fn SetPathname(&self, value: USVString) { + self.set_url_component(value, UrlHelper::SetPathname); + } + // https://url.spec.whatwg.org/#dom-urlutils-port - fn Port(self) -> USVString { + fn Port(&self) -> USVString { UrlHelper::Port(&self.get_url()) } + // https://url.spec.whatwg.org/#dom-urlutils-port + fn SetPort(&self, value: USVString) { + self.set_url_component(value, UrlHelper::SetPort); + } + // https://url.spec.whatwg.org/#dom-urlutils-protocol - fn Protocol(self) -> USVString { + fn Protocol(&self) -> USVString { UrlHelper::Protocol(&self.get_url()) } + // https://url.spec.whatwg.org/#dom-urlutils-protocol + fn SetProtocol(&self, value: USVString) { + self.set_url_component(value, UrlHelper::SetProtocol); + } + // https://url.spec.whatwg.org/#URLUtils-stringification-behavior - fn Stringifier(self) -> DOMString { + fn Stringifier(&self) -> DOMString { self.Href().0 } // https://url.spec.whatwg.org/#dom-urlutils-search - fn Search(self) -> USVString { + fn Search(&self) -> USVString { UrlHelper::Search(&self.get_url()) } + // https://url.spec.whatwg.org/#dom-urlutils-search + fn SetSearch(&self, value: USVString) { + self.set_url_component(value, UrlHelper::SetSearch); + } + // https://url.spec.whatwg.org/#dom-urlutils-username - fn Username(self) -> USVString { + fn Username(&self) -> USVString { UrlHelper::Username(&self.get_url()) } -} -trait PrivateLocationHelpers { - fn get_url(self) -> Url; -} - -impl<'a> PrivateLocationHelpers for &'a Location { - fn get_url(self) -> Url { - let window = self.window.root(); - window.r().get_url() + // https://url.spec.whatwg.org/#dom-urlutils-username + fn SetUsername(&self, value: USVString) { + self.set_url_component(value, UrlHelper::SetUsername); } } diff --git a/components/script/dom/macros.rs b/components/script/dom/macros.rs index c2becf46c48..bb8adc3dcef 100644 --- a/components/script/dom/macros.rs +++ b/components/script/dom/macros.rs @@ -5,9 +5,8 @@ #[macro_export] macro_rules! make_getter( ( $attr:ident, $htmlname:expr ) => ( - fn $attr(self) -> DOMString { + fn $attr(&self) -> DOMString { use dom::bindings::codegen::InheritTypes::ElementCast; - use dom::element::AttributeHandlers; use string_cache::Atom; let element = ElementCast::from_ref(self); element.get_string_attribute(&Atom::from_slice($htmlname)) @@ -21,9 +20,8 @@ macro_rules! make_getter( #[macro_export] macro_rules! make_bool_getter( ( $attr:ident, $htmlname:expr ) => ( - fn $attr(self) -> bool { + fn $attr(&self) -> bool { use dom::bindings::codegen::InheritTypes::ElementCast; - use dom::element::AttributeHandlers; use string_cache::Atom; let element = ElementCast::from_ref(self); // FIXME(pcwalton): Do this at compile time, not runtime. @@ -38,9 +36,8 @@ macro_rules! make_bool_getter( #[macro_export] macro_rules! make_uint_getter( ($attr:ident, $htmlname:expr, $default:expr) => ( - fn $attr(self) -> u32 { + fn $attr(&self) -> u32 { use dom::bindings::codegen::InheritTypes::ElementCast; - use dom::element::AttributeHandlers; use string_cache::Atom; let element = ElementCast::from_ref(self); // FIXME(pcwalton): Do this at compile time, not runtime. @@ -58,9 +55,8 @@ macro_rules! make_uint_getter( #[macro_export] macro_rules! make_url_getter( ( $attr:ident, $htmlname:expr ) => ( - fn $attr(self) -> DOMString { + fn $attr(&self) -> DOMString { use dom::bindings::codegen::InheritTypes::ElementCast; - use dom::element::AttributeHandlers; use string_cache::Atom; let element = ElementCast::from_ref(self); // FIXME(pcwalton): Do this at compile time, not runtime. @@ -76,10 +72,8 @@ macro_rules! make_url_getter( #[macro_export] macro_rules! make_url_or_base_getter( ( $attr:ident, $htmlname:expr ) => ( - fn $attr(self) -> DOMString { + fn $attr(&self) -> DOMString { use dom::bindings::codegen::InheritTypes::ElementCast; - use dom::element::AttributeHandlers; - use dom::window::WindowHelpers; use string_cache::Atom; let element = ElementCast::from_ref(self); let url = element.get_url_attribute(&Atom::from_slice($htmlname)); @@ -99,9 +93,8 @@ macro_rules! make_url_or_base_getter( #[macro_export] macro_rules! make_enumerated_getter( ( $attr:ident, $htmlname:expr, $default:expr, $(($choices: pat))|+) => ( - fn $attr(self) -> DOMString { + fn $attr(&self) -> DOMString { use dom::bindings::codegen::InheritTypes::ElementCast; - use dom::element::AttributeHandlers; use std::ascii::AsciiExt; use std::borrow::ToOwned; use string_cache::Atom; @@ -125,9 +118,8 @@ macro_rules! make_enumerated_getter( #[macro_export] macro_rules! make_setter( ( $attr:ident, $htmlname:expr ) => ( - fn $attr(self, value: DOMString) { + fn $attr(&self, value: DOMString) { use dom::bindings::codegen::InheritTypes::ElementCast; - use dom::element::AttributeHandlers; use string_cache::Atom; let element = ElementCast::from_ref(self); // FIXME(pcwalton): Do this at compile time, not at runtime. @@ -139,9 +131,8 @@ macro_rules! make_setter( #[macro_export] macro_rules! make_bool_setter( ( $attr:ident, $htmlname:expr ) => ( - fn $attr(self, value: bool) { + fn $attr(&self, value: bool) { use dom::bindings::codegen::InheritTypes::ElementCast; - use dom::element::AttributeHandlers; use string_cache::Atom; let element = ElementCast::from_ref(self); // FIXME(pcwalton): Do this at compile time, not at runtime. @@ -153,9 +144,8 @@ macro_rules! make_bool_setter( #[macro_export] macro_rules! make_uint_setter( ($attr:ident, $htmlname:expr, $default:expr) => ( - fn $attr(self, value: u32) { + fn $attr(&self, value: u32) { use dom::bindings::codegen::InheritTypes::ElementCast; - use dom::element::AttributeHandlers; use string_cache::Atom; let value = if value > 2147483647 { $default @@ -175,9 +165,8 @@ macro_rules! make_uint_setter( #[macro_export] macro_rules! make_limited_uint_setter( ($attr:ident, $htmlname:expr, $default:expr) => ( - fn $attr(self, value: u32) -> $crate::dom::bindings::error::ErrorResult { + fn $attr(&self, value: u32) -> $crate::dom::bindings::error::ErrorResult { use dom::bindings::codegen::InheritTypes::ElementCast; - use dom::element::AttributeHandlers; use string_cache::Atom; let value = if value == 0 { return Err($crate::dom::bindings::error::Error::IndexSize); @@ -203,9 +192,8 @@ macro_rules! make_limited_uint_setter( #[macro_export] macro_rules! make_atomic_setter( ( $attr:ident, $htmlname:expr ) => ( - fn $attr(self, value: DOMString) { + fn $attr(&self, value: DOMString) { use dom::bindings::codegen::InheritTypes::ElementCast; - use dom::element::AttributeHandlers; use string_cache::Atom; let element = ElementCast::from_ref(self); // FIXME(pcwalton): Do this at compile time, not at runtime. @@ -240,12 +228,12 @@ macro_rules! no_jsmanaged_fields( /// These are used to generate a event handler which has no special case. macro_rules! define_event_handler( ($handler: ident, $event_type: ident, $getter: ident, $setter: ident) => ( - fn $getter(self) -> Option<::std::rc::Rc<$handler>> { + fn $getter(&self) -> Option<::std::rc::Rc<$handler>> { let eventtarget = EventTargetCast::from_ref(self); eventtarget.get_event_handler_common(stringify!($event_type)) } - fn $setter(self, listener: Option<::std::rc::Rc<$handler>>) { + fn $setter(&self, listener: Option<::std::rc::Rc<$handler>>) { let eventtarget = EventTargetCast::from_ref(self); eventtarget.set_event_handler_common(stringify!($event_type), listener) } diff --git a/components/script/dom/messageevent.rs b/components/script/dom/messageevent.rs index a445dd4bcd9..57b185464bb 100644 --- a/components/script/dom/messageevent.rs +++ b/components/script/dom/messageevent.rs @@ -10,7 +10,7 @@ use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::utils::reflect_dom_object; -use dom::event::{Event, EventHelpers, EventTypeId}; +use dom::event::{Event, EventTypeId}; use dom::eventtarget::EventTarget; use util::str::DOMString; @@ -22,7 +22,6 @@ use std::borrow::ToOwned; use std::default::Default; #[dom_struct] -#[derive(HeapSizeOf)] pub struct MessageEvent { event: Event, data: Heap, @@ -90,20 +89,19 @@ impl MessageEvent { } } -impl<'a> MessageEventMethods for &'a MessageEvent { +impl MessageEventMethods for MessageEvent { // https://html.spec.whatwg.org/multipage/#dom-messageevent-data - fn Data(self, _cx: *mut JSContext) -> JSVal { + fn Data(&self, _cx: *mut JSContext) -> JSVal { self.data.get() } // https://html.spec.whatwg.org/multipage/#dom-messageevent-origin - fn Origin(self) -> DOMString { + fn Origin(&self) -> DOMString { self.origin.clone() } // https://html.spec.whatwg.org/multipage/#dom-messageevent-lasteventid - fn LastEventId(self) -> DOMString { + fn LastEventId(&self) -> DOMString { self.lastEventId.clone() } } - diff --git a/components/script/dom/mod.rs b/components/script/dom/mod.rs index 663d14784a6..e9bc0716217 100644 --- a/components/script/dom/mod.rs +++ b/components/script/dom/mod.rs @@ -109,16 +109,10 @@ //! Implementing methods for a DOM object //! ===================================== //! -//! XXX JSRef no longer exists - should we remove the *Helpers traits? -//! In order to ensure that DOM objects are rooted when they are called, we -//! require that all methods are implemented for `JSRef<'a, Foo>`. This means -//! that all methods are defined on traits. Conventionally, those traits are -//! called -//! //! * `dom::bindings::codegen::Bindings::FooBindings::FooMethods` for methods //! defined through IDL; -//! * `FooHelpers` for public methods; -//! * `PrivateFooHelpers` for private methods. +//! * `&self` public methods for public helpers; +//! * `&self` methods for private helpers. //! //! Accessing fields of a DOM object //! ================================ diff --git a/components/script/dom/mouseevent.rs b/components/script/dom/mouseevent.rs index 08cd4543e54..5fcd232826e 100644 --- a/components/script/dom/mouseevent.rs +++ b/components/script/dom/mouseevent.rs @@ -16,11 +16,10 @@ use dom::uievent::{UIEvent, UIEventTypeId}; use dom::window::Window; use std::cell::Cell; use std::default::Default; -use util::opts; +use util::prefs; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct MouseEvent { uievent: UIEvent, screen_x: Cell, @@ -115,54 +114,54 @@ impl MouseEvent { } } -impl<'a> MouseEventMethods for &'a MouseEvent { +impl MouseEventMethods for MouseEvent { // https://w3c.github.io/uievents/#widl-MouseEvent-screenX - fn ScreenX(self) -> i32 { + fn ScreenX(&self) -> i32 { self.screen_x.get() } // https://w3c.github.io/uievents/#widl-MouseEvent-screenY - fn ScreenY(self) -> i32 { + fn ScreenY(&self) -> i32 { self.screen_y.get() } // https://w3c.github.io/uievents/#widl-MouseEvent-clientX - fn ClientX(self) -> i32 { + fn ClientX(&self) -> i32 { self.client_x.get() } // https://w3c.github.io/uievents/#widl-MouseEvent-clientY - fn ClientY(self) -> i32 { + fn ClientY(&self) -> i32 { self.client_y.get() } // https://w3c.github.io/uievents/#widl-MouseEvent-ctrlKey - fn CtrlKey(self) -> bool { + fn CtrlKey(&self) -> bool { self.ctrl_key.get() } // https://w3c.github.io/uievents/#widl-MouseEvent-shiftKey - fn ShiftKey(self) -> bool { + fn ShiftKey(&self) -> bool { self.shift_key.get() } // https://w3c.github.io/uievents/#widl-MouseEvent-altKey - fn AltKey(self) -> bool { + fn AltKey(&self) -> bool { self.alt_key.get() } // https://w3c.github.io/uievents/#widl-MouseEvent-metaKey - fn MetaKey(self) -> bool { + fn MetaKey(&self) -> bool { self.meta_key.get() } // https://w3c.github.io/uievents/#widl-MouseEvent-button - fn Button(self) -> i16 { + fn Button(&self) -> i16 { self.button.get() } // https://w3c.github.io/uievents/#widl-MouseEvent-relatedTarget - fn GetRelatedTarget(self) -> Option> { + fn GetRelatedTarget(&self) -> Option> { self.related_target.get().map(Root::from_rooted) } @@ -171,8 +170,8 @@ impl<'a> MouseEventMethods for &'a MouseEvent { // - https://bugzilla.mozilla.org/show_bug.cgi?id=1186125 // This returns the same result as current gecko. // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which - fn Which(self) -> i32 { - if opts::experimental_enabled() { + fn Which(&self) -> i32 { + if prefs::get_pref("dom.mouseevent.which.enabled", false) { (self.button.get() + 1) as i32 } else { 0 @@ -180,7 +179,7 @@ impl<'a> MouseEventMethods for &'a MouseEvent { } // https://w3c.github.io/uievents/#widl-MouseEvent-initMouseEvent - fn InitMouseEvent(self, + fn InitMouseEvent(&self, typeArg: DOMString, canBubbleArg: bool, cancelableArg: bool, diff --git a/components/script/dom/namednodemap.rs b/components/script/dom/namednodemap.rs index 829e97519a2..6989706f64f 100644 --- a/components/script/dom/namednodemap.rs +++ b/components/script/dom/namednodemap.rs @@ -9,14 +9,13 @@ use dom::bindings::error::{Error, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::utils::{namespace_from_domstring, Reflector, reflect_dom_object}; -use dom::element::{AttributeHandlers, Element, ElementHelpers}; +use dom::element::Element; use dom::window::Window; use util::str::DOMString; use string_cache::Atom; #[dom_struct] -#[derive(HeapSizeOf)] pub struct NamedNodeMap { reflector_: Reflector, owner: JS, @@ -36,9 +35,9 @@ impl NamedNodeMap { } } -impl<'a> NamedNodeMapMethods for &'a NamedNodeMap { +impl NamedNodeMapMethods for NamedNodeMap { // https://dom.spec.whatwg.org/#dom-namednodemap-length - fn Length(self) -> u32 { + fn Length(&self) -> u32 { let owner = self.owner.root(); // FIXME(https://github.com/rust-lang/rust/issues/23338) let owner = owner.r(); @@ -47,7 +46,7 @@ impl<'a> NamedNodeMapMethods for &'a NamedNodeMap { } // https://dom.spec.whatwg.org/#dom-namednodemap-item - fn Item(self, index: u32) -> Option> { + fn Item(&self, index: u32) -> Option> { let owner = self.owner.root(); // FIXME(https://github.com/rust-lang/rust/issues/23338) let owner = owner.r(); @@ -56,7 +55,7 @@ impl<'a> NamedNodeMapMethods for &'a NamedNodeMap { } // https://dom.spec.whatwg.org/#dom-namednodemap-getnameditem - fn GetNamedItem(self, name: DOMString) -> Option> { + fn GetNamedItem(&self, name: DOMString) -> Option> { let owner = self.owner.root(); // FIXME(https://github.com/rust-lang/rust/issues/23338) let owner = owner.r(); @@ -64,7 +63,7 @@ impl<'a> NamedNodeMapMethods for &'a NamedNodeMap { } // https://dom.spec.whatwg.org/#dom-namednodemap-getnameditemns - fn GetNamedItemNS(self, namespace: Option, local_name: DOMString) + fn GetNamedItemNS(&self, namespace: Option, local_name: DOMString) -> Option> { let owner = self.owner.root(); // FIXME(https://github.com/rust-lang/rust/issues/23338) @@ -74,7 +73,7 @@ impl<'a> NamedNodeMapMethods for &'a NamedNodeMap { } // https://dom.spec.whatwg.org/#dom-namednodemap-removenameditem - fn RemoveNamedItem(self, name: DOMString) -> Fallible> { + fn RemoveNamedItem(&self, name: DOMString) -> Fallible> { let owner = self.owner.root(); // FIXME(https://github.com/rust-lang/rust/issues/23338) let owner = owner.r(); @@ -83,7 +82,7 @@ impl<'a> NamedNodeMapMethods for &'a NamedNodeMap { } // https://dom.spec.whatwg.org/#dom-namednodemap-removenameditemns - fn RemoveNamedItemNS(self, namespace: Option, local_name: DOMString) + fn RemoveNamedItemNS(&self, namespace: Option, local_name: DOMString) -> Fallible> { let owner = self.owner.root(); // FIXME(https://github.com/rust-lang/rust/issues/23338) @@ -93,20 +92,20 @@ impl<'a> NamedNodeMapMethods for &'a NamedNodeMap { } // https://dom.spec.whatwg.org/#dom-namednodemap-item - fn IndexedGetter(self, index: u32, found: &mut bool) -> Option> { + fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option> { let item = self.Item(index); *found = item.is_some(); item } // check-tidy: no specs after this line - fn NamedGetter(self, name: DOMString, found: &mut bool) -> Option> { + fn NamedGetter(&self, name: DOMString, found: &mut bool) -> Option> { let item = self.GetNamedItem(name); *found = item.is_some(); item } - fn SupportedPropertyNames(self) -> Vec { + fn SupportedPropertyNames(&self) -> Vec { // FIXME: unimplemented (https://github.com/servo/servo/issues/7273) vec![] } diff --git a/components/script/dom/navigator.rs b/components/script/dom/navigator.rs index c88e2bf3aa5..4f3f3d2c2da 100644 --- a/components/script/dom/navigator.rs +++ b/components/script/dom/navigator.rs @@ -12,7 +12,6 @@ use dom::window::Window; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct Navigator { reflector_: Reflector, } @@ -31,40 +30,39 @@ impl Navigator { } } -impl<'a> NavigatorMethods for &'a Navigator { +impl NavigatorMethods for Navigator { // https://html.spec.whatwg.org/multipage/#dom-navigator-product - fn Product(self) -> DOMString { + fn Product(&self) -> DOMString { navigatorinfo::Product() } // https://html.spec.whatwg.org/multipage/#dom-navigator-taintenabled - fn TaintEnabled(self) -> bool { + fn TaintEnabled(&self) -> bool { navigatorinfo::TaintEnabled() } // https://html.spec.whatwg.org/multipage/#dom-navigator-appname - fn AppName(self) -> DOMString { + fn AppName(&self) -> DOMString { navigatorinfo::AppName() } // https://html.spec.whatwg.org/multipage/#dom-navigator-appcodename - fn AppCodeName(self) -> DOMString { + fn AppCodeName(&self) -> DOMString { navigatorinfo::AppCodeName() } // https://html.spec.whatwg.org/multipage/#dom-navigator-platform - fn Platform(self) -> DOMString { + fn Platform(&self) -> DOMString { navigatorinfo::Platform() } // https://html.spec.whatwg.org/multipage/#dom-navigator-useragent - fn UserAgent(self) -> DOMString { + fn UserAgent(&self) -> DOMString { navigatorinfo::UserAgent() } // https://html.spec.whatwg.org/multipage/#dom-navigator-appversion - fn AppVersion(self) -> DOMString { + fn AppVersion(&self) -> DOMString { navigatorinfo::AppVersion() } } - diff --git a/components/script/dom/node.rs b/components/script/dom/node.rs index 12c671b70a8..f46cbc0be11 100644 --- a/components/script/dom/node.rs +++ b/components/script/dom/node.rs @@ -6,7 +6,7 @@ use devtools_traits::NodeInfo; use document_loader::DocumentLoader; -use dom::attr::{Attr, AttrHelpers}; +use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; @@ -32,20 +32,19 @@ use dom::bindings::js::{JS, LayoutJS, MutNullableHeap}; use dom::bindings::trace::JSTraceable; use dom::bindings::trace::RootedVec; use dom::bindings::utils::{namespace_from_domstring, Reflectable, reflect_dom_object}; -use dom::characterdata::{CharacterData, CharacterDataHelpers, CharacterDataTypeId}; +use dom::characterdata::{CharacterData, CharacterDataTypeId}; use dom::comment::Comment; -use dom::document::{Document, DocumentHelpers, IsHTMLDocument, DocumentSource}; +use dom::document::{Document, IsHTMLDocument, DocumentSource}; use dom::documentfragment::DocumentFragment; use dom::documenttype::DocumentType; -use dom::element::ElementHelpers; -use dom::element::{AttributeHandlers, Element, ElementCreator, ElementTypeId}; +use dom::element::{Element, ElementCreator, ElementTypeId}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElementTypeId; -use dom::nodelist::{NodeList, NodeListHelpers}; -use dom::processinginstruction::{ProcessingInstruction, ProcessingInstructionHelpers}; +use dom::nodelist::NodeList; +use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; use dom::virtualmethods::{VirtualMethods, vtable_for}; -use dom::window::{Window, WindowHelpers}; +use dom::window::Window; use euclid::rect::Rect; use layout_interface::{LayoutChan, Msg}; use parse::html::parse_html_fragment; @@ -78,7 +77,6 @@ use uuid; /// An HTML node. #[dom_struct] -#[derive(HeapSizeOf)] pub struct Node { /// The JavaScript reflector for this node. eventtarget: EventTarget, @@ -296,16 +294,12 @@ pub enum NodeTypeId { Element(ElementTypeId), } -trait PrivateNodeHelpers { - fn add_child(self, new_child: &Node, before: Option<&Node>); - fn remove_child(self, child: &Node); -} -impl<'a> PrivateNodeHelpers for &'a Node { +impl Node { /// Adds a new child to the end of this node's list of children. /// /// Fails unless `new_child` is disconnected from the tree. - fn add_child(self, new_child: &Node, before: Option<&Node>) { + fn add_child(&self, new_child: &Node, before: Option<&Node>) { assert!(new_child.parent_node.get().is_none()); assert!(new_child.prev_sibling.get().is_none()); assert!(new_child.next_sibling.get().is_none()); @@ -355,7 +349,7 @@ impl<'a> PrivateNodeHelpers for &'a Node { /// Removes the given child from this node's list of children. /// /// Fails unless `child` is a child of this node. - fn remove_child(self, child: &Node) { + fn remove_child(&self, child: &Node) { assert!(child.parent_node.get().map(Root::from_rooted).r() == Some(self)); let prev_sibling = child.GetPreviousSibling(); match prev_sibling { @@ -426,117 +420,9 @@ impl<'a> Iterator for QuerySelectorIterator { } } -pub trait NodeHelpers { - fn ancestors(self) -> AncestorIterator; - fn inclusive_ancestors(self) -> AncestorIterator; - fn children(self) -> NodeSiblingIterator; - fn rev_children(self) -> ReverseSiblingIterator; - fn child_elements(self) -> ChildElementIterator; - fn following_siblings(self) -> NodeSiblingIterator; - fn preceding_siblings(self) -> ReverseSiblingIterator; - fn following_nodes(self, root: &Node) -> FollowingNodeIterator; - fn preceding_nodes(self, root: &Node) -> PrecedingNodeIterator; - fn descending_last_children(self) -> LastChildIterator; - fn is_in_doc(self) -> bool; - fn is_inclusive_ancestor_of(self, parent: &Node) -> bool; - fn is_parent_of(self, child: &Node) -> bool; - fn type_id(self) -> NodeTypeId; - fn len(self) -> u32; - fn index(self) -> u32; - fn children_count(self) -> u32; - - fn owner_doc(self) -> Root; - fn set_owner_doc(self, document: &Document); - fn is_in_html_doc(self) -> bool; - - fn is_doctype(self) -> bool; - fn is_anchor_element(self) -> bool; - - fn get_flag(self, flag: NodeFlags) -> bool; - fn set_flag(self, flag: NodeFlags, value: bool); - - fn get_hover_state(self) -> bool; - fn set_hover_state(self, state: bool); - - fn get_focus_state(self) -> bool; - fn set_focus_state(self, state: bool); - - fn get_active_state(self) -> bool; - fn set_active_state(self, state: bool); - - fn get_disabled_state(self) -> bool; - fn set_disabled_state(self, state: bool); - - fn get_enabled_state(self) -> bool; - fn set_enabled_state(self, state: bool); - - fn get_has_changed(self) -> bool; - fn set_has_changed(self, state: bool); - - fn get_is_dirty(self) -> bool; - fn set_is_dirty(self, state: bool); - - fn get_has_dirty_siblings(self) -> bool; - fn set_has_dirty_siblings(self, state: bool); - - fn get_has_dirty_descendants(self) -> bool; - fn set_has_dirty_descendants(self, state: bool); - - /// Marks the given node as `IS_DIRTY`, its siblings as `HAS_DIRTY_SIBLINGS` (to deal with - /// sibling selectors), its ancestors as `HAS_DIRTY_DESCENDANTS`, and its descendants as - /// `IS_DIRTY`. If anything more than the node's style was damaged, this method also sets the - /// `HAS_CHANGED` flag. - fn dirty(self, damage: NodeDamage); - - /// Similar to `dirty`, but will always walk the ancestors to mark them dirty, - /// too. This is useful when a node is reparented. The node will frequently - /// already be marked as `changed` to skip double-dirties, but the ancestors - /// still need to be marked as `HAS_DIRTY_DESCENDANTS`. - /// - /// See #4170 - fn force_dirty_ancestors(self, damage: NodeDamage); - - fn dirty_impl(self, damage: NodeDamage, force_ancestors: bool); - - fn dump(self); - fn dump_indent(self, indent: u32); - fn debug_str(self) -> String; - - fn traverse_preorder(self) -> TreeIterator; - fn inclusively_following_siblings(self) -> NodeSiblingIterator; - fn inclusively_preceding_siblings(self) -> ReverseSiblingIterator; - - fn to_trusted_node_address(self) -> TrustedNodeAddress; - - fn get_bounding_content_box(self) -> Rect; - fn get_content_boxes(self) -> Vec>; - fn get_client_rect(self) -> Rect; - - fn before(self, nodes: Vec) -> ErrorResult; - fn after(self, nodes: Vec) -> ErrorResult; - fn replace_with(self, nodes: Vec) -> ErrorResult; - fn prepend(self, nodes: Vec) -> ErrorResult; - fn append(self, nodes: Vec) -> ErrorResult; - - fn query_selector(self, selectors: DOMString) -> Fallible>>; - #[allow(unsafe_code)] - unsafe fn query_selector_iter(self, selectors: DOMString) -> Fallible; - fn query_selector_all(self, selectors: DOMString) -> Fallible>; - - fn remove_self(self); - - fn get_unique_id(self) -> String; - fn summarize(self) -> NodeInfo; - - fn teardown(self); - - fn parse_fragment(self, markup: DOMString) -> Fallible>; - -} - -impl<'a> NodeHelpers for &'a Node { - fn teardown(self) { +impl Node { + pub fn teardown(&self) { self.layout_data.dispose(self); for kid in self.children() { kid.r().teardown(); @@ -544,12 +430,12 @@ impl<'a> NodeHelpers for &'a Node { } /// Dumps the subtree rooted at this node, for debugging. - fn dump(self) { + pub fn dump(&self) { self.dump_indent(0); } /// Dumps the node tree, for debugging, with indentation. - fn dump_indent(self, indent: u32) { + pub fn dump_indent(&self, indent: u32) { let mut s = String::new(); for _ in 0..indent { s.push_str(" "); @@ -565,21 +451,21 @@ impl<'a> NodeHelpers for &'a Node { } /// Returns a string that describes this node. - fn debug_str(self) -> String { + pub fn debug_str(&self) -> String { format!("{:?}", self.type_id) } - fn is_in_doc(self) -> bool { + pub fn is_in_doc(&self) -> bool { self.flags.get().contains(IS_IN_DOC) } /// Returns the type ID of this node. Fails if this node is borrowed mutably. - fn type_id(self) -> NodeTypeId { + pub fn type_id(&self) -> NodeTypeId { self.type_id } // https://dom.spec.whatwg.org/#concept-node-length - fn len(self) -> u32 { + pub fn len(&self) -> u32 { match self.type_id { NodeTypeId::DocumentType => 0, NodeTypeId::CharacterData(_) => { @@ -590,29 +476,29 @@ impl<'a> NodeHelpers for &'a Node { } // https://dom.spec.whatwg.org/#concept-tree-index - fn index(self) -> u32 { + pub fn index(&self) -> u32 { self.preceding_siblings().count() as u32 } - fn children_count(self) -> u32 { + pub fn children_count(&self) -> u32 { self.children_count.get() } #[inline] - fn is_anchor_element(self) -> bool { + pub fn is_anchor_element(&self) -> bool { self.type_id == NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) } #[inline] - fn is_doctype(self) -> bool { + pub fn is_doctype(&self) -> bool { self.type_id == NodeTypeId::DocumentType } - fn get_flag(self, flag: NodeFlags) -> bool { + pub fn get_flag(&self, flag: NodeFlags) -> bool { self.flags.get().contains(flag) } - fn set_flag(self, flag: NodeFlags, value: bool) { + pub fn set_flag(&self, flag: NodeFlags, value: bool) { let mut flags = self.flags.get(); if value { @@ -624,90 +510,90 @@ impl<'a> NodeHelpers for &'a Node { self.flags.set(flags); } - fn get_hover_state(self) -> bool { + pub fn get_hover_state(&self) -> bool { self.get_flag(IN_HOVER_STATE) } - fn set_hover_state(self, state: bool) { + pub fn set_hover_state(&self, state: bool) { self.set_flag(IN_HOVER_STATE, state); self.dirty(NodeDamage::NodeStyleDamaged); } - fn get_focus_state(self) -> bool { + pub fn get_focus_state(&self) -> bool { self.get_flag(IN_FOCUS_STATE) } - fn set_focus_state(self, state: bool) { + pub fn set_focus_state(&self, state: bool) { self.set_flag(IN_FOCUS_STATE, state); self.dirty(NodeDamage::NodeStyleDamaged); } - fn get_active_state(self) -> bool { + pub fn get_active_state(&self) -> bool { self.get_flag(IN_ACTIVE_STATE) } - fn set_active_state(self, state: bool) { + pub fn set_active_state(&self, state: bool) { self.set_flag(IN_ACTIVE_STATE, state); self.dirty(NodeDamage::NodeStyleDamaged); } - fn get_disabled_state(self) -> bool { + pub fn get_disabled_state(&self) -> bool { self.get_flag(IN_DISABLED_STATE) } - fn set_disabled_state(self, state: bool) { + pub fn set_disabled_state(&self, state: bool) { self.set_flag(IN_DISABLED_STATE, state) } - fn get_enabled_state(self) -> bool { + pub fn get_enabled_state(&self) -> bool { self.get_flag(IN_ENABLED_STATE) } - fn set_enabled_state(self, state: bool) { + pub fn set_enabled_state(&self, state: bool) { self.set_flag(IN_ENABLED_STATE, state) } - fn get_has_changed(self) -> bool { + pub fn get_has_changed(&self) -> bool { self.get_flag(HAS_CHANGED) } - fn set_has_changed(self, state: bool) { + pub fn set_has_changed(&self, state: bool) { self.set_flag(HAS_CHANGED, state) } - fn get_is_dirty(self) -> bool { + pub fn get_is_dirty(&self) -> bool { self.get_flag(IS_DIRTY) } - fn set_is_dirty(self, state: bool) { + pub fn set_is_dirty(&self, state: bool) { self.set_flag(IS_DIRTY, state) } - fn get_has_dirty_siblings(self) -> bool { + pub fn get_has_dirty_siblings(&self) -> bool { self.get_flag(HAS_DIRTY_SIBLINGS) } - fn set_has_dirty_siblings(self, state: bool) { + pub fn set_has_dirty_siblings(&self, state: bool) { self.set_flag(HAS_DIRTY_SIBLINGS, state) } - fn get_has_dirty_descendants(self) -> bool { + pub fn get_has_dirty_descendants(&self) -> bool { self.get_flag(HAS_DIRTY_DESCENDANTS) } - fn set_has_dirty_descendants(self, state: bool) { + pub fn set_has_dirty_descendants(&self, state: bool) { self.set_flag(HAS_DIRTY_DESCENDANTS, state) } - fn force_dirty_ancestors(self, damage: NodeDamage) { + pub fn force_dirty_ancestors(&self, damage: NodeDamage) { self.dirty_impl(damage, true) } - fn dirty(self, damage: NodeDamage) { + pub fn dirty(&self, damage: NodeDamage) { self.dirty_impl(damage, false) } - fn dirty_impl(self, damage: NodeDamage, force_ancestors: bool) { + pub fn dirty_impl(&self, damage: NodeDamage, force_ancestors: bool) { // 1. Dirty self. match damage { NodeDamage::NodeStyleDamaged => {} @@ -756,83 +642,83 @@ impl<'a> NodeHelpers for &'a Node { } /// Iterates over this node and all its descendants, in preorder. - fn traverse_preorder(self) -> TreeIterator { + pub fn traverse_preorder(&self) -> TreeIterator { TreeIterator::new(self) } - fn inclusively_following_siblings(self) -> NodeSiblingIterator { + pub fn inclusively_following_siblings(&self) -> NodeSiblingIterator { NodeSiblingIterator { current: Some(Root::from_ref(self)), } } - fn inclusively_preceding_siblings(self) -> ReverseSiblingIterator { + pub fn inclusively_preceding_siblings(&self) -> ReverseSiblingIterator { ReverseSiblingIterator { current: Some(Root::from_ref(self)), } } - fn is_inclusive_ancestor_of(self, parent: &Node) -> bool { + pub fn is_inclusive_ancestor_of(&self, parent: &Node) -> bool { self == parent || parent.ancestors().any(|ancestor| ancestor.r() == self) } - fn following_siblings(self) -> NodeSiblingIterator { + pub fn following_siblings(&self) -> NodeSiblingIterator { NodeSiblingIterator { current: self.GetNextSibling(), } } - fn preceding_siblings(self) -> ReverseSiblingIterator { + pub fn preceding_siblings(&self) -> ReverseSiblingIterator { ReverseSiblingIterator { current: self.GetPreviousSibling(), } } - fn following_nodes(self, root: &Node) -> FollowingNodeIterator { + pub fn following_nodes(&self, root: &Node) -> FollowingNodeIterator { FollowingNodeIterator { current: Some(Root::from_ref(self)), root: Root::from_ref(root), } } - fn preceding_nodes(self, root: &Node) -> PrecedingNodeIterator { + pub fn preceding_nodes(&self, root: &Node) -> PrecedingNodeIterator { PrecedingNodeIterator { current: Some(Root::from_ref(self)), root: Root::from_ref(root), } } - fn descending_last_children(self) -> LastChildIterator { + pub fn descending_last_children(&self) -> LastChildIterator { LastChildIterator { current: self.GetLastChild(), } } - fn is_parent_of(self, child: &Node) -> bool { + pub fn is_parent_of(&self, child: &Node) -> bool { match child.parent_node.get() { Some(ref parent) => parent.root().r() == self, None => false, } } - fn to_trusted_node_address(self) -> TrustedNodeAddress { + pub fn to_trusted_node_address(&self) -> TrustedNodeAddress { TrustedNodeAddress(&*self as *const Node as *const libc::c_void) } - fn get_bounding_content_box(self) -> Rect { + pub fn get_bounding_content_box(&self) -> Rect { window_from_node(self).r().content_box_query(self.to_trusted_node_address()) } - fn get_content_boxes(self) -> Vec> { + pub fn get_content_boxes(&self) -> Vec> { window_from_node(self).r().content_boxes_query(self.to_trusted_node_address()) } - fn get_client_rect(self) -> Rect { + pub fn get_client_rect(&self) -> Rect { window_from_node(self).r().client_rect_query(self.to_trusted_node_address()) } // https://dom.spec.whatwg.org/#dom-childnode-before - fn before(self, nodes: Vec) -> ErrorResult { + pub fn before(&self, nodes: Vec) -> ErrorResult { // Step 1. let parent = &self.parent_node; @@ -861,7 +747,7 @@ impl<'a> NodeHelpers for &'a Node { } // https://dom.spec.whatwg.org/#dom-childnode-after - fn after(self, nodes: Vec) -> ErrorResult { + pub fn after(&self, nodes: Vec) -> ErrorResult { // Step 1. let parent = &self.parent_node; @@ -884,7 +770,7 @@ impl<'a> NodeHelpers for &'a Node { } // https://dom.spec.whatwg.org/#dom-childnode-replacewith - fn replace_with(self, nodes: Vec) -> ErrorResult { + pub fn replace_with(&self, nodes: Vec) -> ErrorResult { match self.parent_node.get() { None => { // Step 1. @@ -901,7 +787,7 @@ impl<'a> NodeHelpers for &'a Node { } // https://dom.spec.whatwg.org/#dom-parentnode-prepend - fn prepend(self, nodes: Vec) -> ErrorResult { + pub fn prepend(&self, nodes: Vec) -> ErrorResult { // Step 1. let doc = self.owner_doc(); let node = try!(doc.r().node_from_nodes_and_strings(nodes)); @@ -911,7 +797,7 @@ impl<'a> NodeHelpers for &'a Node { } // https://dom.spec.whatwg.org/#dom-parentnode-append - fn append(self, nodes: Vec) -> ErrorResult { + pub fn append(&self, nodes: Vec) -> ErrorResult { // Step 1. let doc = self.owner_doc(); let node = try!(doc.r().node_from_nodes_and_strings(nodes)); @@ -920,7 +806,7 @@ impl<'a> NodeHelpers for &'a Node { } // https://dom.spec.whatwg.org/#dom-parentnode-queryselector - fn query_selector(self, selectors: DOMString) -> Fallible>> { + pub fn query_selector(&self, selectors: DOMString) -> Fallible>> { // Step 1. match parse_author_origin_selector_list_from_str(&selectors) { // Step 2. @@ -940,7 +826,7 @@ impl<'a> NodeHelpers for &'a Node { /// Be careful not to do anything which may manipulate the DOM tree whilst iterating, otherwise /// the iterator may be invalidated #[allow(unsafe_code)] - unsafe fn query_selector_iter(self, selectors: DOMString) + pub unsafe fn query_selector_iter(&self, selectors: DOMString) -> Fallible { // Step 1. match parse_author_origin_selector_list_from_str(&selectors) { @@ -957,49 +843,49 @@ impl<'a> NodeHelpers for &'a Node { // https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall #[allow(unsafe_code)] - fn query_selector_all(self, selectors: DOMString) -> Fallible> { + pub fn query_selector_all(&self, selectors: DOMString) -> Fallible> { let window = window_from_node(self); let iter = try!(unsafe { self.query_selector_iter(selectors) }); Ok(NodeList::new_simple_list(window.r(), iter)) } - fn ancestors(self) -> AncestorIterator { + pub fn ancestors(&self) -> AncestorIterator { AncestorIterator { current: self.GetParentNode() } } - fn inclusive_ancestors(self) -> AncestorIterator { + pub fn inclusive_ancestors(&self) -> AncestorIterator { AncestorIterator { current: Some(Root::from_ref(self)) } } - fn owner_doc(self) -> Root { + pub fn owner_doc(&self) -> Root { self.owner_doc.get().unwrap().root() } - fn set_owner_doc(self, document: &Document) { + pub fn set_owner_doc(&self, document: &Document) { self.owner_doc.set(Some(JS::from_ref(document))); } - fn is_in_html_doc(self) -> bool { + pub fn is_in_html_doc(&self) -> bool { self.owner_doc().r().is_html_document() } - fn children(self) -> NodeSiblingIterator { + pub fn children(&self) -> NodeSiblingIterator { NodeSiblingIterator { current: self.GetFirstChild(), } } - fn rev_children(self) -> ReverseSiblingIterator { + pub fn rev_children(&self) -> ReverseSiblingIterator { ReverseSiblingIterator { current: self.GetLastChild(), } } - fn child_elements(self) -> ChildElementIterator { + pub fn child_elements(&self) -> ChildElementIterator { fn to_temporary(node: Root) -> Option> { ElementCast::to_root(node) } @@ -1008,13 +894,13 @@ impl<'a> NodeHelpers for &'a Node { .peekable() } - fn remove_self(self) { + pub fn remove_self(&self) { if let Some(ref parent) = self.GetParentNode() { Node::remove(self, parent.r(), SuppressObserver::Unsuppressed); } } - fn get_unique_id(self) -> String { + pub fn get_unique_id(&self) -> String { if self.unique_id.borrow().is_empty() { let mut unique_id = self.unique_id.borrow_mut(); *unique_id = uuid::Uuid::new_v4().to_simple_string(); @@ -1022,7 +908,7 @@ impl<'a> NodeHelpers for &'a Node { self.unique_id.borrow().clone() } - fn summarize(self) -> NodeInfo { + pub fn summarize(&self) -> NodeInfo { NodeInfo { uniqueId: self.get_unique_id(), baseURI: self.BaseURI(), @@ -1058,7 +944,7 @@ impl<'a> NodeHelpers for &'a Node { } // https://dvcs.w3.org/hg/innerhtml/raw-file/tip/index.html#dfn-concept-parse-fragment - fn parse_fragment(self, markup: DOMString) -> Fallible> { + pub fn parse_fragment(&self, markup: DOMString) -> Fallible> { let context_node: &Node = NodeCast::from_ref(self); let context_document = document_from_node(self); let fragment = DocumentFragment::new(context_document.r()); @@ -1743,8 +1629,7 @@ impl Node { Node::adopt(node, &*parent.owner_doc()); } // Step 2. - let mut removed_nodes = RootedVec::new(); - removed_nodes.extend(parent.children().map(|child| JS::from_rooted(&child))); + let removed_nodes = parent.children().collect::>(); // Step 3. let mut added_nodes = RootedVec::new(); let added_nodes = if let Some(node) = node.as_ref() { @@ -2006,9 +1891,9 @@ impl Node { } } -impl<'a> NodeMethods for &'a Node { +impl NodeMethods for Node { // https://dom.spec.whatwg.org/#dom-node-nodetype - fn NodeType(self) -> u16 { + fn NodeType(&self) -> u16 { match self.type_id { NodeTypeId::CharacterData(CharacterDataTypeId::Text) => NodeConstants::TEXT_NODE, @@ -2028,7 +1913,7 @@ impl<'a> NodeMethods for &'a Node { } // https://dom.spec.whatwg.org/#dom-node-nodename - fn NodeName(self) -> DOMString { + fn NodeName(&self) -> DOMString { match self.type_id { NodeTypeId::Element(..) => { let elem: &Element = ElementCast::to_ref(self).unwrap(); @@ -2051,12 +1936,12 @@ impl<'a> NodeMethods for &'a Node { } // https://dom.spec.whatwg.org/#dom-node-baseuri - fn BaseURI(self) -> DOMString { + fn BaseURI(&self) -> DOMString { self.owner_doc().URL() } // https://dom.spec.whatwg.org/#dom-node-ownerdocument - fn GetOwnerDocument(self) -> Option> { + fn GetOwnerDocument(&self) -> Option> { match self.type_id { NodeTypeId::CharacterData(..) | NodeTypeId::Element(..) | @@ -2067,22 +1952,22 @@ impl<'a> NodeMethods for &'a Node { } // https://dom.spec.whatwg.org/#dom-node-parentnode - fn GetParentNode(self) -> Option> { + fn GetParentNode(&self) -> Option> { self.parent_node.get().map(Root::from_rooted) } // https://dom.spec.whatwg.org/#dom-node-parentelement - fn GetParentElement(self) -> Option> { + fn GetParentElement(&self) -> Option> { self.GetParentNode().and_then(ElementCast::to_root) } // https://dom.spec.whatwg.org/#dom-node-haschildnodes - fn HasChildNodes(self) -> bool { + fn HasChildNodes(&self) -> bool { self.first_child.get().is_some() } // https://dom.spec.whatwg.org/#dom-node-childnodes - fn ChildNodes(self) -> Root { + fn ChildNodes(&self) -> Root { self.child_list.or_init(|| { let doc = self.owner_doc(); let window = doc.r().window(); @@ -2091,39 +1976,39 @@ impl<'a> NodeMethods for &'a Node { } // https://dom.spec.whatwg.org/#dom-node-firstchild - fn GetFirstChild(self) -> Option> { + fn GetFirstChild(&self) -> Option> { self.first_child.get().map(Root::from_rooted) } // https://dom.spec.whatwg.org/#dom-node-lastchild - fn GetLastChild(self) -> Option> { + fn GetLastChild(&self) -> Option> { self.last_child.get().map(Root::from_rooted) } // https://dom.spec.whatwg.org/#dom-node-previoussibling - fn GetPreviousSibling(self) -> Option> { + fn GetPreviousSibling(&self) -> Option> { self.prev_sibling.get().map(Root::from_rooted) } // https://dom.spec.whatwg.org/#dom-node-nextsibling - fn GetNextSibling(self) -> Option> { + fn GetNextSibling(&self) -> Option> { self.next_sibling.get().map(Root::from_rooted) } // https://dom.spec.whatwg.org/#dom-node-nodevalue - fn GetNodeValue(self) -> Option { + fn GetNodeValue(&self) -> Option { CharacterDataCast::to_ref(self).map(|c| c.Data()) } // https://dom.spec.whatwg.org/#dom-node-nodevalue - fn SetNodeValue(self, val: Option) { + fn SetNodeValue(&self, val: Option) { if let NodeTypeId::CharacterData(..) = self.type_id { self.SetTextContent(val) } } // https://dom.spec.whatwg.org/#dom-node-textcontent - fn GetTextContent(self) -> Option { + fn GetTextContent(&self) -> Option { match self.type_id { NodeTypeId::DocumentFragment | NodeTypeId::Element(..) => { @@ -2142,7 +2027,7 @@ impl<'a> NodeMethods for &'a Node { } // https://dom.spec.whatwg.org/#dom-node-textcontent - fn SetTextContent(self, value: Option) { + fn SetTextContent(&self, value: Option) { let value = value.unwrap_or(String::new()); match self.type_id { NodeTypeId::DocumentFragment | @@ -2172,17 +2057,17 @@ impl<'a> NodeMethods for &'a Node { } // https://dom.spec.whatwg.org/#dom-node-insertbefore - fn InsertBefore(self, node: &Node, child: Option<&Node>) -> Fallible> { + fn InsertBefore(&self, node: &Node, child: Option<&Node>) -> Fallible> { Node::pre_insert(node, self, child) } // https://dom.spec.whatwg.org/#dom-node-appendchild - fn AppendChild(self, node: &Node) -> Fallible> { + fn AppendChild(&self, node: &Node) -> Fallible> { Node::pre_insert(node, self, None) } // https://dom.spec.whatwg.org/#concept-node-replace - fn ReplaceChild(self, node: &Node, child: &Node) -> Fallible> { + fn ReplaceChild(&self, node: &Node, child: &Node) -> Fallible> { // Step 1. match self.type_id { @@ -2318,13 +2203,13 @@ impl<'a> NodeMethods for &'a Node { } // https://dom.spec.whatwg.org/#dom-node-removechild - fn RemoveChild(self, node: &Node) + fn RemoveChild(&self, node: &Node) -> Fallible> { Node::pre_remove(node, self) } // https://dom.spec.whatwg.org/#dom-node-normalize - fn Normalize(self) { + fn Normalize(&self) { let mut prev_text: Option> = None; for child in self.children() { match TextCast::to_ref(child.r()) { @@ -2353,7 +2238,7 @@ impl<'a> NodeMethods for &'a Node { } // https://dom.spec.whatwg.org/#dom-node-clonenode - fn CloneNode(self, deep: bool) -> Root { + fn CloneNode(&self, deep: bool) -> Root { Node::clone(self, None, if deep { CloneChildrenFlag::CloneChildren } else { @@ -2362,7 +2247,7 @@ impl<'a> NodeMethods for &'a Node { } // https://dom.spec.whatwg.org/#dom-node-isequalnode - fn IsEqualNode(self, maybe_node: Option<&Node>) -> bool { + fn IsEqualNode(&self, maybe_node: Option<&Node>) -> bool { fn is_equal_doctype(node: &Node, other: &Node) -> bool { let doctype: &DocumentType = DocumentTypeCast::to_ref(node).unwrap(); let other_doctype: &DocumentType = DocumentTypeCast::to_ref(other).unwrap(); @@ -2447,7 +2332,7 @@ impl<'a> NodeMethods for &'a Node { } // https://dom.spec.whatwg.org/#dom-node-comparedocumentposition - fn CompareDocumentPosition(self, other: &Node) -> u16 { + fn CompareDocumentPosition(&self, other: &Node) -> u16 { if self == other { // step 2. 0 @@ -2501,7 +2386,7 @@ impl<'a> NodeMethods for &'a Node { } // https://dom.spec.whatwg.org/#dom-node-contains - fn Contains(self, maybe_other: Option<&Node>) -> bool { + fn Contains(&self, maybe_other: Option<&Node>) -> bool { match maybe_other { None => false, Some(other) => self.is_inclusive_ancestor_of(other) @@ -2509,7 +2394,7 @@ impl<'a> NodeMethods for &'a Node { } // https://dom.spec.whatwg.org/#dom-node-lookupprefix - fn LookupPrefix(self, namespace: Option) -> Option { + fn LookupPrefix(&self, namespace: Option) -> Option { let namespace = namespace_from_domstring(namespace); // Step 1. @@ -2535,7 +2420,7 @@ impl<'a> NodeMethods for &'a Node { } // https://dom.spec.whatwg.org/#dom-node-lookupnamespaceuri - fn LookupNamespaceURI(self, prefix: Option) -> Option { + fn LookupNamespaceURI(&self, prefix: Option) -> Option { // Step 1. let prefix = match prefix { Some(ref p) if p.is_empty() => None, @@ -2547,7 +2432,7 @@ impl<'a> NodeMethods for &'a Node { } // https://dom.spec.whatwg.org/#dom-node-isdefaultnamespace - fn IsDefaultNamespace(self, namespace: Option) -> bool { + fn IsDefaultNamespace(&self, namespace: Option) -> bool { // Step 1. let namespace = namespace_from_domstring(namespace); // Steps 2 and 3. @@ -2577,9 +2462,9 @@ pub fn window_from_node(derived: &T) -> Root document.r().window() } -impl<'a> VirtualMethods for &'a Node { +impl VirtualMethods for Node { fn super_type(&self) -> Option<&VirtualMethods> { - let eventtarget: &&EventTarget = EventTargetCast::from_borrowed_ref(self); + let eventtarget: &EventTarget = EventTargetCast::from_ref(self); Some(eventtarget as &VirtualMethods) } @@ -2608,14 +2493,9 @@ impl<'a> VirtualMethods for &'a Node { } } -pub trait DisabledStateHelpers { - fn check_ancestors_disabled_state_for_form_control(self); - fn check_parent_disabled_state_for_option(self); - fn check_disabled_attribute(self); -} -impl<'a> DisabledStateHelpers for &'a Node { - fn check_ancestors_disabled_state_for_form_control(self) { +impl Node { + pub fn check_ancestors_disabled_state_for_form_control(&self) { if self.get_disabled_state() { return; } for ancestor in self.ancestors() { let ancestor = ancestor; @@ -2642,7 +2522,7 @@ impl<'a> DisabledStateHelpers for &'a Node { } } - fn check_parent_disabled_state_for_option(self) { + pub fn check_parent_disabled_state_for_option(&self) { if self.get_disabled_state() { return; } if let Some(ref parent) = self.GetParentNode() { if parent.r().is_htmloptgroupelement() && parent.r().get_disabled_state() { @@ -2652,7 +2532,7 @@ impl<'a> DisabledStateHelpers for &'a Node { } } - fn check_disabled_attribute(self) { + pub fn check_disabled_attribute(&self) { let elem = ElementCast::to_ref(self).unwrap(); let has_disabled_attrib = elem.has_attribute(&atom!("disabled")); self.set_disabled_state(has_disabled_attrib); diff --git a/components/script/dom/nodeiterator.rs b/components/script/dom/nodeiterator.rs index d1194c1326a..e81262de32f 100644 --- a/components/script/dom/nodeiterator.rs +++ b/components/script/dom/nodeiterator.rs @@ -12,14 +12,13 @@ use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutHeap, Root}; use dom::bindings::utils::{Reflector, reflect_dom_object}; -use dom::document::{Document, DocumentHelpers}; -use dom::node::{Node, NodeHelpers}; +use dom::document::Document; +use dom::node::Node; use std::cell::Cell; use std::rc::Rc; #[dom_struct] -#[derive(HeapSizeOf)] pub struct NodeIterator { reflector_: Reflector, root_node: JS, @@ -67,19 +66,19 @@ impl NodeIterator { } } -impl<'a> NodeIteratorMethods for &'a NodeIterator { +impl NodeIteratorMethods for NodeIterator { // https://dom.spec.whatwg.org/#dom-nodeiterator-root - fn Root(self) -> Root { + fn Root(&self) -> Root { self.root_node.root() } // https://dom.spec.whatwg.org/#dom-nodeiterator-whattoshow - fn WhatToShow(self) -> u32 { + fn WhatToShow(&self) -> u32 { self.what_to_show } // https://dom.spec.whatwg.org/#dom-nodeiterator-filter - fn GetFilter(self) -> Option> { + fn GetFilter(&self) -> Option> { match self.filter { Filter::None => None, Filter::Callback(ref nf) => Some((*nf).clone()), @@ -88,17 +87,17 @@ impl<'a> NodeIteratorMethods for &'a NodeIterator { } // https://dom.spec.whatwg.org/#dom-nodeiterator-referencenode - fn ReferenceNode(self) -> Root { + fn ReferenceNode(&self) -> Root { self.reference_node.get().root() } // https://dom.spec.whatwg.org/#dom-nodeiterator-pointerbeforereferencenode - fn PointerBeforeReferenceNode(self) -> bool { + fn PointerBeforeReferenceNode(&self) -> bool { self.pointer_before_reference_node.get() } // https://dom.spec.whatwg.org/#dom-nodeiterator-nextnode - fn NextNode(self) -> Fallible>> { + fn NextNode(&self) -> Fallible>> { // https://dom.spec.whatwg.org/#concept-NodeIterator-traverse // Step 1. let node = self.reference_node.get().root(); @@ -142,7 +141,7 @@ impl<'a> NodeIteratorMethods for &'a NodeIterator { } // https://dom.spec.whatwg.org/#dom-nodeiterator-previousnode - fn PreviousNode(self) -> Fallible>> { + fn PreviousNode(&self) -> Fallible>> { // https://dom.spec.whatwg.org/#concept-NodeIterator-traverse // Step 1. let node = self.reference_node.get().root(); @@ -187,19 +186,15 @@ impl<'a> NodeIteratorMethods for &'a NodeIterator { } // https://dom.spec.whatwg.org/#dom-nodeiterator-detach - fn Detach(self) { + fn Detach(&self) { // This method intentionally left blank. } } -trait PrivateNodeIteratorHelpers { - fn accept_node(self, node: &Node) -> Fallible; - fn is_root_node(self, node: &Node) -> bool; -} -impl<'a> PrivateNodeIteratorHelpers for &'a NodeIterator { +impl NodeIterator { // https://dom.spec.whatwg.org/#concept-node-filter - fn accept_node(self, node: &Node) -> Fallible { + fn accept_node(&self, node: &Node) -> Fallible { // Step 1. let n = node.NodeType() - 1; // Step 2. @@ -213,10 +208,6 @@ impl<'a> PrivateNodeIteratorHelpers for &'a NodeIterator { Filter::Callback(ref callback) => callback.AcceptNode_(self, node, Rethrow) } } - - fn is_root_node(self, node: &Node) -> bool { - JS::from_ref(node) == self.root_node - } } diff --git a/components/script/dom/nodelist.rs b/components/script/dom/nodelist.rs index bcf941a6aa0..3e2bc5145c6 100644 --- a/components/script/dom/nodelist.rs +++ b/components/script/dom/nodelist.rs @@ -8,7 +8,7 @@ use dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::utils::{Reflector, reflect_dom_object}; -use dom::node::{ChildrenMutation, Node, NodeHelpers}; +use dom::node::{ChildrenMutation, Node}; use dom::window::Window; use std::cell::Cell; @@ -22,7 +22,6 @@ pub enum NodeListType { // https://dom.spec.whatwg.org/#interface-nodelist #[dom_struct] -#[derive(HeapSizeOf)] pub struct NodeList { reflector_: Reflector, list_type: NodeListType, @@ -53,9 +52,9 @@ impl NodeList { } } -impl<'a> NodeListMethods for &'a NodeList { +impl NodeListMethods for NodeList { // https://dom.spec.whatwg.org/#dom-nodelist-length - fn Length(self) -> u32 { + fn Length(&self) -> u32 { match self.list_type { NodeListType::Simple(ref elems) => elems.len() as u32, NodeListType::Children(ref list) => list.len(), @@ -63,7 +62,7 @@ impl<'a> NodeListMethods for &'a NodeList { } // https://dom.spec.whatwg.org/#dom-nodelist-item - fn Item(self, index: u32) -> Option> { + fn Item(&self, index: u32) -> Option> { match self.list_type { NodeListType::Simple(ref elems) => { elems.get(index as usize).map(|node| Root::from_rooted(*node)) @@ -73,19 +72,16 @@ impl<'a> NodeListMethods for &'a NodeList { } // https://dom.spec.whatwg.org/#dom-nodelist-item - fn IndexedGetter(self, index: u32, found: &mut bool) -> Option> { + fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option> { let item = self.Item(index); *found = item.is_some(); item } } -pub trait NodeListHelpers<'a> { - fn as_children_list(self) -> &'a ChildrenList; -} -impl<'a> NodeListHelpers<'a> for &'a NodeList { - fn as_children_list(self) -> &'a ChildrenList { +impl NodeList { + pub fn as_children_list(&self) -> &ChildrenList { if let NodeListType::Children(ref list) = self.list_type { list } else { @@ -219,7 +215,10 @@ impl ChildrenList { }, }; list.last_visited.set(Some(JS::from_ref(visited))); - } else { + } else if added.len() != 1 { + // The replaced child isn't the last visited one, and there are + // 0 or more than 1 nodes to replace it. Special care must be + // given to update the state of that ChildrenList. match (prev, next) { (Some(_), None) => {}, (None, Some(next)) => { diff --git a/components/script/dom/performance.rs b/components/script/dom/performance.rs index 71ed3b186ea..2d0a5990cdc 100644 --- a/components/script/dom/performance.rs +++ b/components/script/dom/performance.rs @@ -8,14 +8,13 @@ use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::num::Finite; use dom::bindings::utils::{Reflector, reflect_dom_object}; -use dom::performancetiming::{PerformanceTiming, PerformanceTimingHelpers}; +use dom::performancetiming::PerformanceTiming; use dom::window::Window; use time; pub type DOMHighResTimeStamp = Finite; #[dom_struct] -#[derive(HeapSizeOf)] pub struct Performance { reflector_: Reflector, timing: JS, @@ -44,17 +43,16 @@ impl Performance { } } -impl<'a> PerformanceMethods for &'a Performance { +impl PerformanceMethods for Performance { // https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/NavigationTiming/Overview.html#performance-timing-attribute - fn Timing(self) -> Root { + fn Timing(&self) -> Root { self.timing.root() } // https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/HighResolutionTime/Overview.html#dom-performance-now - fn Now(self) -> DOMHighResTimeStamp { + fn Now(&self) -> DOMHighResTimeStamp { let navStart = self.timing.root().r().NavigationStartPrecise(); let now = (time::precise_time_ns() as f64 - navStart) / 1000000 as f64; Finite::wrap(now) } } - diff --git a/components/script/dom/performancetiming.rs b/components/script/dom/performancetiming.rs index d1588f72927..9992f87f3c8 100644 --- a/components/script/dom/performancetiming.rs +++ b/components/script/dom/performancetiming.rs @@ -10,7 +10,6 @@ use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::window::Window; #[dom_struct] -#[derive(HeapSizeOf)] pub struct PerformanceTiming { reflector_: Reflector, navigationStart: u64, @@ -39,21 +38,17 @@ impl PerformanceTiming { } } -impl<'a> PerformanceTimingMethods for &'a PerformanceTiming { +impl PerformanceTimingMethods for PerformanceTiming { // https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/ // NavigationTiming/Overview.html#dom-performancetiming-navigationstart - fn NavigationStart(self) -> u64 { + fn NavigationStart(&self) -> u64 { self.navigationStart } } -pub trait PerformanceTimingHelpers { - fn NavigationStartPrecise(self) -> f64; -} -impl<'a> PerformanceTimingHelpers for &'a PerformanceTiming { - fn NavigationStartPrecise(self) -> f64 { +impl PerformanceTiming { + pub fn NavigationStartPrecise(&self) -> f64 { self.navigationStartPrecise } } - diff --git a/components/script/dom/processinginstruction.rs b/components/script/dom/processinginstruction.rs index 6b4ae05f592..d3c1e655490 100644 --- a/components/script/dom/processinginstruction.rs +++ b/components/script/dom/processinginstruction.rs @@ -14,7 +14,6 @@ use util::str::DOMString; /// An HTML processing instruction node. #[dom_struct] -#[derive(HeapSizeOf)] pub struct ProcessingInstruction { characterdata: CharacterData, target: DOMString, @@ -41,20 +40,16 @@ impl ProcessingInstruction { } } -pub trait ProcessingInstructionHelpers<'a> { - fn target(self) -> &'a DOMString; -} -impl<'a> ProcessingInstructionHelpers<'a> for &'a ProcessingInstruction { - fn target(self) -> &'a DOMString { +impl ProcessingInstruction { + pub fn target(&self) -> &DOMString { &self.target } } -impl<'a> ProcessingInstructionMethods for &'a ProcessingInstruction { +impl ProcessingInstructionMethods for ProcessingInstruction { // https://dom.spec.whatwg.org/#dom-processinginstruction-target - fn Target(self) -> DOMString { + fn Target(&self) -> DOMString { self.target.clone() } } - diff --git a/components/script/dom/progressevent.rs b/components/script/dom/progressevent.rs index 20af2b68d1c..b715330edae 100644 --- a/components/script/dom/progressevent.rs +++ b/components/script/dom/progressevent.rs @@ -14,7 +14,6 @@ use dom::event::{Event, EventTypeId, EventBubbles, EventCancelable}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct ProgressEvent { event: Event, length_computable: bool, @@ -53,29 +52,28 @@ impl ProgressEvent { type_: DOMString, init: &ProgressEventBinding::ProgressEventInit) -> Fallible> { - let bubbles = if init.parent.bubbles {EventBubbles::Bubbles} else {EventBubbles::DoesNotBubble}; - let cancelable = if init.parent.cancelable {EventCancelable::Cancelable} - else {EventCancelable::NotCancelable}; + let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble }; + let cancelable = if init.parent.cancelable { EventCancelable::Cancelable } + else { EventCancelable::NotCancelable }; let ev = ProgressEvent::new(global, type_, bubbles, cancelable, init.lengthComputable, init.loaded, init.total); Ok(ev) } } -impl<'a> ProgressEventMethods for &'a ProgressEvent { +impl ProgressEventMethods for ProgressEvent { // https://xhr.spec.whatwg.org/#dom-progressevent-lengthcomputable - fn LengthComputable(self) -> bool { + fn LengthComputable(&self) -> bool { self.length_computable } // https://xhr.spec.whatwg.org/#dom-progressevent-loaded - fn Loaded(self) -> u64 { + fn Loaded(&self) -> u64 { self.loaded } // https://xhr.spec.whatwg.org/#dom-progressevent-total - fn Total(self) -> u64 { + fn Total(&self) -> u64 { self.total } } - diff --git a/components/script/dom/range.rs b/components/script/dom/range.rs index c0e832e7ae4..d86c4e96951 100644 --- a/components/script/dom/range.rs +++ b/components/script/dom/range.rs @@ -17,16 +17,15 @@ use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root, RootedReference}; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::characterdata::CharacterDataTypeId; -use dom::document::{Document, DocumentHelpers}; +use dom::document::Document; use dom::documentfragment::DocumentFragment; -use dom::node::{Node, NodeHelpers, NodeTypeId}; +use dom::node::{Node, NodeTypeId}; use std::cell::RefCell; use std::cmp::{Ord, Ordering, PartialEq, PartialOrd}; use std::rc::Rc; #[dom_struct] -#[derive(HeapSizeOf)] pub struct Range { reflector_: Reflector, inner: Rc>, @@ -126,50 +125,47 @@ impl Range { } } -pub trait RangeHelpers<'a> { - fn inner(self) -> &'a Rc>; -} -impl<'a> RangeHelpers<'a> for &'a Range { - fn inner(self) -> &'a Rc> { +impl Range { + pub fn inner(&self) -> &Rc> { &self.inner } } -impl<'a> RangeMethods for &'a Range { +impl RangeMethods for Range { // https://dom.spec.whatwg.org/#dom-range-startcontainer - fn StartContainer(self) -> Root { + fn StartContainer(&self) -> Root { self.inner().borrow().start.node() } // https://dom.spec.whatwg.org/#dom-range-startoffset - fn StartOffset(self) -> u32 { + fn StartOffset(&self) -> u32 { self.inner().borrow().start.offset } // https://dom.spec.whatwg.org/#dom-range-endcontainer - fn EndContainer(self) -> Root { + fn EndContainer(&self) -> Root { self.inner().borrow().end.node() } // https://dom.spec.whatwg.org/#dom-range-endoffset - fn EndOffset(self) -> u32 { + fn EndOffset(&self) -> u32 { self.inner().borrow().end.offset } // https://dom.spec.whatwg.org/#dom-range-collapsed - fn Collapsed(self) -> bool { + fn Collapsed(&self) -> bool { let inner = self.inner().borrow(); inner.start == inner.end } // https://dom.spec.whatwg.org/#dom-range-commonancestorcontainer - fn CommonAncestorContainer(self) -> Root { + fn CommonAncestorContainer(&self) -> Root { self.inner().borrow().common_ancestor_container() } // https://dom.spec.whatwg.org/#dom-range-setstartnode-offset - fn SetStart(self, node: &Node, offset: u32) -> ErrorResult { + fn SetStart(&self, node: &Node, offset: u32) -> ErrorResult { if node.is_doctype() { // Step 1. Err(Error::InvalidNodeType) @@ -184,7 +180,7 @@ impl<'a> RangeMethods for &'a Range { } // https://dom.spec.whatwg.org/#dom-range-setendnode-offset - fn SetEnd(self, node: &Node, offset: u32) -> ErrorResult { + fn SetEnd(&self, node: &Node, offset: u32) -> ErrorResult { if node.is_doctype() { // Step 1. Err(Error::InvalidNodeType) @@ -199,46 +195,46 @@ impl<'a> RangeMethods for &'a Range { } // https://dom.spec.whatwg.org/#dom-range-setstartbeforenode - fn SetStartBefore(self, node: &Node) -> ErrorResult { + fn SetStartBefore(&self, node: &Node) -> ErrorResult { let parent = try!(node.GetParentNode().ok_or(Error::InvalidNodeType)); self.SetStart(parent.r(), node.index()) } // https://dom.spec.whatwg.org/#dom-range-setstartafternode - fn SetStartAfter(self, node: &Node) -> ErrorResult { + fn SetStartAfter(&self, node: &Node) -> ErrorResult { let parent = try!(node.GetParentNode().ok_or(Error::InvalidNodeType)); self.SetStart(parent.r(), node.index() + 1) } // https://dom.spec.whatwg.org/#dom-range-setendbeforenode - fn SetEndBefore(self, node: &Node) -> ErrorResult { + fn SetEndBefore(&self, node: &Node) -> ErrorResult { let parent = try!(node.GetParentNode().ok_or(Error::InvalidNodeType)); self.SetEnd(parent.r(), node.index()) } // https://dom.spec.whatwg.org/#dom-range-setendafternode - fn SetEndAfter(self, node: &Node) -> ErrorResult { + fn SetEndAfter(&self, node: &Node) -> ErrorResult { let parent = try!(node.GetParentNode().ok_or(Error::InvalidNodeType)); self.SetEnd(parent.r(), node.index() + 1) } // https://dom.spec.whatwg.org/#dom-range-collapsetostart - fn Collapse(self, to_start: bool) { + fn Collapse(&self, to_start: bool) { self.inner().borrow_mut().collapse(to_start); } // https://dom.spec.whatwg.org/#dom-range-selectnodenode - fn SelectNode(self, node: &Node) -> ErrorResult { + fn SelectNode(&self, node: &Node) -> ErrorResult { self.inner().borrow_mut().select_node(node) } // https://dom.spec.whatwg.org/#dom-range-selectnodecontentsnode - fn SelectNodeContents(self, node: &Node) -> ErrorResult { + fn SelectNodeContents(&self, node: &Node) -> ErrorResult { self.inner().borrow_mut().select_node_contents(node) } // https://dom.spec.whatwg.org/#dom-range-compareboundarypointshow-sourcerange - fn CompareBoundaryPoints(self, how: u16, source_range: &Range) + fn CompareBoundaryPoints(&self, how: u16, source_range: &Range) -> Fallible { if how > RangeConstants::END_TO_START { // Step 1. @@ -279,7 +275,7 @@ impl<'a> RangeMethods for &'a Range { } // https://dom.spec.whatwg.org/#dom-range-clonerange - fn CloneRange(self) -> Root { + fn CloneRange(&self) -> Root { let inner = self.inner().borrow(); let start = &inner.start; let end = &inner.end; @@ -290,7 +286,7 @@ impl<'a> RangeMethods for &'a Range { } // https://dom.spec.whatwg.org/#dom-range-ispointinrangenode-offset - fn IsPointInRange(self, node: &Node, offset: u32) -> Fallible { + fn IsPointInRange(&self, node: &Node, offset: u32) -> Fallible { match self.inner().borrow().compare_point(node, offset) { Ok(Ordering::Less) => Ok(false), Ok(Ordering::Equal) => Ok(true), @@ -304,7 +300,7 @@ impl<'a> RangeMethods for &'a Range { } // https://dom.spec.whatwg.org/#dom-range-comparepointnode-offset - fn ComparePoint(self, node: &Node, offset: u32) -> Fallible { + fn ComparePoint(&self, node: &Node, offset: u32) -> Fallible { self.inner().borrow().compare_point(node, offset).map(|order| { match order { Ordering::Less => -1, @@ -315,7 +311,7 @@ impl<'a> RangeMethods for &'a Range { } // https://dom.spec.whatwg.org/#dom-range-intersectsnode - fn IntersectsNode(self, node: &Node) -> bool { + fn IntersectsNode(&self, node: &Node) -> bool { let inner = self.inner().borrow(); let start = &inner.start; let start_node = start.node(); @@ -347,7 +343,7 @@ impl<'a> RangeMethods for &'a Range { // https://dom.spec.whatwg.org/#dom-range-clonecontents // https://dom.spec.whatwg.org/#concept-range-clone - fn CloneContents(self) -> Fallible> { + fn CloneContents(&self) -> Fallible> { let inner = self.inner.borrow(); let start = &inner.start; let end = &inner.end; @@ -456,7 +452,7 @@ impl<'a> RangeMethods for &'a Range { // https://dom.spec.whatwg.org/#dom-range-extractcontents // https://dom.spec.whatwg.org/#concept-range-extract - fn ExtractContents(self) -> Fallible> { + fn ExtractContents(&self) -> Fallible> { // Step 3. let (start_node, start_offset, end_node, end_offset) = { @@ -585,13 +581,13 @@ impl<'a> RangeMethods for &'a Range { } // https://dom.spec.whatwg.org/#dom-range-detach - fn Detach(self) { + fn Detach(&self) { // This method intentionally left blank. } // https://dom.spec.whatwg.org/#dom-range-insertnode // https://dom.spec.whatwg.org/#concept-range-insert - fn InsertNode(self, node: &Node) -> ErrorResult { + fn InsertNode(&self, node: &Node) -> ErrorResult { let (start_node, start_offset) = { let inner = self.inner().borrow(); let start = &inner.start; diff --git a/components/script/dom/screen.rs b/components/script/dom/screen.rs index 831fd393670..e38dc676afe 100644 --- a/components/script/dom/screen.rs +++ b/components/script/dom/screen.rs @@ -10,7 +10,6 @@ use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::window::Window; #[dom_struct] -#[derive(HeapSizeOf)] pub struct Screen { reflector_: Reflector, } @@ -29,15 +28,14 @@ impl Screen { } } -impl<'a> ScreenMethods for &'a Screen { +impl ScreenMethods for Screen { // https://drafts.csswg.org/cssom-view/#dom-screen-colordepth - fn ColorDepth(self) -> u32 { + fn ColorDepth(&self) -> u32 { 24 } // https://drafts.csswg.org/cssom-view/#dom-screen-pixeldepth - fn PixelDepth(self) -> u32 { + fn PixelDepth(&self) -> u32 { 24 } } - diff --git a/components/script/dom/servohtmlparser.rs b/components/script/dom/servohtmlparser.rs index 63cb459379f..75d060ddf29 100644 --- a/components/script/dom/servohtmlparser.rs +++ b/components/script/dom/servohtmlparser.rs @@ -8,13 +8,15 @@ use document_loader::LoadType; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::ServoHTMLParserBinding; +use dom::bindings::codegen::InheritTypes::NodeCast; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::refcounted::Trusted; use dom::bindings::trace::JSTraceable; use dom::bindings::utils::{Reflector, reflect_dom_object}; -use dom::document::{Document, DocumentHelpers}; +use dom::document::Document; use dom::node::{window_from_node, Node}; +use dom::text::Text; use dom::window::Window; use network_listener::PreInvoke; use parse::Parser; @@ -27,7 +29,7 @@ use encoding::all::UTF_8; use encoding::types::{Encoding, DecoderTrap}; use html5ever::tokenizer; use html5ever::tree_builder; -use html5ever::tree_builder::{TreeBuilder, TreeBuilderOpts}; +use html5ever::tree_builder::{NodeOrText, TreeBuilder, TreeBuilderOpts}; use hyper::header::ContentType; use hyper::mime::{Mime, TopLevel, SubLevel}; use js::jsapi::JSTracer; @@ -42,6 +44,19 @@ pub struct Sink { pub document: JS, } +impl Sink { + pub fn get_or_create(&self, child: NodeOrText>) -> Root { + match child { + NodeOrText::AppendNode(n) => n.root(), + NodeOrText::AppendText(t) => { + let doc = self.document.root(); + let text = Text::new(t.into(), &doc); + NodeCast::from_root(text) + } + } + } +} + /// FragmentContext is used only to pass this group of related values /// into functions. #[derive(Copy, Clone)] @@ -157,7 +172,6 @@ impl PreInvoke for ParserContext { } #[dom_struct] -#[derive(HeapSizeOf)] pub struct ServoHTMLParser { reflector_: Reflector, #[ignore_heap_size_of = "Defined in html5ever"] @@ -273,16 +287,9 @@ impl ServoHTMLParser { } } -trait PrivateServoHTMLParserHelpers { - /// Synchronously run the tokenizer parse loop until explicitly suspended or - /// the tokenizer runs out of input. - fn parse_sync(self); - /// Retrieve the window object associated with this parser. - fn window(self) -> Root; -} -impl<'a> PrivateServoHTMLParserHelpers for &'a ServoHTMLParser { - fn parse_sync(self) { +impl ServoHTMLParser { + fn parse_sync(&self) { let mut first = true; // This parser will continue to parse while there is either pending input or @@ -315,28 +322,20 @@ impl<'a> PrivateServoHTMLParserHelpers for &'a ServoHTMLParser { } } - fn window(self) -> Root { + fn window(&self) -> Root { let doc = self.document.root(); window_from_node(doc.r()) } } -pub trait ServoHTMLParserHelpers { - /// Cause the parser to interrupt next time the tokenizer reaches a quiescent state. - /// No further parsing will occur after that point until the `resume` method is called. - /// Panics if the parser is already suspended. - fn suspend(self); - /// Immediately resume a suspended parser. Panics if the parser is not suspended. - fn resume(self); -} -impl<'a> ServoHTMLParserHelpers for &'a ServoHTMLParser { - fn suspend(self) { +impl ServoHTMLParser { + pub fn suspend(&self) { assert!(!self.suspended.get()); self.suspended.set(true); } - fn resume(self) { + pub fn resume(&self) { assert!(self.suspended.get()); self.suspended.set(false); self.parse_sync(); diff --git a/components/script/dom/storage.rs b/components/script/dom/storage.rs index 6ee0d3c9ccd..a749663d945 100644 --- a/components/script/dom/storage.rs +++ b/components/script/dom/storage.rs @@ -9,10 +9,9 @@ use dom::bindings::global::{GlobalRef, GlobalField}; use dom::bindings::js::{Root, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::bindings::utils::{Reflector, reflect_dom_object}; -use dom::event::{EventHelpers, EventBubbles, EventCancelable}; +use dom::event::{EventBubbles, EventCancelable}; use dom::storageevent::StorageEvent; use dom::urlhelper::UrlHelper; -use dom::window::WindowHelpers; use ipc_channel::ipc; use net_traits::storage_task::{StorageTask, StorageTaskMsg, StorageType}; use page::IterablePage; @@ -23,7 +22,6 @@ use url::Url; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct Storage { reflector_: Reflector, global: GlobalField, @@ -57,9 +55,9 @@ impl Storage { } -impl<'a> StorageMethods for &'a Storage { +impl StorageMethods for Storage { // https://html.spec.whatwg.org/multipage/#dom-storage-length - fn Length(self) -> u32 { + fn Length(&self) -> u32 { let (sender, receiver) = ipc::channel().unwrap(); self.get_storage_task().send(StorageTaskMsg::Length(sender, self.get_url(), self.storage_type)).unwrap(); @@ -67,7 +65,7 @@ impl<'a> StorageMethods for &'a Storage { } // https://html.spec.whatwg.org/multipage/#dom-storage-key - fn Key(self, index: u32) -> Option { + fn Key(&self, index: u32) -> Option { let (sender, receiver) = ipc::channel().unwrap(); self.get_storage_task().send(StorageTaskMsg::Key(sender, self.get_url(), self.storage_type, index)).unwrap(); @@ -75,7 +73,7 @@ impl<'a> StorageMethods for &'a Storage { } // https://html.spec.whatwg.org/multipage/#dom-storage-getitem - fn GetItem(self, name: DOMString) -> Option { + fn GetItem(&self, name: DOMString) -> Option { let (sender, receiver) = ipc::channel().unwrap(); let msg = StorageTaskMsg::GetItem(sender, self.get_url(), self.storage_type, name); @@ -84,7 +82,7 @@ impl<'a> StorageMethods for &'a Storage { } // https://html.spec.whatwg.org/multipage/#dom-storage-setitem - fn SetItem(self, name: DOMString, value: DOMString) { + fn SetItem(&self, name: DOMString, value: DOMString) { let (sender, receiver) = ipc::channel().unwrap(); let msg = StorageTaskMsg::SetItem(sender, self.get_url(), self.storage_type, name.clone(), value.clone()); @@ -96,7 +94,7 @@ impl<'a> StorageMethods for &'a Storage { } // https://html.spec.whatwg.org/multipage/#dom-storage-removeitem - fn RemoveItem(self, name: DOMString) { + fn RemoveItem(&self, name: DOMString) { let (sender, receiver) = ipc::channel().unwrap(); let msg = StorageTaskMsg::RemoveItem(sender, self.get_url(), self.storage_type, name.clone()); @@ -107,7 +105,7 @@ impl<'a> StorageMethods for &'a Storage { } // https://html.spec.whatwg.org/multipage/#dom-storage-clear - fn Clear(self) { + fn Clear(&self) { let (sender, receiver) = ipc::channel().unwrap(); self.get_storage_task().send(StorageTaskMsg::Clear(sender, self.get_url(), self.storage_type)).unwrap(); @@ -117,38 +115,34 @@ impl<'a> StorageMethods for &'a Storage { } // check-tidy: no specs after this line - fn NamedGetter(self, name: DOMString, found: &mut bool) -> Option { + fn NamedGetter(&self, name: DOMString, found: &mut bool) -> Option { let item = self.GetItem(name); *found = item.is_some(); item } - fn NamedSetter(self, name: DOMString, value: DOMString) { + fn NamedSetter(&self, name: DOMString, value: DOMString) { self.SetItem(name, value); } - fn NamedCreator(self, name: DOMString, value: DOMString) { + fn NamedCreator(&self, name: DOMString, value: DOMString) { self.SetItem(name, value); } - fn NamedDeleter(self, name: DOMString) { + fn NamedDeleter(&self, name: DOMString) { self.RemoveItem(name); } - fn SupportedPropertyNames(self) -> Vec { + fn SupportedPropertyNames(&self) -> Vec { // FIXME: unimplemented (https://github.com/servo/servo/issues/7273) vec![] } } -trait PrivateStorageHelpers { - fn broadcast_change_notification(self, key: Option, old_value: Option, - new_value: Option); -} -impl<'a> PrivateStorageHelpers for &'a Storage { +impl Storage { /// https://html.spec.whatwg.org/multipage/#send-a-storage-notification - fn broadcast_change_notification(self, key: Option, old_value: Option, + fn broadcast_change_notification(&self, key: Option, old_value: Option, new_value: Option) { let global_root = self.global.root(); let global_ref = global_root.r(); diff --git a/components/script/dom/storageevent.rs b/components/script/dom/storageevent.rs index 7fd1c039284..c83fb4807b6 100644 --- a/components/script/dom/storageevent.rs +++ b/components/script/dom/storageevent.rs @@ -17,7 +17,6 @@ use dom::storage::Storage; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct StorageEvent { event: Event, key: DOMRefCell>, @@ -88,29 +87,29 @@ impl StorageEvent { } } -impl<'a> StorageEventMethods for &'a StorageEvent { +impl StorageEventMethods for StorageEvent { // https://html.spec.whatwg.org/multipage/#dom-storageevent-key - fn GetKey(self) -> Option { + fn GetKey(&self) -> Option { self.key.borrow().clone() } // https://html.spec.whatwg.org/multipage/#dom-storageevent-oldvalue - fn GetOldValue(self) -> Option { + fn GetOldValue(&self) -> Option { self.oldValue.borrow().clone() } // https://html.spec.whatwg.org/multipage/#dom-storageevent-newvalue - fn GetNewValue(self) -> Option { + fn GetNewValue(&self) -> Option { self.newValue.borrow().clone() } // https://html.spec.whatwg.org/multipage/#dom-storageevent-url - fn Url(self) -> DOMString { + fn Url(&self) -> DOMString { self.url.borrow().clone() } // https://html.spec.whatwg.org/multipage/#dom-storageevent-storagearea - fn GetStorageArea(self) -> Option> { + fn GetStorageArea(&self) -> Option> { self.storageArea.get().map(Root::from_rooted) } } diff --git a/components/script/dom/testbinding.rs b/components/script/dom/testbinding.rs index e61b12eee7b..e050f799c8f 100644 --- a/components/script/dom/testbinding.rs +++ b/components/script/dom/testbinding.rs @@ -30,339 +30,342 @@ use std::ptr; use std::rc::Rc; #[dom_struct] -#[derive(HeapSizeOf)] pub struct TestBinding { reflector_: Reflector, global: GlobalField, } -impl<'a> TestBindingMethods for &'a TestBinding { - fn BooleanAttribute(self) -> bool { false } - fn SetBooleanAttribute(self, _: bool) {} - fn ByteAttribute(self) -> i8 { 0 } - fn SetByteAttribute(self, _: i8) {} - fn OctetAttribute(self) -> u8 { 0 } - fn SetOctetAttribute(self, _: u8) {} - fn ShortAttribute(self) -> i16 { 0 } - fn SetShortAttribute(self, _: i16) {} - fn UnsignedShortAttribute(self) -> u16 { 0 } - fn SetUnsignedShortAttribute(self, _: u16) {} - fn LongAttribute(self) -> i32 { 0 } - fn SetLongAttribute(self, _: i32) {} - fn UnsignedLongAttribute(self) -> u32 { 0 } - fn SetUnsignedLongAttribute(self, _: u32) {} - fn LongLongAttribute(self) -> i64 { 0 } - fn SetLongLongAttribute(self, _: i64) {} - fn UnsignedLongLongAttribute(self) -> u64 { 0 } - fn SetUnsignedLongLongAttribute(self, _: u64) {} - fn UnrestrictedFloatAttribute(self) -> f32 { 0. } - fn SetUnrestrictedFloatAttribute(self, _: f32) {} - fn FloatAttribute(self) -> Finite { Finite::wrap(0.) } - fn SetFloatAttribute(self, _: Finite) {} - fn UnrestrictedDoubleAttribute(self) -> f64 { 0. } - fn SetUnrestrictedDoubleAttribute(self, _: f64) {} - fn DoubleAttribute(self) -> Finite { Finite::wrap(0.) } - fn SetDoubleAttribute(self, _: Finite) {} - fn StringAttribute(self) -> DOMString { "".to_owned() } - fn SetStringAttribute(self, _: DOMString) {} - fn UsvstringAttribute(self) -> USVString { USVString("".to_owned()) } - fn SetUsvstringAttribute(self, _: USVString) {} - fn ByteStringAttribute(self) -> ByteString { ByteString::new(vec!()) } - fn SetByteStringAttribute(self, _: ByteString) {} - fn EnumAttribute(self) -> TestEnum { _empty } - fn SetEnumAttribute(self, _: TestEnum) {} - fn InterfaceAttribute(self) -> Root { +impl TestBindingMethods for TestBinding { + fn BooleanAttribute(&self) -> bool { false } + fn SetBooleanAttribute(&self, _: bool) {} + fn ByteAttribute(&self) -> i8 { 0 } + fn SetByteAttribute(&self, _: i8) {} + fn OctetAttribute(&self) -> u8 { 0 } + fn SetOctetAttribute(&self, _: u8) {} + fn ShortAttribute(&self) -> i16 { 0 } + fn SetShortAttribute(&self, _: i16) {} + fn UnsignedShortAttribute(&self) -> u16 { 0 } + fn SetUnsignedShortAttribute(&self, _: u16) {} + fn LongAttribute(&self) -> i32 { 0 } + fn SetLongAttribute(&self, _: i32) {} + fn UnsignedLongAttribute(&self) -> u32 { 0 } + fn SetUnsignedLongAttribute(&self, _: u32) {} + fn LongLongAttribute(&self) -> i64 { 0 } + fn SetLongLongAttribute(&self, _: i64) {} + fn UnsignedLongLongAttribute(&self) -> u64 { 0 } + fn SetUnsignedLongLongAttribute(&self, _: u64) {} + fn UnrestrictedFloatAttribute(&self) -> f32 { 0. } + fn SetUnrestrictedFloatAttribute(&self, _: f32) {} + fn FloatAttribute(&self) -> Finite { Finite::wrap(0.) } + fn SetFloatAttribute(&self, _: Finite) {} + fn UnrestrictedDoubleAttribute(&self) -> f64 { 0. } + fn SetUnrestrictedDoubleAttribute(&self, _: f64) {} + fn DoubleAttribute(&self) -> Finite { Finite::wrap(0.) } + fn SetDoubleAttribute(&self, _: Finite) {} + fn StringAttribute(&self) -> DOMString { "".to_owned() } + fn SetStringAttribute(&self, _: DOMString) {} + fn UsvstringAttribute(&self) -> USVString { USVString("".to_owned()) } + fn SetUsvstringAttribute(&self, _: USVString) {} + fn ByteStringAttribute(&self) -> ByteString { ByteString::new(vec!()) } + fn SetByteStringAttribute(&self, _: ByteString) {} + fn EnumAttribute(&self) -> TestEnum { _empty } + fn SetEnumAttribute(&self, _: TestEnum) {} + fn InterfaceAttribute(&self) -> Root { let global = self.global.root(); Blob::new(global.r(), None, "") } - fn SetInterfaceAttribute(self, _: &Blob) {} - fn UnionAttribute(self) -> HTMLElementOrLong { eLong(0) } - fn SetUnionAttribute(self, _: HTMLElementOrLong) {} - fn Union2Attribute(self) -> EventOrString { eString("".to_owned()) } - fn SetUnion2Attribute(self, _: EventOrString) {} - fn ArrayAttribute(self, _: *mut JSContext) -> *mut JSObject { NullValue().to_object_or_null() } - fn AnyAttribute(self, _: *mut JSContext) -> JSVal { NullValue() } - fn SetAnyAttribute(self, _: *mut JSContext, _: HandleValue) {} - fn ObjectAttribute(self, _: *mut JSContext) -> *mut JSObject { panic!() } - fn SetObjectAttribute(self, _: *mut JSContext, _: *mut JSObject) {} + fn SetInterfaceAttribute(&self, _: &Blob) {} + fn UnionAttribute(&self) -> HTMLElementOrLong { eLong(0) } + fn SetUnionAttribute(&self, _: HTMLElementOrLong) {} + fn Union2Attribute(&self) -> EventOrString { eString("".to_owned()) } + fn SetUnion2Attribute(&self, _: EventOrString) {} + fn ArrayAttribute(&self, _: *mut JSContext) -> *mut JSObject { NullValue().to_object_or_null() } + fn AnyAttribute(&self, _: *mut JSContext) -> JSVal { NullValue() } + fn SetAnyAttribute(&self, _: *mut JSContext, _: HandleValue) {} + fn ObjectAttribute(&self, _: *mut JSContext) -> *mut JSObject { panic!() } + fn SetObjectAttribute(&self, _: *mut JSContext, _: *mut JSObject) {} - fn GetBooleanAttributeNullable(self) -> Option { Some(false) } - fn SetBooleanAttributeNullable(self, _: Option) {} - fn GetByteAttributeNullable(self) -> Option { Some(0) } - fn SetByteAttributeNullable(self, _: Option) {} - fn GetOctetAttributeNullable(self) -> Option { Some(0) } - fn SetOctetAttributeNullable(self, _: Option) {} - fn GetShortAttributeNullable(self) -> Option { Some(0) } - fn SetShortAttributeNullable(self, _: Option) {} - fn GetUnsignedShortAttributeNullable(self) -> Option { Some(0) } - fn SetUnsignedShortAttributeNullable(self, _: Option) {} - fn GetLongAttributeNullable(self) -> Option { Some(0) } - fn SetLongAttributeNullable(self, _: Option) {} - fn GetUnsignedLongAttributeNullable(self) -> Option { Some(0) } - fn SetUnsignedLongAttributeNullable(self, _: Option) {} - fn GetLongLongAttributeNullable(self) -> Option { Some(0) } - fn SetLongLongAttributeNullable(self, _: Option) {} - fn GetUnsignedLongLongAttributeNullable(self) -> Option { Some(0) } - fn SetUnsignedLongLongAttributeNullable(self, _: Option) {} - fn GetUnrestrictedFloatAttributeNullable(self) -> Option { Some(0.) } - fn SetUnrestrictedFloatAttributeNullable(self, _: Option) {} - fn GetFloatAttributeNullable(self) -> Option> { Some(Finite::wrap(0.)) } - fn SetFloatAttributeNullable(self, _: Option>) {} - fn GetUnrestrictedDoubleAttributeNullable(self) -> Option { Some(0.) } - fn SetUnrestrictedDoubleAttributeNullable(self, _: Option) {} - fn GetDoubleAttributeNullable(self) -> Option> { Some(Finite::wrap(0.)) } - fn SetDoubleAttributeNullable(self, _: Option>) {} - fn GetByteStringAttributeNullable(self) -> Option { Some(ByteString::new(vec!())) } - fn SetByteStringAttributeNullable(self, _: Option) {} - fn GetStringAttributeNullable(self) -> Option { Some("".to_owned()) } - fn SetStringAttributeNullable(self, _: Option) {} - fn GetUsvstringAttributeNullable(self) -> Option { Some(USVString("".to_owned())) } - fn SetUsvstringAttributeNullable(self, _: Option) {} - fn SetBinaryRenamedAttribute(self, _: DOMString) {} - fn ForwardedAttribute(self) -> Root { Root::from_ref(self) } - fn BinaryRenamedAttribute(self) -> DOMString { "".to_owned() } - fn GetEnumAttributeNullable(self) -> Option { Some(_empty) } - fn GetInterfaceAttributeNullable(self) -> Option> { + fn GetBooleanAttributeNullable(&self) -> Option { Some(false) } + fn SetBooleanAttributeNullable(&self, _: Option) {} + fn GetByteAttributeNullable(&self) -> Option { Some(0) } + fn SetByteAttributeNullable(&self, _: Option) {} + fn GetOctetAttributeNullable(&self) -> Option { Some(0) } + fn SetOctetAttributeNullable(&self, _: Option) {} + fn GetShortAttributeNullable(&self) -> Option { Some(0) } + fn SetShortAttributeNullable(&self, _: Option) {} + fn GetUnsignedShortAttributeNullable(&self) -> Option { Some(0) } + fn SetUnsignedShortAttributeNullable(&self, _: Option) {} + fn GetLongAttributeNullable(&self) -> Option { Some(0) } + fn SetLongAttributeNullable(&self, _: Option) {} + fn GetUnsignedLongAttributeNullable(&self) -> Option { Some(0) } + fn SetUnsignedLongAttributeNullable(&self, _: Option) {} + fn GetLongLongAttributeNullable(&self) -> Option { Some(0) } + fn SetLongLongAttributeNullable(&self, _: Option) {} + fn GetUnsignedLongLongAttributeNullable(&self) -> Option { Some(0) } + fn SetUnsignedLongLongAttributeNullable(&self, _: Option) {} + fn GetUnrestrictedFloatAttributeNullable(&self) -> Option { Some(0.) } + fn SetUnrestrictedFloatAttributeNullable(&self, _: Option) {} + fn GetFloatAttributeNullable(&self) -> Option> { Some(Finite::wrap(0.)) } + fn SetFloatAttributeNullable(&self, _: Option>) {} + fn GetUnrestrictedDoubleAttributeNullable(&self) -> Option { Some(0.) } + fn SetUnrestrictedDoubleAttributeNullable(&self, _: Option) {} + fn GetDoubleAttributeNullable(&self) -> Option> { Some(Finite::wrap(0.)) } + fn SetDoubleAttributeNullable(&self, _: Option>) {} + fn GetByteStringAttributeNullable(&self) -> Option { Some(ByteString::new(vec!())) } + fn SetByteStringAttributeNullable(&self, _: Option) {} + fn GetStringAttributeNullable(&self) -> Option { Some("".to_owned()) } + fn SetStringAttributeNullable(&self, _: Option) {} + fn GetUsvstringAttributeNullable(&self) -> Option { Some(USVString("".to_owned())) } + fn SetUsvstringAttributeNullable(&self, _: Option) {} + fn SetBinaryRenamedAttribute(&self, _: DOMString) {} + fn ForwardedAttribute(&self) -> Root { Root::from_ref(self) } + fn BinaryRenamedAttribute(&self) -> DOMString { "".to_owned() } + fn SetBinaryRenamedAttribute2(&self, _: DOMString) {} + fn BinaryRenamedAttribute2(&self) -> DOMString { "".to_owned() } + fn Attr_to_automatically_rename(&self) -> DOMString { "".to_owned() } + fn SetAttr_to_automatically_rename(&self, _: DOMString) {} + fn GetEnumAttributeNullable(&self) -> Option { Some(_empty) } + fn GetInterfaceAttributeNullable(&self) -> Option> { let global = self.global.root(); Some(Blob::new(global.r(), None, "")) } - fn SetInterfaceAttributeNullable(self, _: Option<&Blob>) {} - fn GetObjectAttributeNullable(self, _: *mut JSContext) -> *mut JSObject { ptr::null_mut() } - fn SetObjectAttributeNullable(self, _: *mut JSContext, _: *mut JSObject) {} - fn GetUnionAttributeNullable(self) -> Option { Some(eLong(0)) } - fn SetUnionAttributeNullable(self, _: Option) {} - fn GetUnion2AttributeNullable(self) -> Option { Some(eString("".to_owned())) } - fn SetUnion2AttributeNullable(self, _: Option) {} - 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 { Finite::wrap(0.) } - fn ReceiveUnrestrictedDouble(self) -> f64 { 0. } - fn ReceiveDouble(self) -> Finite { Finite::wrap(0.) } - fn ReceiveString(self) -> DOMString { "".to_owned() } - fn ReceiveUsvstring(self) -> USVString { USVString("".to_owned()) } - fn ReceiveByteString(self) -> ByteString { ByteString::new(vec!()) } - fn ReceiveEnum(self) -> TestEnum { _empty } - fn ReceiveInterface(self) -> Root { + fn SetInterfaceAttributeNullable(&self, _: Option<&Blob>) {} + fn GetObjectAttributeNullable(&self, _: *mut JSContext) -> *mut JSObject { ptr::null_mut() } + fn SetObjectAttributeNullable(&self, _: *mut JSContext, _: *mut JSObject) {} + fn GetUnionAttributeNullable(&self) -> Option { Some(eLong(0)) } + fn SetUnionAttributeNullable(&self, _: Option) {} + fn GetUnion2AttributeNullable(&self) -> Option { Some(eString("".to_owned())) } + fn SetUnion2AttributeNullable(&self, _: Option) {} + 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 { Finite::wrap(0.) } + fn ReceiveUnrestrictedDouble(&self) -> f64 { 0. } + fn ReceiveDouble(&self) -> Finite { Finite::wrap(0.) } + fn ReceiveString(&self) -> DOMString { "".to_owned() } + fn ReceiveUsvstring(&self) -> USVString { USVString("".to_owned()) } + fn ReceiveByteString(&self) -> ByteString { ByteString::new(vec!()) } + fn ReceiveEnum(&self) -> TestEnum { _empty } + fn ReceiveInterface(&self) -> Root { let global = self.global.root(); Blob::new(global.r(), None, "") } - fn ReceiveAny(self, _: *mut JSContext) -> JSVal { NullValue() } - fn ReceiveObject(self, _: *mut JSContext) -> *mut JSObject { panic!() } - fn ReceiveUnion(self) -> HTMLElementOrLong { eLong(0) } - fn ReceiveUnion2(self) -> EventOrString { eString("".to_owned()) } + fn ReceiveAny(&self, _: *mut JSContext) -> JSVal { NullValue() } + fn ReceiveObject(&self, _: *mut JSContext) -> *mut JSObject { panic!() } + fn ReceiveUnion(&self) -> HTMLElementOrLong { eLong(0) } + fn ReceiveUnion2(&self) -> EventOrString { eString("".to_owned()) } - fn ReceiveNullableBoolean(self) -> Option { Some(false) } - fn ReceiveNullableByte(self) -> Option { Some(0) } - fn ReceiveNullableOctet(self) -> Option { Some(0) } - fn ReceiveNullableShort(self) -> Option { Some(0) } - fn ReceiveNullableUnsignedShort(self) -> Option { Some(0) } - fn ReceiveNullableLong(self) -> Option { Some(0) } - fn ReceiveNullableUnsignedLong(self) -> Option { Some(0) } - fn ReceiveNullableLongLong(self) -> Option { Some(0) } - fn ReceiveNullableUnsignedLongLong(self) -> Option { Some(0) } - fn ReceiveNullableUnrestrictedFloat(self) -> Option { Some(0.) } - fn ReceiveNullableFloat(self) -> Option> { Some(Finite::wrap(0.)) } - fn ReceiveNullableUnrestrictedDouble(self) -> Option { Some(0.) } - fn ReceiveNullableDouble(self) -> Option> { Some(Finite::wrap(0.)) } - fn ReceiveNullableString(self) -> Option { Some("".to_owned()) } - fn ReceiveNullableUsvstring(self) -> Option { Some(USVString("".to_owned())) } - fn ReceiveNullableByteString(self) -> Option { Some(ByteString::new(vec!())) } - fn ReceiveNullableEnum(self) -> Option { Some(_empty) } - fn ReceiveNullableInterface(self) -> Option> { + fn ReceiveNullableBoolean(&self) -> Option { Some(false) } + fn ReceiveNullableByte(&self) -> Option { Some(0) } + fn ReceiveNullableOctet(&self) -> Option { Some(0) } + fn ReceiveNullableShort(&self) -> Option { Some(0) } + fn ReceiveNullableUnsignedShort(&self) -> Option { Some(0) } + fn ReceiveNullableLong(&self) -> Option { Some(0) } + fn ReceiveNullableUnsignedLong(&self) -> Option { Some(0) } + fn ReceiveNullableLongLong(&self) -> Option { Some(0) } + fn ReceiveNullableUnsignedLongLong(&self) -> Option { Some(0) } + fn ReceiveNullableUnrestrictedFloat(&self) -> Option { Some(0.) } + fn ReceiveNullableFloat(&self) -> Option> { Some(Finite::wrap(0.)) } + fn ReceiveNullableUnrestrictedDouble(&self) -> Option { Some(0.) } + fn ReceiveNullableDouble(&self) -> Option> { Some(Finite::wrap(0.)) } + fn ReceiveNullableString(&self) -> Option { Some("".to_owned()) } + fn ReceiveNullableUsvstring(&self) -> Option { Some(USVString("".to_owned())) } + fn ReceiveNullableByteString(&self) -> Option { Some(ByteString::new(vec!())) } + fn ReceiveNullableEnum(&self) -> Option { Some(_empty) } + fn ReceiveNullableInterface(&self) -> Option> { let global = self.global.root(); Some(Blob::new(global.r(), None, "")) } - fn ReceiveNullableObject(self, _: *mut JSContext) -> *mut JSObject { ptr::null_mut() } - fn ReceiveNullableUnion(self) -> Option { Some(eLong(0)) } - fn ReceiveNullableUnion2(self) -> Option { Some(eString("".to_owned())) } + fn ReceiveNullableObject(&self, _: *mut JSContext) -> *mut JSObject { ptr::null_mut() } + fn ReceiveNullableUnion(&self) -> Option { Some(eLong(0)) } + fn ReceiveNullableUnion2(&self) -> Option { Some(eString("".to_owned())) } - fn PassBoolean(self, _: bool) {} - fn PassByte(self, _: i8) {} - fn PassOctet(self, _: u8) {} - fn PassShort(self, _: i16) {} - fn PassUnsignedShort(self, _: u16) {} - fn PassLong(self, _: i32) {} - fn PassUnsignedLong(self, _: u32) {} - fn PassLongLong(self, _: i64) {} - fn PassUnsignedLongLong(self, _: u64) {} - fn PassUnrestrictedFloat(self, _: f32) {} - fn PassFloat(self, _: Finite) {} - fn PassUnrestrictedDouble(self, _: f64) {} - fn PassDouble(self, _: Finite) {} - fn PassString(self, _: DOMString) {} - fn PassUsvstring(self, _: USVString) {} - fn PassByteString(self, _: ByteString) {} - fn PassEnum(self, _: TestEnum) {} - fn PassInterface(self, _: &Blob) {} - fn PassUnion(self, _: HTMLElementOrLong) {} - fn PassUnion2(self, _: EventOrString) {} - fn PassUnion3(self, _: BlobOrString) {} - fn PassAny(self, _: *mut JSContext, _: HandleValue) {} - fn PassObject(self, _: *mut JSContext, _: *mut JSObject) {} - fn PassCallbackFunction(self, _: Rc) {} - fn PassCallbackInterface(self, _: Rc) {} + fn PassBoolean(&self, _: bool) {} + fn PassByte(&self, _: i8) {} + fn PassOctet(&self, _: u8) {} + fn PassShort(&self, _: i16) {} + fn PassUnsignedShort(&self, _: u16) {} + fn PassLong(&self, _: i32) {} + fn PassUnsignedLong(&self, _: u32) {} + fn PassLongLong(&self, _: i64) {} + fn PassUnsignedLongLong(&self, _: u64) {} + fn PassUnrestrictedFloat(&self, _: f32) {} + fn PassFloat(&self, _: Finite) {} + fn PassUnrestrictedDouble(&self, _: f64) {} + fn PassDouble(&self, _: Finite) {} + fn PassString(&self, _: DOMString) {} + fn PassUsvstring(&self, _: USVString) {} + fn PassByteString(&self, _: ByteString) {} + fn PassEnum(&self, _: TestEnum) {} + fn PassInterface(&self, _: &Blob) {} + fn PassUnion(&self, _: HTMLElementOrLong) {} + fn PassUnion2(&self, _: EventOrString) {} + fn PassUnion3(&self, _: BlobOrString) {} + fn PassAny(&self, _: *mut JSContext, _: HandleValue) {} + fn PassObject(&self, _: *mut JSContext, _: *mut JSObject) {} + fn PassCallbackFunction(&self, _: Rc) {} + fn PassCallbackInterface(&self, _: Rc) {} - fn PassNullableBoolean(self, _: Option) {} - fn PassNullableByte(self, _: Option) {} - fn PassNullableOctet(self, _: Option) {} - fn PassNullableShort(self, _: Option) {} - fn PassNullableUnsignedShort(self, _: Option) {} - fn PassNullableLong(self, _: Option) {} - fn PassNullableUnsignedLong(self, _: Option) {} - fn PassNullableLongLong(self, _: Option) {} - fn PassNullableUnsignedLongLong(self, _: Option) {} - fn PassNullableUnrestrictedFloat(self, _: Option) {} - fn PassNullableFloat(self, _: Option>) {} - fn PassNullableUnrestrictedDouble(self, _: Option) {} - fn PassNullableDouble(self, _: Option>) {} - fn PassNullableString(self, _: Option) {} - fn PassNullableUsvstring(self, _: Option) {} - fn PassNullableByteString(self, _: Option) {} + fn PassNullableBoolean(&self, _: Option) {} + fn PassNullableByte(&self, _: Option) {} + fn PassNullableOctet(&self, _: Option) {} + fn PassNullableShort(&self, _: Option) {} + fn PassNullableUnsignedShort(&self, _: Option) {} + fn PassNullableLong(&self, _: Option) {} + fn PassNullableUnsignedLong(&self, _: Option) {} + fn PassNullableLongLong(&self, _: Option) {} + fn PassNullableUnsignedLongLong(&self, _: Option) {} + fn PassNullableUnrestrictedFloat(&self, _: Option) {} + fn PassNullableFloat(&self, _: Option>) {} + fn PassNullableUnrestrictedDouble(&self, _: Option) {} + fn PassNullableDouble(&self, _: Option>) {} + fn PassNullableString(&self, _: Option) {} + fn PassNullableUsvstring(&self, _: Option) {} + fn PassNullableByteString(&self, _: Option) {} // fn PassNullableEnum(self, _: Option) {} - fn PassNullableInterface(self, _: Option<&Blob>) {} - fn PassNullableObject(self, _: *mut JSContext, _: *mut JSObject) {} - fn PassNullableUnion(self, _: Option) {} - fn PassNullableUnion2(self, _: Option) {} - fn PassNullableCallbackFunction(self, _: Option>) {} - fn PassNullableCallbackInterface(self, _: Option>) {} + fn PassNullableInterface(&self, _: Option<&Blob>) {} + fn PassNullableObject(&self, _: *mut JSContext, _: *mut JSObject) {} + fn PassNullableUnion(&self, _: Option) {} + fn PassNullableUnion2(&self, _: Option) {} + fn PassNullableCallbackFunction(&self, _: Option>) {} + fn PassNullableCallbackInterface(&self, _: Option>) {} - fn PassOptionalBoolean(self, _: Option) {} - fn PassOptionalByte(self, _: Option) {} - fn PassOptionalOctet(self, _: Option) {} - fn PassOptionalShort(self, _: Option) {} - fn PassOptionalUnsignedShort(self, _: Option) {} - fn PassOptionalLong(self, _: Option) {} - fn PassOptionalUnsignedLong(self, _: Option) {} - fn PassOptionalLongLong(self, _: Option) {} - fn PassOptionalUnsignedLongLong(self, _: Option) {} - fn PassOptionalUnrestrictedFloat(self, _: Option) {} - fn PassOptionalFloat(self, _: Option>) {} - fn PassOptionalUnrestrictedDouble(self, _: Option) {} - fn PassOptionalDouble(self, _: Option>) {} - fn PassOptionalString(self, _: Option) {} - fn PassOptionalUsvstring(self, _: Option) {} - fn PassOptionalByteString(self, _: Option) {} - fn PassOptionalEnum(self, _: Option) {} - fn PassOptionalInterface(self, _: Option<&Blob>) {} - fn PassOptionalUnion(self, _: Option) {} - fn PassOptionalUnion2(self, _: Option) {} - fn PassOptionalAny(self, _: *mut JSContext, _: HandleValue) {} - fn PassOptionalObject(self, _: *mut JSContext, _: Option<*mut JSObject>) {} - fn PassOptionalCallbackFunction(self, _: Option>) {} - fn PassOptionalCallbackInterface(self, _: Option>) {} + fn PassOptionalBoolean(&self, _: Option) {} + fn PassOptionalByte(&self, _: Option) {} + fn PassOptionalOctet(&self, _: Option) {} + fn PassOptionalShort(&self, _: Option) {} + fn PassOptionalUnsignedShort(&self, _: Option) {} + fn PassOptionalLong(&self, _: Option) {} + fn PassOptionalUnsignedLong(&self, _: Option) {} + fn PassOptionalLongLong(&self, _: Option) {} + fn PassOptionalUnsignedLongLong(&self, _: Option) {} + fn PassOptionalUnrestrictedFloat(&self, _: Option) {} + fn PassOptionalFloat(&self, _: Option>) {} + fn PassOptionalUnrestrictedDouble(&self, _: Option) {} + fn PassOptionalDouble(&self, _: Option>) {} + fn PassOptionalString(&self, _: Option) {} + fn PassOptionalUsvstring(&self, _: Option) {} + fn PassOptionalByteString(&self, _: Option) {} + fn PassOptionalEnum(&self, _: Option) {} + fn PassOptionalInterface(&self, _: Option<&Blob>) {} + fn PassOptionalUnion(&self, _: Option) {} + fn PassOptionalUnion2(&self, _: Option) {} + fn PassOptionalAny(&self, _: *mut JSContext, _: HandleValue) {} + fn PassOptionalObject(&self, _: *mut JSContext, _: Option<*mut JSObject>) {} + fn PassOptionalCallbackFunction(&self, _: Option>) {} + fn PassOptionalCallbackInterface(&self, _: Option>) {} - fn PassOptionalNullableBoolean(self, _: Option>) {} - fn PassOptionalNullableByte(self, _: Option>) {} - fn PassOptionalNullableOctet(self, _: Option>) {} - fn PassOptionalNullableShort(self, _: Option>) {} - fn PassOptionalNullableUnsignedShort(self, _: Option>) {} - fn PassOptionalNullableLong(self, _: Option>) {} - fn PassOptionalNullableUnsignedLong(self, _: Option>) {} - fn PassOptionalNullableLongLong(self, _: Option>) {} - fn PassOptionalNullableUnsignedLongLong(self, _: Option>) {} - fn PassOptionalNullableUnrestrictedFloat(self, _: Option>) {} - fn PassOptionalNullableFloat(self, _: Option>>) {} - fn PassOptionalNullableUnrestrictedDouble(self, _: Option>) {} - fn PassOptionalNullableDouble(self, _: Option>>) {} - fn PassOptionalNullableString(self, _: Option>) {} - fn PassOptionalNullableUsvstring(self, _: Option>) {} - fn PassOptionalNullableByteString(self, _: Option>) {} + fn PassOptionalNullableBoolean(&self, _: Option>) {} + fn PassOptionalNullableByte(&self, _: Option>) {} + fn PassOptionalNullableOctet(&self, _: Option>) {} + fn PassOptionalNullableShort(&self, _: Option>) {} + fn PassOptionalNullableUnsignedShort(&self, _: Option>) {} + fn PassOptionalNullableLong(&self, _: Option>) {} + fn PassOptionalNullableUnsignedLong(&self, _: Option>) {} + fn PassOptionalNullableLongLong(&self, _: Option>) {} + fn PassOptionalNullableUnsignedLongLong(&self, _: Option>) {} + fn PassOptionalNullableUnrestrictedFloat(&self, _: Option>) {} + fn PassOptionalNullableFloat(&self, _: Option>>) {} + fn PassOptionalNullableUnrestrictedDouble(&self, _: Option>) {} + fn PassOptionalNullableDouble(&self, _: Option>>) {} + fn PassOptionalNullableString(&self, _: Option>) {} + fn PassOptionalNullableUsvstring(&self, _: Option>) {} + fn PassOptionalNullableByteString(&self, _: Option>) {} // fn PassOptionalNullableEnum(self, _: Option>) {} - fn PassOptionalNullableInterface(self, _: Option>) {} - fn PassOptionalNullableObject(self, _: *mut JSContext, _: Option<*mut JSObject>) {} - fn PassOptionalNullableUnion(self, _: Option>) {} - fn PassOptionalNullableUnion2(self, _: Option>) {} - fn PassOptionalNullableCallbackFunction(self, _: Option>>) {} - fn PassOptionalNullableCallbackInterface(self, _: Option>>) {} + fn PassOptionalNullableInterface(&self, _: Option>) {} + fn PassOptionalNullableObject(&self, _: *mut JSContext, _: Option<*mut JSObject>) {} + fn PassOptionalNullableUnion(&self, _: Option>) {} + fn PassOptionalNullableUnion2(&self, _: Option>) {} + fn PassOptionalNullableCallbackFunction(&self, _: Option>>) {} + fn PassOptionalNullableCallbackInterface(&self, _: Option>>) {} - fn PassOptionalBooleanWithDefault(self, _: bool) {} - fn PassOptionalByteWithDefault(self, _: i8) {} - fn PassOptionalOctetWithDefault(self, _: u8) {} - fn PassOptionalShortWithDefault(self, _: i16) {} - fn PassOptionalUnsignedShortWithDefault(self, _: u16) {} - fn PassOptionalLongWithDefault(self, _: i32) {} - fn PassOptionalUnsignedLongWithDefault(self, _: u32) {} - fn PassOptionalLongLongWithDefault(self, _: i64) {} - fn PassOptionalUnsignedLongLongWithDefault(self, _: u64) {} - fn PassOptionalStringWithDefault(self, _: DOMString) {} - fn PassOptionalUsvstringWithDefault(self, _: USVString) {} - fn PassOptionalEnumWithDefault(self, _: TestEnum) {} + fn PassOptionalBooleanWithDefault(&self, _: bool) {} + fn PassOptionalByteWithDefault(&self, _: i8) {} + fn PassOptionalOctetWithDefault(&self, _: u8) {} + fn PassOptionalShortWithDefault(&self, _: i16) {} + fn PassOptionalUnsignedShortWithDefault(&self, _: u16) {} + fn PassOptionalLongWithDefault(&self, _: i32) {} + fn PassOptionalUnsignedLongWithDefault(&self, _: u32) {} + fn PassOptionalLongLongWithDefault(&self, _: i64) {} + fn PassOptionalUnsignedLongLongWithDefault(&self, _: u64) {} + fn PassOptionalStringWithDefault(&self, _: DOMString) {} + fn PassOptionalUsvstringWithDefault(&self, _: USVString) {} + fn PassOptionalEnumWithDefault(&self, _: TestEnum) {} - fn PassOptionalNullableBooleanWithDefault(self, _: Option) {} - fn PassOptionalNullableByteWithDefault(self, _: Option) {} - fn PassOptionalNullableOctetWithDefault(self, _: Option) {} - fn PassOptionalNullableShortWithDefault(self, _: Option) {} - fn PassOptionalNullableUnsignedShortWithDefault(self, _: Option) {} - fn PassOptionalNullableLongWithDefault(self, _: Option) {} - fn PassOptionalNullableUnsignedLongWithDefault(self, _: Option) {} - fn PassOptionalNullableLongLongWithDefault(self, _: Option) {} - fn PassOptionalNullableUnsignedLongLongWithDefault(self, _: Option) {} + fn PassOptionalNullableBooleanWithDefault(&self, _: Option) {} + fn PassOptionalNullableByteWithDefault(&self, _: Option) {} + fn PassOptionalNullableOctetWithDefault(&self, _: Option) {} + fn PassOptionalNullableShortWithDefault(&self, _: Option) {} + fn PassOptionalNullableUnsignedShortWithDefault(&self, _: Option) {} + fn PassOptionalNullableLongWithDefault(&self, _: Option) {} + fn PassOptionalNullableUnsignedLongWithDefault(&self, _: Option) {} + fn PassOptionalNullableLongLongWithDefault(&self, _: Option) {} + fn PassOptionalNullableUnsignedLongLongWithDefault(&self, _: Option) {} // fn PassOptionalNullableUnrestrictedFloatWithDefault(self, _: Option) {} // fn PassOptionalNullableFloatWithDefault(self, _: Option>) {} // fn PassOptionalNullableUnrestrictedDoubleWithDefault(self, _: Option) {} // fn PassOptionalNullableDoubleWithDefault(self, _: Option>) {} - fn PassOptionalNullableStringWithDefault(self, _: Option) {} - fn PassOptionalNullableUsvstringWithDefault(self, _: Option) {} - fn PassOptionalNullableByteStringWithDefault(self, _: Option) {} + fn PassOptionalNullableStringWithDefault(&self, _: Option) {} + fn PassOptionalNullableUsvstringWithDefault(&self, _: Option) {} + fn PassOptionalNullableByteStringWithDefault(&self, _: Option) {} // fn PassOptionalNullableEnumWithDefault(self, _: Option) {} - fn PassOptionalNullableInterfaceWithDefault(self, _: Option<&Blob>) {} - fn PassOptionalNullableObjectWithDefault(self, _: *mut JSContext, _: *mut JSObject) {} - fn PassOptionalNullableUnionWithDefault(self, _: Option) {} - fn PassOptionalNullableUnion2WithDefault(self, _: Option) {} + fn PassOptionalNullableInterfaceWithDefault(&self, _: Option<&Blob>) {} + fn PassOptionalNullableObjectWithDefault(&self, _: *mut JSContext, _: *mut JSObject) {} + fn PassOptionalNullableUnionWithDefault(&self, _: Option) {} + fn PassOptionalNullableUnion2WithDefault(&self, _: Option) {} // fn PassOptionalNullableCallbackFunctionWithDefault(self, _: Option) {} - fn PassOptionalNullableCallbackInterfaceWithDefault(self, _: Option>) {} - fn PassOptionalAnyWithDefault(self, _: *mut JSContext, _: HandleValue) {} + fn PassOptionalNullableCallbackInterfaceWithDefault(&self, _: Option>) {} + fn PassOptionalAnyWithDefault(&self, _: *mut JSContext, _: HandleValue) {} - fn PassOptionalNullableBooleanWithNonNullDefault(self, _: Option) {} - fn PassOptionalNullableByteWithNonNullDefault(self, _: Option) {} - fn PassOptionalNullableOctetWithNonNullDefault(self, _: Option) {} - fn PassOptionalNullableShortWithNonNullDefault(self, _: Option) {} - fn PassOptionalNullableUnsignedShortWithNonNullDefault(self, _: Option) {} - fn PassOptionalNullableLongWithNonNullDefault(self, _: Option) {} - fn PassOptionalNullableUnsignedLongWithNonNullDefault(self, _: Option) {} - fn PassOptionalNullableLongLongWithNonNullDefault(self, _: Option) {} - fn PassOptionalNullableUnsignedLongLongWithNonNullDefault(self, _: Option) {} + fn PassOptionalNullableBooleanWithNonNullDefault(&self, _: Option) {} + fn PassOptionalNullableByteWithNonNullDefault(&self, _: Option) {} + fn PassOptionalNullableOctetWithNonNullDefault(&self, _: Option) {} + fn PassOptionalNullableShortWithNonNullDefault(&self, _: Option) {} + fn PassOptionalNullableUnsignedShortWithNonNullDefault(&self, _: Option) {} + fn PassOptionalNullableLongWithNonNullDefault(&self, _: Option) {} + fn PassOptionalNullableUnsignedLongWithNonNullDefault(&self, _: Option) {} + fn PassOptionalNullableLongLongWithNonNullDefault(&self, _: Option) {} + fn PassOptionalNullableUnsignedLongLongWithNonNullDefault(&self, _: Option) {} // fn PassOptionalNullableUnrestrictedFloatWithNonNullDefault(self, _: Option) {} // fn PassOptionalNullableFloatWithNonNullDefault(self, _: Option>) {} // fn PassOptionalNullableUnrestrictedDoubleWithNonNullDefault(self, _: Option) {} // fn PassOptionalNullableDoubleWithNonNullDefault(self, _: Option>) {} - fn PassOptionalNullableStringWithNonNullDefault(self, _: Option) {} - fn PassOptionalNullableUsvstringWithNonNullDefault(self, _: Option) {} + fn PassOptionalNullableStringWithNonNullDefault(&self, _: Option) {} + fn PassOptionalNullableUsvstringWithNonNullDefault(&self, _: Option) {} // fn PassOptionalNullableEnumWithNonNullDefault(self, _: Option) {} - fn PassVariadicBoolean(self, _: Vec) {} - fn PassVariadicByte(self, _: Vec) {} - fn PassVariadicOctet(self, _: Vec) {} - fn PassVariadicShort(self, _: Vec) {} - fn PassVariadicUnsignedShort(self, _: Vec) {} - fn PassVariadicLong(self, _: Vec) {} - fn PassVariadicUnsignedLong(self, _: Vec) {} - fn PassVariadicLongLong(self, _: Vec) {} - fn PassVariadicUnsignedLongLong(self, _: Vec) {} - fn PassVariadicUnrestrictedFloat(self, _: Vec) {} - fn PassVariadicFloat(self, _: Vec>) {} - fn PassVariadicUnrestrictedDouble(self, _: Vec) {} - fn PassVariadicDouble(self, _: Vec>) {} - fn PassVariadicString(self, _: Vec) {} - fn PassVariadicUsvstring(self, _: Vec) {} - fn PassVariadicByteString(self, _: Vec) {} - fn PassVariadicEnum(self, _: Vec) {} + fn PassVariadicBoolean(&self, _: Vec) {} + fn PassVariadicByte(&self, _: Vec) {} + fn PassVariadicOctet(&self, _: Vec) {} + fn PassVariadicShort(&self, _: Vec) {} + fn PassVariadicUnsignedShort(&self, _: Vec) {} + fn PassVariadicLong(&self, _: Vec) {} + fn PassVariadicUnsignedLong(&self, _: Vec) {} + fn PassVariadicLongLong(&self, _: Vec) {} + fn PassVariadicUnsignedLongLong(&self, _: Vec) {} + fn PassVariadicUnrestrictedFloat(&self, _: Vec) {} + fn PassVariadicFloat(&self, _: Vec>) {} + fn PassVariadicUnrestrictedDouble(&self, _: Vec) {} + fn PassVariadicDouble(&self, _: Vec>) {} + fn PassVariadicString(&self, _: Vec) {} + fn PassVariadicUsvstring(&self, _: Vec) {} + fn PassVariadicByteString(&self, _: Vec) {} + fn PassVariadicEnum(&self, _: Vec) {} // fn PassVariadicInterface(self, _: Vec<&Blob>) {} - fn PassVariadicUnion(self, _: Vec) {} - fn PassVariadicUnion2(self, _: Vec) {} - fn PassVariadicUnion3(self, _: Vec) {} - fn PassVariadicAny(self, _: *mut JSContext, _: Vec) {} - fn PassVariadicObject(self, _: *mut JSContext, _: Vec<*mut JSObject>) {} + fn PassVariadicUnion(&self, _: Vec) {} + fn PassVariadicUnion2(&self, _: Vec) {} + fn PassVariadicUnion3(&self, _: Vec) {} + fn PassVariadicAny(&self, _: *mut JSContext, _: Vec) {} + fn PassVariadicObject(&self, _: *mut JSContext, _: Vec<*mut JSObject>) {} } impl TestBinding { diff --git a/components/script/dom/testbindingproxy.rs b/components/script/dom/testbindingproxy.rs index 57b925e8d55..5ca27eae735 100644 --- a/components/script/dom/testbindingproxy.rs +++ b/components/script/dom/testbindingproxy.rs @@ -10,26 +10,25 @@ use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct TestBindingProxy { reflector_: Reflector } -impl<'a> TestBindingProxyMethods for &'a TestBindingProxy { - fn Length(self) -> u32 {0} - fn SupportedPropertyNames(self) -> Vec {vec![]} - fn GetNamedItem(self, _: DOMString) -> DOMString {"".to_owned()} - fn SetNamedItem(self, _: DOMString, _: DOMString) -> () {} - fn GetItem(self, _: u32) -> DOMString {"".to_owned()} - fn SetItem(self, _: u32, _: DOMString) -> () {} - fn RemoveItem(self, _: DOMString) -> () {} - fn Stringifier(self) -> DOMString {"".to_owned()} - fn NamedCreator(self, _: DOMString, _: DOMString) -> () {} - fn IndexedGetter(self, _: u32, _: &mut bool) -> DOMString {"".to_owned()} - fn NamedDeleter(self, _: DOMString) -> () {} - fn IndexedSetter(self, _: u32, _: DOMString) -> () {} - fn NamedSetter(self, _: DOMString, _: DOMString) -> () {} - fn IndexedCreator(self, _: u32, _: DOMString) -> () {} - fn NamedGetter(self, _: DOMString, _: &mut bool) -> DOMString {"".to_owned()} +impl TestBindingProxyMethods for TestBindingProxy { + fn Length(&self) -> u32 { 0 } + fn SupportedPropertyNames(&self) -> Vec { vec![] } + fn GetNamedItem(&self, _: DOMString) -> DOMString { "".to_owned() } + fn SetNamedItem(&self, _: DOMString, _: DOMString) -> () {} + fn GetItem(&self, _: u32) -> DOMString { "".to_owned() } + fn SetItem(&self, _: u32, _: DOMString) -> () {} + fn RemoveItem(&self, _: DOMString) -> () {} + fn Stringifier(&self) -> DOMString { "".to_owned() } + fn NamedCreator(&self, _: DOMString, _: DOMString) -> () {} + fn IndexedGetter(&self, _: u32, _: &mut bool) -> DOMString { "".to_owned() } + fn NamedDeleter(&self, _: DOMString) -> () {} + fn IndexedSetter(&self, _: u32, _: DOMString) -> () {} + fn NamedSetter(&self, _: DOMString, _: DOMString) -> () {} + fn IndexedCreator(&self, _: u32, _: DOMString) -> () {} + fn NamedGetter(&self, _: DOMString, _: &mut bool) -> DOMString { "".to_owned() } } diff --git a/components/script/dom/text.rs b/components/script/dom/text.rs index d5f314ab0c6..2eac167ca51 100644 --- a/components/script/dom/text.rs +++ b/components/script/dom/text.rs @@ -13,15 +13,14 @@ use dom::bindings::error::{Error, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::js::{RootedReference}; -use dom::characterdata::{CharacterData, CharacterDataHelpers, CharacterDataTypeId}; +use dom::characterdata::{CharacterData, CharacterDataTypeId}; use dom::document::Document; use dom::eventtarget::{EventTarget, EventTargetTypeId}; -use dom::node::{Node, NodeHelpers, NodeTypeId}; +use dom::node::{Node, NodeTypeId}; use util::str::DOMString; /// An HTML text node. #[dom_struct] -#[derive(HeapSizeOf)] pub struct Text { characterdata: CharacterData, } @@ -50,9 +49,9 @@ impl Text { } } -impl<'a> TextMethods for &'a Text { +impl TextMethods for Text { // https://dom.spec.whatwg.org/#dom-text-splittextoffset - fn SplitText(self, offset: u32) -> Fallible> { + fn SplitText(&self, offset: u32) -> Fallible> { let cdata = CharacterDataCast::from_ref(self); // Step 1. let length = cdata.Length(); @@ -88,7 +87,7 @@ impl<'a> TextMethods for &'a Text { } // https://dom.spec.whatwg.org/#dom-text-wholetext - fn WholeText(self) -> DOMString { + fn WholeText(&self) -> DOMString { let first = NodeCast::from_ref(self).inclusively_preceding_siblings() .take_while(|node| node.r().is_text()) .last().unwrap(); @@ -102,4 +101,3 @@ impl<'a> TextMethods for &'a Text { text } } - diff --git a/components/script/dom/textdecoder.rs b/components/script/dom/textdecoder.rs index c921dc68289..e058562bebb 100644 --- a/components/script/dom/textdecoder.rs +++ b/components/script/dom/textdecoder.rs @@ -24,7 +24,6 @@ use std::ptr; use std::slice; #[dom_struct] -#[derive(HeapSizeOf)] pub struct TextDecoder { reflector_: Reflector, #[ignore_heap_size_of = "Defined in rust-encoding"] @@ -74,20 +73,20 @@ impl TextDecoder { } -impl<'a> TextDecoderMethods for &'a TextDecoder { +impl TextDecoderMethods for TextDecoder { // https://encoding.spec.whatwg.org/#dom-textdecoder-encoding - fn Encoding(self) -> DOMString { + fn Encoding(&self) -> DOMString { self.encoding.whatwg_name().unwrap().to_owned() } // https://encoding.spec.whatwg.org/#dom-textdecoder-fatal - fn Fatal(self) -> bool { + fn Fatal(&self) -> bool { self.fatal } #[allow(unsafe_code)] // https://encoding.spec.whatwg.org/#dom-textdecoder-decode - fn Decode(self, _cx: *mut JSContext, input: Option<*mut JSObject>) + fn Decode(&self, _cx: *mut JSContext, input: Option<*mut JSObject>) -> Fallible { let input = match input { Some(input) => input, diff --git a/components/script/dom/textencoder.rs b/components/script/dom/textencoder.rs index 47a23681e74..7144ad77330 100644 --- a/components/script/dom/textencoder.rs +++ b/components/script/dom/textencoder.rs @@ -25,7 +25,6 @@ use js::jsapi::{JS_NewUint8Array, JS_GetUint8ArrayData}; use libc::uint8_t; #[dom_struct] -#[derive(HeapSizeOf)] pub struct TextEncoder { reflector_: Reflector, encoding: DOMString, @@ -71,15 +70,15 @@ impl TextEncoder { } } -impl<'a> TextEncoderMethods for &'a TextEncoder { +impl TextEncoderMethods for TextEncoder { // https://encoding.spec.whatwg.org/#dom-textencoder-encoding - fn Encoding(self) -> DOMString { + fn Encoding(&self) -> DOMString { self.encoding.clone() } #[allow(unsafe_code)] // https://encoding.spec.whatwg.org/#dom-textencoder-encode - fn Encode(self, cx: *mut JSContext, input: USVString) -> *mut JSObject { + fn Encode(&self, cx: *mut JSContext, input: USVString) -> *mut JSObject { unsafe { let encoded = self.encoder.encode(&input.0, EncoderTrap::Strict).unwrap(); let length = encoded.len() as u32; diff --git a/components/script/dom/treewalker.rs b/components/script/dom/treewalker.rs index cc90a0ab23e..eb30ab5ff4b 100644 --- a/components/script/dom/treewalker.rs +++ b/components/script/dom/treewalker.rs @@ -13,7 +13,7 @@ use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::js::{JS, MutHeap}; use dom::bindings::utils::{Reflector, reflect_dom_object}; -use dom::document::{Document, DocumentHelpers}; +use dom::document::Document; use dom::node::Node; use std::rc::Rc; @@ -24,6 +24,7 @@ pub struct TreeWalker { root_node: JS, current_node: MutHeap>, what_to_show: u32, + #[ignore_heap_size_of = "function pointers and Rc are hard"] filter: Filter } @@ -62,19 +63,19 @@ impl TreeWalker { } } -impl<'a> TreeWalkerMethods for &'a TreeWalker { +impl TreeWalkerMethods for TreeWalker { // https://dom.spec.whatwg.org/#dom-treewalker-root - fn Root(self) -> Root { + fn Root(&self) -> Root { self.root_node.root() } // https://dom.spec.whatwg.org/#dom-treewalker-whattoshow - fn WhatToShow(self) -> u32 { + fn WhatToShow(&self) -> u32 { self.what_to_show } // https://dom.spec.whatwg.org/#dom-treewalker-filter - fn GetFilter(self) -> Option> { + fn GetFilter(&self) -> Option> { match self.filter { Filter::None => None, Filter::JS(ref nf) => Some(nf.clone()), @@ -83,17 +84,17 @@ impl<'a> TreeWalkerMethods for &'a TreeWalker { } // https://dom.spec.whatwg.org/#dom-treewalker-currentnode - fn CurrentNode(self) -> Root { + fn CurrentNode(&self) -> Root { self.current_node.get().root() } // https://dom.spec.whatwg.org/#dom-treewalker-currentnode - fn SetCurrentNode(self, node: &Node) { + fn SetCurrentNode(&self, node: &Node) { self.current_node.set(JS::from_ref(node)); } // https://dom.spec.whatwg.org/#dom-treewalker-parentnode - fn ParentNode(self) -> Fallible>> { + fn ParentNode(&self) -> Fallible>> { // "1. Let node be the value of the currentNode attribute." let mut node = self.current_node.get().root(); // "2. While node is not null and is not root, run these substeps:" @@ -117,35 +118,35 @@ impl<'a> TreeWalkerMethods for &'a TreeWalker { } // https://dom.spec.whatwg.org/#dom-treewalker-firstchild - fn FirstChild(self) -> Fallible>> { + fn FirstChild(&self) -> Fallible>> { // "The firstChild() method must traverse children of type first." self.traverse_children(|node| node.GetFirstChild(), |node| node.GetNextSibling()) } // https://dom.spec.whatwg.org/#dom-treewalker-lastchild - fn LastChild(self) -> Fallible>> { + fn LastChild(&self) -> Fallible>> { // "The lastChild() method must traverse children of type last." self.traverse_children(|node| node.GetLastChild(), |node| node.GetPreviousSibling()) } // https://dom.spec.whatwg.org/#dom-treewalker-previoussibling - fn PreviousSibling(self) -> Fallible>> { + fn PreviousSibling(&self) -> Fallible>> { // "The nextSibling() method must traverse siblings of type next." self.traverse_siblings(|node| node.GetLastChild(), |node| node.GetPreviousSibling()) } // https://dom.spec.whatwg.org/#dom-treewalker-nextsibling - fn NextSibling(self) -> Fallible>> { + fn NextSibling(&self) -> Fallible>> { // "The previousSibling() method must traverse siblings of type previous." self.traverse_siblings(|node| node.GetFirstChild(), |node| node.GetNextSibling()) } // https://dom.spec.whatwg.org/#dom-treewalker-previousnode - fn PreviousNode(self) -> Fallible>> { + fn PreviousNode(&self) -> Fallible>> { // "1. Let node be the value of the currentNode attribute." let mut node = self.current_node.get().root(); // "2. While node is not root, run these substeps:" @@ -202,7 +203,7 @@ impl<'a> TreeWalkerMethods for &'a TreeWalker { } // https://dom.spec.whatwg.org/#dom-treewalker-nextnode - fn NextNode(self) -> Fallible>> { + fn NextNode(&self) -> Fallible>> { // "1. Let node be the value of the currentNode attribute." let mut node = self.current_node.get().root(); // "2. Let result be FILTER_ACCEPT." @@ -254,29 +255,10 @@ impl<'a> TreeWalkerMethods for &'a TreeWalker { type NodeAdvancer<'a> = Fn(&Node) -> Option> + 'a; -trait PrivateTreeWalkerHelpers { - fn traverse_children(self, - next_child: F, - next_sibling: G) - -> Fallible>> - where F: Fn(&Node) -> Option>, - G: Fn(&Node) -> Option>; - fn traverse_siblings(self, - next_child: F, - next_sibling: G) - -> Fallible>> - where F: Fn(&Node) -> Option>, - G: Fn(&Node) -> Option>; - fn is_root_node(self, node: &Node) -> bool; - fn is_current_node(self, node: &Node) -> bool; - fn first_following_node_not_following_root(self, node: &Node) - -> Option>; - fn accept_node(self, node: &Node) -> Fallible; -} -impl<'a> PrivateTreeWalkerHelpers for &'a TreeWalker { +impl TreeWalker { // https://dom.spec.whatwg.org/#concept-traverse-children - fn traverse_children(self, + fn traverse_children(&self, next_child: F, next_sibling: G) -> Fallible>> @@ -351,7 +333,7 @@ impl<'a> PrivateTreeWalkerHelpers for &'a TreeWalker { } // https://dom.spec.whatwg.org/#concept-traverse-siblings - fn traverse_siblings(self, + fn traverse_siblings(&self, next_child: F, next_sibling: G) -> Fallible>> @@ -413,7 +395,7 @@ impl<'a> PrivateTreeWalkerHelpers for &'a TreeWalker { } // https://dom.spec.whatwg.org/#concept-tree-following - fn first_following_node_not_following_root(self, node: &Node) + fn first_following_node_not_following_root(&self, node: &Node) -> Option> { // "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." @@ -440,7 +422,7 @@ impl<'a> PrivateTreeWalkerHelpers for &'a TreeWalker { } // https://dom.spec.whatwg.org/#concept-node-filter - fn accept_node(self, node: &Node) -> Fallible { + fn accept_node(&self, node: &Node) -> Fallible { // "To filter node run these steps:" // "1. Let n be node's nodeType attribute value minus 1." let n = node.NodeType() - 1; @@ -460,11 +442,11 @@ impl<'a> PrivateTreeWalkerHelpers for &'a TreeWalker { } } - fn is_root_node(self, node: &Node) -> bool { + fn is_root_node(&self, node: &Node) -> bool { JS::from_ref(node) == self.root_node } - fn is_current_node(self, node: &Node) -> bool { + fn is_current_node(&self, node: &Node) -> bool { JS::from_ref(node) == self.current_node.get() } } diff --git a/components/script/dom/uievent.rs b/components/script/dom/uievent.rs index abccf1abcd2..ff9c2beab6b 100644 --- a/components/script/dom/uievent.rs +++ b/components/script/dom/uievent.rs @@ -28,7 +28,6 @@ pub enum UIEventTypeId { // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#interface-UIEvent #[dom_struct] -#[derive(HeapSizeOf)] pub struct UIEvent { event: Event, view: MutNullableHeap>, @@ -87,19 +86,19 @@ impl UIEvent { } } -impl<'a> UIEventMethods for &'a UIEvent { +impl UIEventMethods for UIEvent { // https://w3c.github.io/uievents/#widl-UIEvent-view - fn GetView(self) -> Option> { + fn GetView(&self) -> Option> { self.view.get().map(Root::from_rooted) } // https://w3c.github.io/uievents/#widl-UIEvent-detail - fn Detail(self) -> i32 { + fn Detail(&self) -> i32 { self.detail.get() } // https://w3c.github.io/uievents/#widl-UIEvent-initUIEvent - fn InitUIEvent(self, + fn InitUIEvent(&self, type_: DOMString, can_bubble: bool, cancelable: bool, @@ -115,4 +114,3 @@ impl<'a> UIEventMethods for &'a UIEvent { self.detail.set(detail); } } - diff --git a/components/script/dom/url.rs b/components/script/dom/url.rs index daba091955c..f34428d4bbb 100644 --- a/components/script/dom/url.rs +++ b/components/script/dom/url.rs @@ -3,38 +3,42 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::URLBinding::{self, URLMethods}; -use dom::bindings::error::{Error, Fallible}; +use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::str::USVString; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::urlhelper::UrlHelper; -use url::{Host, Url, UrlParser}; +use url::{Host, ParseResult, Url, UrlParser}; use util::str::DOMString; use std::borrow::ToOwned; +use std::cell::RefCell; // https://url.spec.whatwg.org/#url #[dom_struct] -#[derive(HeapSizeOf)] pub struct URL { reflector_: Reflector, // https://url.spec.whatwg.org/#concept-urlutils-url - url: Url, + url: RefCell, + + // https://url.spec.whatwg.org/#concept-urlutils-get-the-base + base: Option, } impl URL { - fn new_inherited(url: Url) -> URL { + fn new_inherited(url: Url, base: Option) -> URL { URL { reflector_: Reflector::new(), - url: url, + url: RefCell::new(url), + base: base, } } - pub fn new(global: GlobalRef, url: Url) -> Root { - reflect_dom_object(box URL::new_inherited(url), + pub fn new(global: GlobalRef, url: Url, base: Option) -> Root { + reflect_dom_object(box URL::new_inherited(url, base), global, URLBinding::Wrap) } } @@ -60,7 +64,7 @@ impl URL { } }; // Step 3. - let parsed_url = match parser_with_base(parsed_base.as_ref()).parse(&url.0) { + let parsed_url = match parse_with_base(url, parsed_base.as_ref()) { Ok(url) => url, Err(error) => { // Step 4. @@ -68,7 +72,7 @@ impl URL { } }; // Steps 5-8. - Ok(URL::new(global, parsed_url)) + Ok(URL::new(global, parsed_url, parsed_base)) } // https://url.spec.whatwg.org/#dom-url-domaintoasciidomain @@ -85,67 +89,125 @@ impl URL { } } -impl<'a> URLMethods for &'a URL { +impl URLMethods for URL { // https://url.spec.whatwg.org/#dom-urlutils-hash - fn Hash(self) -> USVString { - UrlHelper::Hash(&self.url) + fn Hash(&self) -> USVString { + UrlHelper::Hash(&self.url.borrow()) + } + + // https://url.spec.whatwg.org/#dom-urlutils-hash + fn SetHash(&self, value: USVString) { + UrlHelper::SetHash(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-urlutils-host - fn Host(self) -> USVString { - UrlHelper::Host(&self.url) + fn Host(&self) -> USVString { + UrlHelper::Host(&self.url.borrow()) + } + + // https://url.spec.whatwg.org/#dom-urlutils-host + fn SetHost(&self, value: USVString) { + UrlHelper::SetHost(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-urlutils-hostname - fn Hostname(self) -> USVString { - UrlHelper::Hostname(&self.url) + fn Hostname(&self) -> USVString { + UrlHelper::Hostname(&self.url.borrow()) + } + + // https://url.spec.whatwg.org/#dom-urlutils-hostname + fn SetHostname(&self, value: USVString) { + UrlHelper::SetHostname(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-urlutils-href - fn Href(self) -> USVString { - UrlHelper::Href(&self.url) + fn Href(&self) -> USVString { + UrlHelper::Href(&self.url.borrow()) + } + + // https://url.spec.whatwg.org/#dom-urlutils-href + fn SetHref(&self, value: USVString) -> ErrorResult { + match parse_with_base(value, self.base.as_ref()) { + Ok(url) => { + *self.url.borrow_mut() = url; + Ok(()) + }, + Err(error) => { + Err(Error::Type(format!("could not parse URL: {}", error))) + }, + } } // https://url.spec.whatwg.org/#dom-urlutils-password - fn Password(self) -> USVString { - UrlHelper::Password(&self.url) + fn Password(&self) -> USVString { + UrlHelper::Password(&self.url.borrow()) + } + + // https://url.spec.whatwg.org/#dom-urlutils-password + fn SetPassword(&self, value: USVString) { + UrlHelper::SetPassword(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-urlutils-pathname - fn Pathname(self) -> USVString { - UrlHelper::Pathname(&self.url) + fn Pathname(&self) -> USVString { + UrlHelper::Pathname(&self.url.borrow()) + } + + // https://url.spec.whatwg.org/#dom-urlutils-pathname + fn SetPathname(&self, value: USVString) { + UrlHelper::SetPathname(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-urlutils-port - fn Port(self) -> USVString { - UrlHelper::Port(&self.url) + fn Port(&self) -> USVString { + UrlHelper::Port(&self.url.borrow()) + } + + // https://url.spec.whatwg.org/#dom-urlutils-port + fn SetPort(&self, value: USVString) { + UrlHelper::SetPort(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-urlutils-protocol - fn Protocol(self) -> USVString { - UrlHelper::Protocol(&self.url) + fn Protocol(&self) -> USVString { + UrlHelper::Protocol(&self.url.borrow()) + } + + // https://url.spec.whatwg.org/#dom-urlutils-protocol + fn SetProtocol(&self, value: USVString) { + UrlHelper::SetProtocol(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-urlutils-search - fn Search(self) -> USVString { - UrlHelper::Search(&self.url) + fn Search(&self) -> USVString { + UrlHelper::Search(&self.url.borrow()) + } + + // https://url.spec.whatwg.org/#dom-urlutils-search + fn SetSearch(&self, value: USVString) { + UrlHelper::SetSearch(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#URLUtils-stringification-behavior - fn Stringifier(self) -> DOMString { + fn Stringifier(&self) -> DOMString { self.Href().0 } // https://url.spec.whatwg.org/#dom-urlutils-username - fn Username(self) -> USVString { - UrlHelper::Username(&self.url) + fn Username(&self) -> USVString { + UrlHelper::Username(&self.url.borrow()) + } + + // https://url.spec.whatwg.org/#dom-urlutils-username + fn SetUsername(&self, value: USVString) { + UrlHelper::SetUsername(&mut self.url.borrow_mut(), value); } } -fn parser_with_base(base: Option<&Url>) -> UrlParser { +fn parse_with_base(input: USVString, base: Option<&Url>) -> ParseResult { let mut parser = UrlParser::new(); if let Some(base) = base { parser.base_url(base); } - parser + parser.parse(&input.0) } diff --git a/components/script/dom/urlhelper.rs b/components/script/dom/urlhelper.rs index 4376a85e390..684d6666e0c 100644 --- a/components/script/dom/urlhelper.rs +++ b/components/script/dom/urlhelper.rs @@ -4,7 +4,9 @@ use dom::bindings::str::USVString; -use url::{Url, SchemeData}; +use url::{Url, UrlParser, SchemeData}; + +use url::urlutils::{UrlUtils, UrlUtilsWrapper}; use std::borrow::ToOwned; use std::fmt::Write; @@ -22,6 +24,12 @@ impl UrlHelper { }) } + // https://url.spec.whatwg.org/#dom-urlutils-hash + pub fn SetHash(url: &mut Url, value: USVString) { + let mut wrapper = UrlUtilsWrapper { url: url, parser: &UrlParser::new() }; + let _ = wrapper.set_fragment(&value.0); + } + // https://url.spec.whatwg.org/#dom-urlutils-host pub fn Host(url: &Url) -> USVString { USVString(match url.scheme_data { @@ -36,11 +44,23 @@ impl UrlHelper { }) } + // https://url.spec.whatwg.org/#dom-urlutils-host + pub fn SetHost(url: &mut Url, value: USVString) { + let mut wrapper = UrlUtilsWrapper { url: url, parser: &UrlParser::new() }; + let _ = wrapper.set_host(&value.0); + } + // https://url.spec.whatwg.org/#dom-urlutils-hostname pub fn Hostname(url: &Url) -> USVString { USVString(url.serialize_host().unwrap_or_else(|| "".to_owned())) } + // https://url.spec.whatwg.org/#dom-urlutils-hostname + pub fn SetHostname(url: &mut Url, value: USVString) { + let mut wrapper = UrlUtilsWrapper { url: url, parser: &UrlParser::new() }; + let _ = wrapper.set_host_and_port(&value.0); + } + // https://url.spec.whatwg.org/#dom-urlutils-href pub fn Href(url: &Url) -> USVString { USVString(url.serialize()) @@ -51,15 +71,26 @@ impl UrlHelper { USVString(url.password().unwrap_or("").to_owned()) } + // https://url.spec.whatwg.org/#dom-urlutils-password + pub fn SetPassword(url: &mut Url, value: USVString) { + let mut wrapper = UrlUtilsWrapper { url: url, parser: &UrlParser::new() }; + let _ = wrapper.set_password(&value.0); + } + // https://url.spec.whatwg.org/#dom-urlutils-pathname pub fn Pathname(url: &Url) -> USVString { - // FIXME: Url null check is skipped for now USVString(match url.scheme_data { SchemeData::NonRelative(ref scheme_data) => scheme_data.clone(), SchemeData::Relative(..) => url.serialize_path().unwrap() }) } + // https://url.spec.whatwg.org/#dom-urlutils-pathname + pub fn SetPathname(url: &mut Url, value: USVString) { + let mut wrapper = UrlUtilsWrapper { url: url, parser: &UrlParser::new() }; + let _ = wrapper.set_path(&value.0); + } + // https://url.spec.whatwg.org/#dom-urlutils-port pub fn Port(url: &Url) -> USVString { USVString(match url.port() { @@ -68,11 +99,23 @@ impl UrlHelper { }) } + // https://url.spec.whatwg.org/#dom-urlutils-port + pub fn SetPort(url: &mut Url, value: USVString) { + let mut wrapper = UrlUtilsWrapper { url: url, parser: &UrlParser::new() }; + let _ = wrapper.set_port(&value.0); + } + // https://url.spec.whatwg.org/#dom-urlutils-protocol pub fn Protocol(url: &Url) -> USVString { USVString(format!("{}:", url.scheme.clone())) } + // https://url.spec.whatwg.org/#dom-urlutils-protocol + pub fn SetProtocol(url: &mut Url, value: USVString) { + let mut wrapper = UrlUtilsWrapper { url: url, parser: &UrlParser::new() }; + let _ = wrapper.set_scheme(&value.0); + } + // https://html.spec.whatwg.org/multipage/#same-origin pub fn SameOrigin(urlA: &Url, urlB: &Url) -> bool { if urlA.host() != urlB.host() { @@ -96,8 +139,20 @@ impl UrlHelper { }) } + // https://url.spec.whatwg.org/#dom-urlutils-search + pub fn SetSearch(url: &mut Url, value: USVString) { + let mut wrapper = UrlUtilsWrapper { url: url, parser: &UrlParser::new() }; + let _ = wrapper.set_query(&value.0); + } + // https://url.spec.whatwg.org/#dom-urlutils-username pub fn Username(url: &Url) -> USVString { USVString(url.username().unwrap_or("").to_owned()) } + + // https://url.spec.whatwg.org/#dom-urlutils-username + pub fn SetUsername(url: &mut Url, value: USVString) { + let mut wrapper = UrlUtilsWrapper { url: url, parser: &UrlParser::new() }; + let _ = wrapper.set_username(&value.0); + } } diff --git a/components/script/dom/urlsearchparams.rs b/components/script/dom/urlsearchparams.rs index e4bc0a8b30d..3c5b7800434 100644 --- a/components/script/dom/urlsearchparams.rs +++ b/components/script/dom/urlsearchparams.rs @@ -18,7 +18,6 @@ use util::str::DOMString; // https://url.spec.whatwg.org/#interface-urlsearchparams #[dom_struct] -#[derive(HeapSizeOf)] pub struct URLSearchParams { reflector_: Reflector, // https://url.spec.whatwg.org/#concept-urlsearchparams-list @@ -59,9 +58,9 @@ impl URLSearchParams { } } -impl<'a> URLSearchParamsMethods for &'a URLSearchParams { +impl URLSearchParamsMethods for URLSearchParams { // https://url.spec.whatwg.org/#dom-urlsearchparams-append - fn Append(self, name: DOMString, value: DOMString) { + fn Append(&self, name: DOMString, value: DOMString) { // Step 1. self.list.borrow_mut().push((name, value)); // Step 2. @@ -69,7 +68,7 @@ impl<'a> URLSearchParamsMethods for &'a URLSearchParams { } // https://url.spec.whatwg.org/#dom-urlsearchparams-delete - fn Delete(self, name: DOMString) { + fn Delete(&self, name: DOMString) { // Step 1. self.list.borrow_mut().retain(|&(ref k, _)| k != &name); // Step 2. @@ -77,7 +76,7 @@ impl<'a> URLSearchParamsMethods for &'a URLSearchParams { } // https://url.spec.whatwg.org/#dom-urlsearchparams-get - fn Get(self, name: DOMString) -> Option { + fn Get(&self, name: DOMString) -> Option { let list = self.list.borrow(); list.iter().filter_map(|&(ref k, ref v)| { if k == &name { @@ -89,13 +88,13 @@ impl<'a> URLSearchParamsMethods for &'a URLSearchParams { } // https://url.spec.whatwg.org/#dom-urlsearchparams-has - fn Has(self, name: DOMString) -> bool { + fn Has(&self, name: DOMString) -> bool { let list = self.list.borrow(); list.iter().find(|&&(ref k, _)| k == &name).is_some() } // https://url.spec.whatwg.org/#dom-urlsearchparams-set - fn Set(self, name: DOMString, value: DOMString) { + fn Set(&self, name: DOMString, value: DOMString) { let mut list = self.list.borrow_mut(); let mut index = None; let mut i = 0; @@ -119,30 +118,24 @@ impl<'a> URLSearchParamsMethods for &'a URLSearchParams { } // https://url.spec.whatwg.org/#stringification-behavior - fn Stringifier(self) -> DOMString { + fn Stringifier(&self) -> DOMString { self.serialize(None) } } -pub trait URLSearchParamsHelpers { - fn serialize(self, encoding: Option) -> DOMString; -} -impl<'a> URLSearchParamsHelpers for &'a URLSearchParams { +impl URLSearchParams { // https://url.spec.whatwg.org/#concept-urlencoded-serializer - fn serialize(self, encoding: Option) -> DOMString { + pub fn serialize(&self, encoding: Option) -> DOMString { let list = self.list.borrow(); serialize_with_encoding(list.iter(), encoding) } } -trait PrivateURLSearchParamsHelpers { - fn update_steps(self); -} -impl<'a> PrivateURLSearchParamsHelpers for &'a URLSearchParams { +impl URLSearchParams { // https://url.spec.whatwg.org/#concept-uq-update - fn update_steps(self) { + fn update_steps(&self) { // XXXManishearth Implement this when the URL interface is implemented } } diff --git a/components/script/dom/userscripts.rs b/components/script/dom/userscripts.rs index c8fce99002c..3520cbe5745 100644 --- a/components/script/dom/userscripts.rs +++ b/components/script/dom/userscripts.rs @@ -6,9 +6,7 @@ use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::codegen::InheritTypes::NodeCast; use dom::bindings::js::{RootedReference}; -use dom::element::AttributeHandlers; use dom::htmlheadelement::HTMLHeadElement; -use dom::node::NodeHelpers; use std::borrow::ToOwned; use std::fs::read_dir; use std::path::PathBuf; @@ -18,7 +16,7 @@ use util::resource_files::resources_dir_path; pub fn load_script(head: &HTMLHeadElement) { if let Some(ref path_str) = opts::get().userscripts { - let node = NodeCast::from_borrowed_ref(&head); + let node = NodeCast::from_ref(head); let first_child = node.GetFirstChild(); let doc = node.owner_doc(); let doc = doc.r(); @@ -45,8 +43,8 @@ pub fn load_script(head: &HTMLHeadElement) { let new_script = doc.CreateElement("script".to_owned()).unwrap(); let new_script = new_script.r(); new_script.set_string_attribute(&atom!("src"), name); - let new_script_node = NodeCast::from_borrowed_ref(&new_script); - node.InsertBefore(*new_script_node, first_child.r()).unwrap(); + let new_script_node = NodeCast::from_ref(new_script); + node.InsertBefore(new_script_node, first_child.r()).unwrap(); } } } diff --git a/components/script/dom/validitystate.rs b/components/script/dom/validitystate.rs index f14ebddff6f..c6288145d93 100644 --- a/components/script/dom/validitystate.rs +++ b/components/script/dom/validitystate.rs @@ -10,7 +10,6 @@ use dom::window::Window; // https://html.spec.whatwg.org/#validitystate #[dom_struct] -#[derive(HeapSizeOf)] pub struct ValidityState { reflector_: Reflector, state: u8, @@ -30,4 +29,3 @@ impl ValidityState { ValidityStateBinding::Wrap) } } - diff --git a/components/script/dom/virtualmethods.rs b/components/script/dom/virtualmethods.rs index 22f33d63201..589a2b2461c 100644 --- a/components/script/dom/virtualmethods.rs +++ b/components/script/dom/virtualmethods.rs @@ -37,7 +37,7 @@ use dom::element::ElementTypeId; use dom::event::Event; use dom::htmlelement::HTMLElementTypeId; use dom::node::NodeTypeId; -use dom::node::{ChildrenMutation, CloneChildrenFlag, Node, NodeHelpers}; +use dom::node::{ChildrenMutation, CloneChildrenFlag, Node}; use util::str::DOMString; @@ -126,126 +126,126 @@ pub trait VirtualMethods { /// method call on the trait object will invoke the corresponding method on the /// concrete type, propagating up the parent hierarchy unless otherwise /// interrupted. -pub fn vtable_for<'a>(node: &'a &'a Node) -> &'a (VirtualMethods + 'a) { +pub fn vtable_for<'a>(node: &'a Node) -> &'a (VirtualMethods + 'a) { match node.type_id() { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) => { - let element = HTMLAnchorElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLAnchorElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAppletElement)) => { - HTMLAppletElementCast::to_borrowed_ref(node).unwrap() as &'a (VirtualMethods + 'a) + HTMLAppletElementCast::to_ref(node).unwrap() as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAreaElement)) => { - let element = HTMLAreaElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLAreaElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBaseElement)) => { - let element = HTMLBaseElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLBaseElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBodyElement)) => { - let element = HTMLBodyElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLBodyElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) => { - let element = HTMLButtonElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLButtonElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLCanvasElement)) => { - let element = HTMLCanvasElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLCanvasElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFieldSetElement)) => { - let element = HTMLFieldSetElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLFieldSetElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFontElement)) => { - let element = HTMLFontElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLFontElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFormElement)) => { - let element = HTMLFormElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLFormElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLHeadElement)) => { - let element = HTMLHeadElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLHeadElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLImageElement)) => { - let element = HTMLImageElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLImageElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLIFrameElement)) => { - let element = HTMLIFrameElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLIFrameElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => { - let element = HTMLInputElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLInputElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLinkElement)) => { - let element = HTMLLinkElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLLinkElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLObjectElement)) => { - let element = HTMLObjectElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLObjectElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptGroupElement)) => { - let element = HTMLOptGroupElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLOptGroupElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptionElement)) => { - let element = HTMLOptionElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLOptionElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLScriptElement)) => { - let element = HTMLScriptElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLScriptElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) => { - let element = HTMLSelectElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLSelectElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLStyleElement)) => { - let element = HTMLStyleElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLStyleElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableElement)) => { let element = - HTMLTableElementCast::to_borrowed_ref(node).unwrap(); + HTMLTableElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableCellElement(_))) => { let element = - HTMLTableCellElementCast::to_borrowed_ref(node).unwrap(); + HTMLTableCellElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableRowElement)) => { let element = - HTMLTableRowElementCast::to_borrowed_ref(node).unwrap(); + HTMLTableRowElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableSectionElement)) => { let element = - HTMLTableSectionElementCast::to_borrowed_ref(node).unwrap(); + HTMLTableSectionElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => { - let element = HTMLTextAreaElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLTextAreaElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTitleElement)) => { let element = - HTMLTitleElementCast::to_borrowed_ref(node).unwrap(); + HTMLTitleElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(ElementTypeId::Element) => { - let element = ElementCast::to_borrowed_ref(node).unwrap(); + let element = ElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } NodeTypeId::Element(_) => { - let element = HTMLElementCast::to_borrowed_ref(node).unwrap(); + let element = HTMLElementCast::to_ref(node).unwrap(); element as &'a (VirtualMethods + 'a) } _ => { diff --git a/components/script/dom/webglactiveinfo.rs b/components/script/dom/webglactiveinfo.rs index 3bbcfd7dee2..efac59725b5 100644 --- a/components/script/dom/webglactiveinfo.rs +++ b/components/script/dom/webglactiveinfo.rs @@ -11,7 +11,6 @@ use dom::bindings::utils::{Reflector, reflect_dom_object}; use util::str::DOMString; #[dom_struct] -#[derive(HeapSizeOf)] pub struct WebGLActiveInfo { reflector_: Reflector, size: i32, @@ -35,19 +34,19 @@ impl WebGLActiveInfo { } } -impl<'a> WebGLActiveInfoMethods for &'a WebGLActiveInfo { +impl WebGLActiveInfoMethods for WebGLActiveInfo { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.11.1 - fn Size(self) -> i32 { + fn Size(&self) -> i32 { self.size } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.11.1 - fn Type(self) -> u32 { + fn Type(&self) -> u32 { self.ty } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.11.1 - fn Name(self) -> DOMString { + fn Name(&self) -> DOMString { self.name.clone() } } diff --git a/components/script/dom/webglbuffer.rs b/components/script/dom/webglbuffer.rs index 6f958d62597..e5fc0295a90 100644 --- a/components/script/dom/webglbuffer.rs +++ b/components/script/dom/webglbuffer.rs @@ -14,7 +14,6 @@ use ipc_channel::ipc::{self, IpcSender}; use std::cell::Cell; #[dom_struct] -#[derive(HeapSizeOf)] pub struct WebGLBuffer { webgl_object: WebGLObject, id: u32, @@ -50,19 +49,14 @@ impl WebGLBuffer { } } -pub trait WebGLBufferHelpers { - fn id(self) -> u32; - fn bind(self, target: u32) -> WebGLResult<()>; - fn delete(self); -} -impl<'a> WebGLBufferHelpers for &'a WebGLBuffer { - fn id(self) -> u32 { +impl WebGLBuffer { + pub fn id(&self) -> u32 { self.id } // NB: Only valid buffer targets come here - fn bind(self, target: u32) -> WebGLResult<()> { + pub fn bind(&self, target: u32) -> WebGLResult<()> { if let Some(previous_target) = self.target.get() { if target != previous_target { return Err(WebGLError::InvalidOperation); @@ -75,7 +69,7 @@ impl<'a> WebGLBufferHelpers for &'a WebGLBuffer { Ok(()) } - fn delete(self) { + pub fn delete(&self) { if !self.is_deleted.get() { self.is_deleted.set(true); self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::DeleteBuffer(self.id))).unwrap(); diff --git a/components/script/dom/webglframebuffer.rs b/components/script/dom/webglframebuffer.rs index 790cb46c3c4..c387fc2d711 100644 --- a/components/script/dom/webglframebuffer.rs +++ b/components/script/dom/webglframebuffer.rs @@ -14,7 +14,6 @@ use ipc_channel::ipc::{self, IpcSender}; use std::cell::Cell; #[dom_struct] -#[derive(HeapSizeOf)] pub struct WebGLFramebuffer { webgl_object: WebGLObject, id: u32, @@ -48,23 +47,18 @@ impl WebGLFramebuffer { } } -pub trait WebGLFramebufferHelpers { - fn id(self) -> u32; - fn bind(self, target: u32); - fn delete(self); -} -impl<'a> WebGLFramebufferHelpers for &'a WebGLFramebuffer { - fn id(self) -> u32 { +impl WebGLFramebuffer { + pub fn id(&self) -> u32 { self.id } - fn bind(self, target: u32) { + pub fn bind(&self, target: u32) { let cmd = CanvasWebGLMsg::BindFramebuffer(target, WebGLFramebufferBindingRequest::Explicit(self.id)); self.renderer.send(CanvasMsg::WebGL(cmd)).unwrap(); } - fn delete(self) { + pub fn delete(&self) { if !self.is_deleted.get() { self.is_deleted.set(true); self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::DeleteFramebuffer(self.id))).unwrap(); diff --git a/components/script/dom/webglobject.rs b/components/script/dom/webglobject.rs index ea31d7364e7..c950768e329 100644 --- a/components/script/dom/webglobject.rs +++ b/components/script/dom/webglobject.rs @@ -9,7 +9,6 @@ use dom::bindings::js::Root; use dom::bindings::utils::{Reflector, reflect_dom_object}; #[dom_struct] -#[derive(HeapSizeOf)] pub struct WebGLObject { reflector_: Reflector, } diff --git a/components/script/dom/webglprogram.rs b/components/script/dom/webglprogram.rs index e4f598285d3..2a1a0cfc6a5 100644 --- a/components/script/dom/webglprogram.rs +++ b/components/script/dom/webglprogram.rs @@ -9,7 +9,7 @@ use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::utils::reflect_dom_object; use dom::webglobject::WebGLObject; use dom::webglrenderingcontext::MAX_UNIFORM_AND_ATTRIBUTE_LEN; -use dom::webglshader::{WebGLShader, WebGLShaderHelpers}; +use dom::webglshader::WebGLShader; use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants; @@ -18,7 +18,6 @@ use ipc_channel::ipc::{self, IpcSender}; use std::cell::Cell; #[dom_struct] -#[derive(HeapSizeOf)] pub struct WebGLProgram { webgl_object: WebGLObject, id: u32, @@ -55,18 +54,10 @@ impl WebGLProgram { } } -pub trait WebGLProgramHelpers { - fn delete(self); - fn link(self); - fn use_program(self); - fn attach_shader(self, shader: &WebGLShader) -> WebGLResult<()>; - fn get_attrib_location(self, name: String) -> WebGLResult>; - fn get_uniform_location(self, name: String) -> WebGLResult>; -} -impl<'a> WebGLProgramHelpers for &'a WebGLProgram { +impl WebGLProgram { /// glDeleteProgram - fn delete(self) { + pub fn delete(&self) { if !self.is_deleted.get() { self.is_deleted.set(true); self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::DeleteProgram(self.id))).unwrap(); @@ -74,17 +65,17 @@ impl<'a> WebGLProgramHelpers for &'a WebGLProgram { } /// glLinkProgram - fn link(self) { + pub fn link(&self) { self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::LinkProgram(self.id))).unwrap(); } /// glUseProgram - fn use_program(self) { + pub fn use_program(&self) { self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::UseProgram(self.id))).unwrap(); } /// glAttachShader - fn attach_shader(self, shader: &WebGLShader) -> WebGLResult<()> { + pub fn attach_shader(&self, shader: &WebGLShader) -> WebGLResult<()> { let shader_slot = match shader.gl_type() { constants::FRAGMENT_SHADER => &self.fragment_shader, constants::VERTEX_SHADER => &self.vertex_shader, @@ -105,7 +96,7 @@ impl<'a> WebGLProgramHelpers for &'a WebGLProgram { } /// glGetAttribLocation - fn get_attrib_location(self, name: String) -> WebGLResult> { + pub fn get_attrib_location(&self, name: String) -> WebGLResult> { if name.len() > MAX_UNIFORM_AND_ATTRIBUTE_LEN { return Err(WebGLError::InvalidValue); } @@ -121,7 +112,7 @@ impl<'a> WebGLProgramHelpers for &'a WebGLProgram { } /// glGetUniformLocation - fn get_uniform_location(self, name: String) -> WebGLResult> { + pub fn get_uniform_location(&self, name: String) -> WebGLResult> { if name.len() > MAX_UNIFORM_AND_ATTRIBUTE_LEN { return Err(WebGLError::InvalidValue); } diff --git a/components/script/dom/webglrenderbuffer.rs b/components/script/dom/webglrenderbuffer.rs index ed68e6277be..a8d963894b6 100644 --- a/components/script/dom/webglrenderbuffer.rs +++ b/components/script/dom/webglrenderbuffer.rs @@ -14,7 +14,6 @@ use ipc_channel::ipc::{self, IpcSender}; use std::cell::Cell; #[dom_struct] -#[derive(HeapSizeOf)] pub struct WebGLRenderbuffer { webgl_object: WebGLObject, id: u32, @@ -48,22 +47,17 @@ impl WebGLRenderbuffer { } } -pub trait WebGLRenderbufferHelpers { - fn id(self) -> u32; - fn bind(self, target: u32); - fn delete(self); -} -impl<'a> WebGLRenderbufferHelpers for &'a WebGLRenderbuffer { - fn id(self) -> u32 { +impl WebGLRenderbuffer { + pub fn id(&self) -> u32 { self.id } - fn bind(self, target: u32) { + pub fn bind(&self, target: u32) { self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::BindRenderbuffer(target, self.id))).unwrap(); } - fn delete(self) { + pub fn delete(&self) { if !self.is_deleted.get() { self.is_deleted.set(true); self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::DeleteRenderbuffer(self.id))).unwrap(); diff --git a/components/script/dom/webglrenderingcontext.rs b/components/script/dom/webglrenderingcontext.rs index c7f6ca54885..799b088a792 100644 --- a/components/script/dom/webglrenderingcontext.rs +++ b/components/script/dom/webglrenderingcontext.rs @@ -17,16 +17,14 @@ use dom::bindings::js::{JS, LayoutJS, Root}; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::htmlcanvaselement::HTMLCanvasElement; use dom::htmlcanvaselement::utils as canvas_utils; -use dom::htmlimageelement::HTMLImageElementHelpers; -use dom::imagedata::ImageDataHelpers; -use dom::node::{window_from_node, NodeHelpers, NodeDamage}; -use dom::webglbuffer::{WebGLBuffer, WebGLBufferHelpers}; -use dom::webglframebuffer::{WebGLFramebuffer, WebGLFramebufferHelpers}; -use dom::webglprogram::{WebGLProgram, WebGLProgramHelpers}; -use dom::webglrenderbuffer::{WebGLRenderbuffer, WebGLRenderbufferHelpers}; -use dom::webglshader::{WebGLShader, WebGLShaderHelpers}; -use dom::webgltexture::{TexParameterValue, WebGLTexture, WebGLTextureHelpers}; -use dom::webgluniformlocation::{WebGLUniformLocation, WebGLUniformLocationHelpers}; +use dom::node::{window_from_node, NodeDamage}; +use dom::webglbuffer::WebGLBuffer; +use dom::webglframebuffer::WebGLFramebuffer; +use dom::webglprogram::WebGLProgram; +use dom::webglrenderbuffer::WebGLRenderbuffer; +use dom::webglshader::WebGLShader; +use dom::webgltexture::{TexParameterValue, WebGLTexture}; +use dom::webgluniformlocation::WebGLUniformLocation; use euclid::size::Size2D; use ipc_channel::ipc::{self, IpcSender}; use js::jsapi::{JSContext, JSObject, RootedValue}; @@ -75,7 +73,6 @@ bitflags! { } #[dom_struct] -#[derive(HeapSizeOf)] pub struct WebGLRenderingContext { reflector_: Reflector, global: GlobalField, @@ -146,14 +143,14 @@ impl Drop for WebGLRenderingContext { } } -impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { +impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.1 - fn Canvas(self) -> Root { + fn Canvas(&self) -> Root { self.canvas.root() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.1 - fn DrawingBufferWidth(self) -> i32 { + fn DrawingBufferWidth(&self) -> i32 { let (sender, receiver) = ipc::channel().unwrap(); self.ipc_renderer .send(CanvasMsg::WebGL(CanvasWebGLMsg::DrawingBufferWidth(sender))) @@ -162,7 +159,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.1 - fn DrawingBufferHeight(self) -> i32 { + fn DrawingBufferHeight(&self) -> i32 { let (sender, receiver) = ipc::channel().unwrap(); self.ipc_renderer .send(CanvasMsg::WebGL(CanvasWebGLMsg::DrawingBufferHeight(sender))) @@ -171,7 +168,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn GetParameter(self, cx: *mut JSContext, parameter: u32) -> JSVal { + fn GetParameter(&self, cx: *mut JSContext, parameter: u32) -> JSVal { // TODO(ecoal95): Implement the missing parameters from the spec let mut rval = RootedValue::new(cx, UndefinedValue()); match parameter { @@ -186,7 +183,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn GetError(self) -> u32 { + fn GetError(&self) -> u32 { let error_code = if let Some(error) = self.last_error.get() { match error { WebGLError::InvalidEnum => constants::INVALID_ENUM, @@ -203,7 +200,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.2 - fn GetContextAttributes(self) -> Option { + fn GetContextAttributes(&self) -> Option { let (sender, receiver) = ipc::channel().unwrap(); // If the send does not succeed, assume context lost @@ -226,49 +223,49 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14 - fn GetExtension(self, _cx: *mut JSContext, _name: DOMString) -> *mut JSObject { + fn GetExtension(&self, _cx: *mut JSContext, _name: DOMString) -> *mut JSObject { // TODO(ecoal95) we actually do not support extensions. // `getSupportedExtensions` cannot be implemented as of right now (see #544) 0 as *mut JSObject } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn ActiveTexture(self, texture: u32) { + fn ActiveTexture(&self, texture: u32) { self.ipc_renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::ActiveTexture(texture))).unwrap(); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn BlendColor(self, r: f32, g: f32, b: f32, a: f32) { + fn BlendColor(&self, r: f32, g: f32, b: f32, a: f32) { self.ipc_renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::BlendColor(r, g, b, a))).unwrap(); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn BlendEquation(self, mode: u32) { + fn BlendEquation(&self, mode: u32) { self.ipc_renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::BlendEquation(mode))).unwrap(); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn BlendEquationSeparate(self, mode_rgb: u32, mode_alpha: u32) { + fn BlendEquationSeparate(&self, mode_rgb: u32, mode_alpha: u32) { self.ipc_renderer .send(CanvasMsg::WebGL(CanvasWebGLMsg::BlendEquationSeparate(mode_rgb, mode_alpha))) .unwrap(); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn BlendFunc(self, src_factor: u32, dest_factor: u32) { + fn BlendFunc(&self, src_factor: u32, dest_factor: u32) { self.ipc_renderer .send(CanvasMsg::WebGL(CanvasWebGLMsg::BlendFunc(src_factor, dest_factor))) .unwrap(); } // 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) { + fn BlendFuncSeparate(&self, src_rgb: u32, dest_rgb: u32, src_alpha: u32, dest_alpha: u32) { self.ipc_renderer.send( CanvasMsg::WebGL(CanvasWebGLMsg::BlendFuncSeparate(src_rgb, dest_rgb, src_alpha, dest_alpha))).unwrap(); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - fn AttachShader(self, program: Option<&WebGLProgram>, shader: Option<&WebGLShader>) { + fn AttachShader(&self, program: Option<&WebGLProgram>, shader: Option<&WebGLShader>) { if let Some(program) = program { if let Some(shader) = shader { handle_potential_webgl_error!(self, program.attach_shader(shader)); @@ -277,7 +274,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 - fn BindBuffer(self, target: u32, buffer: Option<&WebGLBuffer>) { + fn BindBuffer(&self, target: u32, buffer: Option<&WebGLBuffer>) { match target { constants::ARRAY_BUFFER | constants::ELEMENT_ARRAY_BUFFER => (), @@ -296,7 +293,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6 - fn BindFramebuffer(self, target: u32, framebuffer: Option<&WebGLFramebuffer>) { + fn BindFramebuffer(&self, target: u32, framebuffer: Option<&WebGLFramebuffer>) { if target != constants::FRAMEBUFFER { return self.webgl_error(InvalidOperation); } @@ -311,7 +308,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 - fn BindRenderbuffer(self, target: u32, renderbuffer: Option<&WebGLRenderbuffer>) { + fn BindRenderbuffer(&self, target: u32, renderbuffer: Option<&WebGLRenderbuffer>) { if target != constants::RENDERBUFFER { return self.webgl_error(InvalidEnum); } @@ -327,7 +324,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn BindTexture(self, target: u32, texture: Option<&WebGLTexture>) { + fn BindTexture(&self, target: u32, texture: Option<&WebGLTexture>) { let slot = match target { constants::TEXTURE_2D => &self.bound_texture_2d, constants::TEXTURE_CUBE_MAP => &self.bound_texture_cube_map, @@ -350,7 +347,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 - fn BufferData(self, _cx: *mut JSContext, target: u32, data: Option<*mut JSObject>, usage: u32) { + fn BufferData(&self, _cx: *mut JSContext, target: u32, data: Option<*mut JSObject>, usage: u32) { let data = match data { Some(data) => data, None => return, @@ -372,41 +369,41 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11 - fn Clear(self, mask: u32) { + fn Clear(&self, mask: u32) { self.ipc_renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::Clear(mask))).unwrap(); self.mark_as_dirty(); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn ClearColor(self, red: f32, green: f32, blue: f32, alpha: f32) { + fn ClearColor(&self, red: f32, green: f32, blue: f32, alpha: f32) { self.ipc_renderer .send(CanvasMsg::WebGL(CanvasWebGLMsg::ClearColor(red, green, blue, alpha))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn ClearDepth(self, depth: f32) { + fn ClearDepth(&self, depth: f32) { self.ipc_renderer .send(CanvasMsg::WebGL(CanvasWebGLMsg::ClearDepth(depth as f64))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn ClearStencil(self, stencil: i32) { + fn ClearStencil(&self, stencil: i32) { self.ipc_renderer .send(CanvasMsg::WebGL(CanvasWebGLMsg::ClearStencil(stencil))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn ColorMask(self, r: bool, g: bool, b: bool, a: bool) { + fn ColorMask(&self, r: bool, g: bool, b: bool, a: bool) { self.ipc_renderer .send(CanvasMsg::WebGL(CanvasWebGLMsg::ColorMask(r, g, b, a))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn CullFace(self, mode: u32) { + fn CullFace(&self, mode: u32) { match mode { constants::FRONT | constants::BACK | constants::FRONT_AND_BACK => self.ipc_renderer @@ -417,7 +414,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn FrontFace(self, mode: u32) { + fn FrontFace(&self, mode: u32) { match mode { constants::CW | constants::CCW => self.ipc_renderer @@ -427,7 +424,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn DepthFunc(self, func: u32) { + fn DepthFunc(&self, func: u32) { match func { constants::NEVER | constants::LESS | constants::EQUAL | constants::LEQUAL | @@ -441,21 +438,21 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn DepthMask(self, flag: bool) { + fn DepthMask(&self, flag: bool) { self.ipc_renderer .send(CanvasMsg::WebGL(CanvasWebGLMsg::DepthMask(flag))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn DepthRange(self, near: f32, far: f32) { + fn DepthRange(&self, near: f32, far: f32) { self.ipc_renderer .send(CanvasMsg::WebGL(CanvasWebGLMsg::DepthRange(near as f64, far as f64))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn Enable(self, cap: u32) { + fn Enable(&self, cap: u32) { match cap { constants::BLEND | constants::CULL_FACE | constants::DEPTH_TEST | constants::DITHER | constants::POLYGON_OFFSET_FILL | constants::SAMPLE_ALPHA_TO_COVERAGE | constants::SAMPLE_COVERAGE | @@ -468,7 +465,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn Disable(self, cap: u32) { + fn Disable(&self, cap: u32) { match cap { constants::BLEND | constants::CULL_FACE | constants::DEPTH_TEST | constants::DITHER | constants::POLYGON_OFFSET_FILL | constants::SAMPLE_ALPHA_TO_COVERAGE | constants::SAMPLE_COVERAGE | @@ -481,7 +478,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - fn CompileShader(self, shader: Option<&WebGLShader>) { + fn CompileShader(&self, shader: Option<&WebGLShader>) { if let Some(shader) = shader { shader.compile() } @@ -490,81 +487,81 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { // TODO(ecoal95): Probably in the future we should keep track of the // generated objects, either here or in the webgl task // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 - fn CreateBuffer(self) -> Option> { + fn CreateBuffer(&self) -> Option> { WebGLBuffer::maybe_new(self.global.root().r(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6 - fn CreateFramebuffer(self) -> Option> { + fn CreateFramebuffer(&self) -> Option> { WebGLFramebuffer::maybe_new(self.global.root().r(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 - fn CreateRenderbuffer(self) -> Option> { + fn CreateRenderbuffer(&self) -> Option> { WebGLRenderbuffer::maybe_new(self.global.root().r(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn CreateTexture(self) -> Option> { + fn CreateTexture(&self) -> Option> { WebGLTexture::maybe_new(self.global.root().r(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - fn CreateProgram(self) -> Option> { + fn CreateProgram(&self) -> Option> { WebGLProgram::maybe_new(self.global.root().r(), self.ipc_renderer.clone()) } // TODO(ecoal95): Check if constants are cross-platform or if we must make a translation // between WebGL constants and native ones. // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - fn CreateShader(self, shader_type: u32) -> Option> { + fn CreateShader(&self, shader_type: u32) -> Option> { WebGLShader::maybe_new(self.global.root().r(), self.ipc_renderer.clone(), shader_type) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 - fn DeleteBuffer(self, buffer: Option<&WebGLBuffer>) { + fn DeleteBuffer(&self, buffer: Option<&WebGLBuffer>) { if let Some(buffer) = buffer { buffer.delete() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6 - fn DeleteFramebuffer(self, framebuffer: Option<&WebGLFramebuffer>) { + fn DeleteFramebuffer(&self, framebuffer: Option<&WebGLFramebuffer>) { if let Some(framebuffer) = framebuffer { framebuffer.delete() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 - fn DeleteRenderbuffer(self, renderbuffer: Option<&WebGLRenderbuffer>) { + fn DeleteRenderbuffer(&self, renderbuffer: Option<&WebGLRenderbuffer>) { if let Some(renderbuffer) = renderbuffer { renderbuffer.delete() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn DeleteTexture(self, texture: Option<&WebGLTexture>) { + fn DeleteTexture(&self, texture: Option<&WebGLTexture>) { if let Some(texture) = texture { texture.delete() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - fn DeleteProgram(self, program: Option<&WebGLProgram>) { + fn DeleteProgram(&self, program: Option<&WebGLProgram>) { if let Some(program) = program { program.delete() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - fn DeleteShader(self, shader: Option<&WebGLShader>) { + fn DeleteShader(&self, shader: Option<&WebGLShader>) { if let Some(shader) = shader { shader.delete() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11 - fn DrawArrays(self, mode: u32, first: i32, count: i32) { + fn DrawArrays(&self, mode: u32, first: i32, count: i32) { match mode { constants::POINTS | constants::LINE_STRIP | constants::LINE_LOOP | constants::LINES | @@ -586,14 +583,14 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn EnableVertexAttribArray(self, attrib_id: u32) { + fn EnableVertexAttribArray(&self, attrib_id: u32) { self.ipc_renderer .send(CanvasMsg::WebGL(CanvasWebGLMsg::EnableVertexAttribArray(attrib_id))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn GetAttribLocation(self, program: Option<&WebGLProgram>, name: DOMString) -> i32 { + fn GetAttribLocation(&self, program: Option<&WebGLProgram>, name: DOMString) -> i32 { if let Some(program) = program { handle_potential_webgl_error!(self, program.get_attrib_location(name), None).unwrap_or(-1) } else { @@ -602,7 +599,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - fn GetShaderInfoLog(self, shader: Option<&WebGLShader>) -> Option { + fn GetShaderInfoLog(&self, shader: Option<&WebGLShader>) -> Option { if let Some(shader) = shader { shader.info_log() } else { @@ -611,7 +608,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - fn GetShaderParameter(self, _: *mut JSContext, shader: Option<&WebGLShader>, param_id: u32) -> JSVal { + fn GetShaderParameter(&self, _: *mut JSContext, shader: Option<&WebGLShader>, param_id: u32) -> JSVal { if let Some(shader) = shader { match handle_potential_webgl_error!(self, shader.parameter(param_id), WebGLShaderParameter::Invalid) { WebGLShaderParameter::Int(val) => Int32Value(val), @@ -624,7 +621,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn GetUniformLocation(self, + fn GetUniformLocation(&self, program: Option<&WebGLProgram>, name: DOMString) -> Option> { if let Some(program) = program { @@ -636,7 +633,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn Hint(self, target: u32, mode: u32) { + fn Hint(&self, target: u32, mode: u32) { if target != constants::GENERATE_MIPMAP_HINT { return self.webgl_error(InvalidEnum); } @@ -655,7 +652,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn LineWidth(self, width: f32) { + fn LineWidth(&self, width: f32) { if width.is_nan() || width <= 0f32 { return self.webgl_error(InvalidValue); } @@ -668,7 +665,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { // NOTE: Usage of this function could affect rendering while we keep using // readback to render to the page. // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn PixelStorei(self, param_name: u32, param_value: i32) { + fn PixelStorei(&self, param_name: u32, param_value: i32) { let mut texture_settings = self.texture_unpacking_settings.get(); match param_name { constants::UNPACK_FLIP_Y_WEBGL => { @@ -719,28 +716,28 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 - fn PolygonOffset(self, factor: f32, units: f32) { + fn PolygonOffset(&self, factor: f32, units: f32) { self.ipc_renderer .send(CanvasMsg::WebGL(CanvasWebGLMsg::PolygonOffset(factor, units))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - fn LinkProgram(self, program: Option<&WebGLProgram>) { + fn LinkProgram(&self, program: Option<&WebGLProgram>) { if let Some(program) = program { program.link() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - fn ShaderSource(self, shader: Option<&WebGLShader>, source: DOMString) { + fn ShaderSource(&self, shader: Option<&WebGLShader>, source: DOMString) { if let Some(shader) = shader { shader.set_source(source) } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - fn GetShaderSource(self, shader: Option<&WebGLShader>) -> Option { + fn GetShaderSource(&self, shader: Option<&WebGLShader>) -> Option { if let Some(shader) = shader { shader.source() } else { @@ -750,7 +747,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn Uniform4fv(self, + fn Uniform4fv(&self, _cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, data: Option<*mut JSObject>) { @@ -774,14 +771,14 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 - fn UseProgram(self, program: Option<&WebGLProgram>) { + fn UseProgram(&self, program: Option<&WebGLProgram>) { if let Some(program) = program { program.use_program() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 - fn VertexAttribPointer(self, attrib_id: u32, size: i32, data_type: u32, + fn VertexAttribPointer(&self, attrib_id: u32, size: i32, data_type: u32, normalized: bool, stride: i32, offset: i64) { if let constants::FLOAT = data_type { let msg = CanvasMsg::WebGL( @@ -793,14 +790,14 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.4 - fn Viewport(self, x: i32, y: i32, width: i32, height: i32) { + fn Viewport(&self, x: i32, y: i32, width: i32, height: i32) { self.ipc_renderer .send(CanvasMsg::WebGL(CanvasWebGLMsg::Viewport(x, y, width, height))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn TexImage2D(self, + fn TexImage2D(&self, target: u32, level: i32, internal_format: u32, @@ -871,7 +868,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn TexParameterf(self, target: u32, name: u32, value: f32) { + fn TexParameterf(&self, target: u32, name: u32, value: f32) { match target { constants::TEXTURE_2D | constants::TEXTURE_CUBE_MAP => { @@ -889,7 +886,7 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 - fn TexParameteri(self, target: u32, name: u32, value: i32) { + fn TexParameteri(&self, target: u32, name: u32, value: i32) { match target { constants::TEXTURE_2D | constants::TEXTURE_CUBE_MAP => { @@ -907,13 +904,9 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { } } -pub trait WebGLRenderingContextHelpers { - fn webgl_error(&self, err: WebGLError); - fn bound_texture_for(&self, target: u32) -> Option>; -} -impl<'a> WebGLRenderingContextHelpers for &'a WebGLRenderingContext { - fn webgl_error(&self, err: WebGLError) { +impl WebGLRenderingContext { + pub fn webgl_error(&self, err: WebGLError) { // If an error has been detected no further errors must be // recorded until `getError` has been called if self.last_error.get().is_none() { @@ -921,7 +914,7 @@ impl<'a> WebGLRenderingContextHelpers for &'a WebGLRenderingContext { } } - fn bound_texture_for(&self, target: u32) -> Option> { + pub fn bound_texture_for(&self, target: u32) -> Option> { match target { constants::TEXTURE_2D => self.bound_texture_2d.get(), constants::TEXTURE_CUBE_MAP => self.bound_texture_cube_map.get(), diff --git a/components/script/dom/webglshader.rs b/components/script/dom/webglshader.rs index 3fe107d9f67..bcad061853f 100644 --- a/components/script/dom/webglshader.rs +++ b/components/script/dom/webglshader.rs @@ -11,32 +11,52 @@ use dom::webglobject::WebGLObject; use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants; +use angle::hl::{BuiltInResources, Output, ShaderValidator}; use canvas_traits::{CanvasMsg, CanvasWebGLMsg, WebGLResult, WebGLError, WebGLShaderParameter}; use ipc_channel::ipc::{self, IpcSender}; use std::cell::Cell; use std::cell::RefCell; +use std::sync::{Once, ONCE_INIT}; + +#[derive(Clone, Copy, PartialEq, Debug, JSTraceable, HeapSizeOf)] +pub enum ShaderCompilationStatus { + NotCompiled, + Succeeded, + Failed, +} #[dom_struct] -#[derive(HeapSizeOf)] pub struct WebGLShader { webgl_object: WebGLObject, id: u32, gl_type: u32, source: RefCell>, + info_log: RefCell>, is_deleted: Cell, - // TODO(ecoal95): Evaluate moving this to `WebGLObject` + compilation_status: Cell, #[ignore_heap_size_of = "Defined in ipc-channel"] renderer: IpcSender, } +#[cfg(not(target_os = "android"))] +const SHADER_OUTPUT_FORMAT: Output = Output::Glsl; + +#[cfg(target_os = "android")] +const SHADER_OUTPUT_FORMAT: Output = Output::Essl; + +static GLSLANG_INITIALIZATION: Once = ONCE_INIT; + impl WebGLShader { fn new_inherited(renderer: IpcSender, id: u32, shader_type: u32) -> WebGLShader { + GLSLANG_INITIALIZATION.call_once(|| ::angle::hl::initialize().unwrap()); WebGLShader { webgl_object: WebGLObject::new_inherited(), id: id, gl_type: shader_type, source: RefCell::new(None), + info_log: RefCell::new(None), is_deleted: Cell::new(false), + compilation_status: Cell::new(ShaderCompilationStatus::NotCompiled), renderer: renderer, } } @@ -60,35 +80,48 @@ impl WebGLShader { } } -pub trait WebGLShaderHelpers { - fn id(self) -> u32; - fn gl_type(self) -> u32; - fn compile(self); - fn delete(self); - fn info_log(self) -> Option; - fn parameter(self, param_id: u32) -> WebGLResult; - fn source(self) -> Option; - fn set_source(self, src: String); -} -impl<'a> WebGLShaderHelpers for &'a WebGLShader { - fn id(self) -> u32 { +impl WebGLShader { + pub fn id(&self) -> u32 { self.id } - fn gl_type(self) -> u32 { + pub fn gl_type(&self) -> u32 { self.gl_type } - // TODO(ecoal95): Validate shaders to be conforming to the WebGL spec /// glCompileShader - fn compile(self) { - self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::CompileShader(self.id))).unwrap() + pub fn compile(&self) { + if self.compilation_status.get() != ShaderCompilationStatus::NotCompiled { + debug!("Compiling already compiled shader {}", self.id); + } + + if let Some(ref source) = *self.source.borrow() { + let validator = ShaderValidator::for_webgl(self.gl_type, + SHADER_OUTPUT_FORMAT, + &BuiltInResources::default()).unwrap(); + match validator.compile_and_translate(&[source.as_bytes()]) { + Ok(translated_source) => { + // NOTE: At this point we should be pretty sure that the compilation in the paint task + // will succeed. + // It could be interesting to retrieve the info log from the paint task though + let msg = CanvasWebGLMsg::CompileShader(self.id, translated_source); + self.renderer.send(CanvasMsg::WebGL(msg)).unwrap(); + self.compilation_status.set(ShaderCompilationStatus::Succeeded); + }, + Err(error) => { + self.compilation_status.set(ShaderCompilationStatus::Failed); + debug!("Shader {} compilation failed: {}", self.id, error); + }, + } + + *self.info_log.borrow_mut() = Some(validator.info_log()); + } } /// Mark this shader as deleted (if it wasn't previously) /// and delete it as if calling glDeleteShader. - fn delete(self) { + pub fn delete(&self) { if !self.is_deleted.get() { self.is_deleted.set(true); self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::DeleteShader(self.id))).unwrap() @@ -96,14 +129,12 @@ impl<'a> WebGLShaderHelpers for &'a WebGLShader { } /// glGetShaderInfoLog - fn info_log(self) -> Option { - let (sender, receiver) = ipc::channel().unwrap(); - self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::GetShaderInfoLog(self.id, sender))).unwrap(); - receiver.recv().unwrap() + pub fn info_log(&self) -> Option { + self.info_log.borrow().clone() } /// glGetShaderParameter - fn parameter(self, param_id: u32) -> WebGLResult { + pub fn parameter(&self, param_id: u32) -> WebGLResult { match param_id { constants::SHADER_TYPE | constants::DELETE_STATUS | constants::COMPILE_STATUS => {}, _ => return Err(WebGLError::InvalidEnum), @@ -115,14 +146,12 @@ impl<'a> WebGLShaderHelpers for &'a WebGLShader { } /// Get the shader source - fn source(self) -> Option { + pub fn source(&self) -> Option { self.source.borrow().clone() } /// glShaderSource - fn set_source(self, source: String) { - *self.source.borrow_mut() = Some(source.clone()); - self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::ShaderSource(self.id, source))).unwrap() + pub fn set_source(&self, source: String) { + *self.source.borrow_mut() = Some(source); } } - diff --git a/components/script/dom/webglshaderprecisionformat.rs b/components/script/dom/webglshaderprecisionformat.rs index 5c7d4232b88..e3b8f473bc5 100644 --- a/components/script/dom/webglshaderprecisionformat.rs +++ b/components/script/dom/webglshaderprecisionformat.rs @@ -10,7 +10,6 @@ use dom::bindings::js::Root; use dom::bindings::utils::{Reflector, reflect_dom_object}; #[dom_struct] -#[derive(HeapSizeOf)] pub struct WebGLShaderPrecisionFormat { reflector_: Reflector, range_min: i32, @@ -39,19 +38,19 @@ impl WebGLShaderPrecisionFormat { } } -impl<'a> WebGLShaderPrecisionFormatMethods for &'a WebGLShaderPrecisionFormat { +impl WebGLShaderPrecisionFormatMethods for WebGLShaderPrecisionFormat { // https://www.khronos.org/registry/webgl/specs/1.0/#5.12.1 - fn RangeMin(self) -> i32 { + fn RangeMin(&self) -> i32 { self.range_min } // https://www.khronos.org/registry/webgl/specs/1.0/#5.12.1 - fn RangeMax(self) -> i32 { + fn RangeMax(&self) -> i32 { self.range_max } // https://www.khronos.org/registry/webgl/specs/1.0/#5.12.1 - fn Precision(self) -> i32 { + fn Precision(&self) -> i32 { self.precision } } diff --git a/components/script/dom/webgltexture.rs b/components/script/dom/webgltexture.rs index 7fa44178155..c549a6b7513 100644 --- a/components/script/dom/webgltexture.rs +++ b/components/script/dom/webgltexture.rs @@ -20,7 +20,6 @@ pub enum TexParameterValue { } #[dom_struct] -#[derive(HeapSizeOf)] pub struct WebGLTexture { webgl_object: WebGLObject, id: u32, @@ -56,23 +55,14 @@ impl WebGLTexture { } } -pub trait WebGLTextureHelpers { - fn id(self) -> u32; - fn bind(self, target: u32) -> WebGLResult<()>; - fn delete(self); - fn tex_parameter(self, - target: u32, - name: u32, - value: TexParameterValue) -> WebGLResult<()>; -} -impl<'a> WebGLTextureHelpers for &'a WebGLTexture { - fn id(self) -> u32 { +impl WebGLTexture { + pub fn id(&self) -> u32 { self.id } // NB: Only valid texture targets come here - fn bind(self, target: u32) -> WebGLResult<()> { + pub fn bind(&self, target: u32) -> WebGLResult<()> { if let Some(previous_target) = self.target.get() { if target != previous_target { return Err(WebGLError::InvalidOperation); @@ -86,7 +76,7 @@ impl<'a> WebGLTextureHelpers for &'a WebGLTexture { Ok(()) } - fn delete(self) { + pub fn delete(&self) { if !self.is_deleted.get() { self.is_deleted.set(true); self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::DeleteTexture(self.id))).unwrap(); @@ -96,7 +86,7 @@ impl<'a> WebGLTextureHelpers for &'a 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 /// - fn tex_parameter(self, + pub fn tex_parameter(&self, target: u32, name: u32, value: TexParameterValue) -> WebGLResult<()> { diff --git a/components/script/dom/webgluniformlocation.rs b/components/script/dom/webgluniformlocation.rs index add5da9f928..ea30afc8b51 100644 --- a/components/script/dom/webgluniformlocation.rs +++ b/components/script/dom/webgluniformlocation.rs @@ -9,7 +9,6 @@ use dom::bindings::js::Root; use dom::bindings::utils::{Reflector, reflect_dom_object}; #[dom_struct] -#[derive(HeapSizeOf)] pub struct WebGLUniformLocation { reflector_: Reflector, id: i32, @@ -28,12 +27,9 @@ impl WebGLUniformLocation { } } -pub trait WebGLUniformLocationHelpers { - fn id(self) -> i32; -} -impl<'a> WebGLUniformLocationHelpers for &'a WebGLUniformLocation { - fn id(self) -> i32 { +impl WebGLUniformLocation { + pub fn id(&self) -> i32 { self.id } } diff --git a/components/script/dom/webidls/CSSStyleDeclaration.webidl b/components/script/dom/webidls/CSSStyleDeclaration.webidl index 014e12740bf..dba69a515b0 100644 --- a/components/script/dom/webidls/CSSStyleDeclaration.webidl +++ b/components/script/dom/webidls/CSSStyleDeclaration.webidl @@ -34,40 +34,73 @@ interface CSSStyleDeclaration { partial interface CSSStyleDeclaration { [SetterThrows, TreatNullAs=EmptyString] attribute DOMString background; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString backgroundColor; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString background-color; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString backgroundPosition; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString background-position; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString backgroundRepeat; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString background-repeat; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString backgroundImage; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString background-image; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString backgroundAttachment; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString background-attachment; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString backgroundSize; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString background-size; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString backgroundOrigin; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString background-origin; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString backgroundClip; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString background-clip; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderColor; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-color; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderRadius; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-radius; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderSpacing; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-spacing; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderStyle; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-style; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderWidth; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-width; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderBottom; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-bottom; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderBottomColor; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-bottom-color; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderBottomLeftRadius; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-bottom-left-radius; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderBottomRightRadius; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-bottom-right-radius; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderBottomStyle; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-bottom-style; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderBottomWidth; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-bottom-width; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderLeft; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-left; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderLeftColor; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-left-color; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderLeftStyle; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-left-style; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderLeftWidth; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-left-width; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderRight; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-right; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderRightColor; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-right-color; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderRightStyle; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-right-style; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderRightWidth; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-right-width; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderTop; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-top; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderTopColor; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-top-color; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderTopLeftRadius; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-top-left-radius; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderTopRightRadius; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-top-right-radius; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderTopStyle; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-top-style; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderTopWidth; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-top-width; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString content; @@ -82,8 +115,11 @@ partial interface CSSStyleDeclaration { [SetterThrows, TreatNullAs=EmptyString] attribute DOMString cursor; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString boxSizing; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString box-sizing; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString boxShadow; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString box-shadow; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString textShadow; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString text-shadow; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString _float; @@ -93,89 +129,143 @@ partial interface CSSStyleDeclaration { [SetterThrows, TreatNullAs=EmptyString] attribute DOMString transform; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString transformOrigin; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString transform-origin; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString perspective; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString perspectiveOrigin; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString perspective-origin; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString transformStyle; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString transform-style; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString backfaceVisibility; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString backface-visibility; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString direction; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString unicodeBidi; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString unicode-bidi; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString filter; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString lineHeight; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString line-height; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString mixBlendMode; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString mix-blend-mode; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString verticalAlign; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString vertical-align; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString listStyle; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString list-style; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString listStylePosition; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString list-style-position; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString listStyleType; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString list-style-type; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString listStyleImage; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString list-style-image; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString quotes; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString counterIncrement; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString counter-increment; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString counterReset; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString counter-reset; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString overflow; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString overflowX; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString overflow-x; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString overflowY; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString overflow-y; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString overflowWrap; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString overflow-wrap; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString tableLayout; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString table-layout; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString borderCollapse; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString border-collapse; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString emptyCells; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString empty-cells; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString captionSide; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString caption-side; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString whiteSpace; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString white-space; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString writingMode; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString writing-mode; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString letterSpacing; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString letter-spacing; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString wordBreak; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString word-break; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString wordSpacing; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString word-spacing; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString wordWrap; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString word-wrap; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString textOverflow; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString text-overflow; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString textAlign; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString text-align; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString textDecoration; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString text-decoration; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString textIndent; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString text-indent; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString textJustify; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString text-justify; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString textOrientation; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString text-orientation; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString textRendering; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString text-rendering; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString textTransform; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString text-transform; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString font; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString fontFamily; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString font-family; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString fontSize; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString font-size; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString fontStretch; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString font-stretch; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString fontStyle; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString font-style; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString fontVariant; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString font-variant; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString fontWeight; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString font-weight; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString margin; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString marginBottom; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString margin-bottom; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString marginLeft; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString margin-left; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString marginRight; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString margin-right; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString marginTop; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString margin-top; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString padding; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString paddingBottom; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString padding-bottom; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString paddingLeft; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString padding-left; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString paddingRight; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString padding-right; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString paddingTop; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString padding-top; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString outline; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString outlineColor; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString outline-color; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString outlineStyle; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString outline-style; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString outlineWidth; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString outline-width; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString outlineOffset; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString outline-offset; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString position; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString pointerEvents; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString pointer-events; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString top; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString right; @@ -184,26 +274,40 @@ partial interface CSSStyleDeclaration { [SetterThrows, TreatNullAs=EmptyString] attribute DOMString height; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString minHeight; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString min-height; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString maxHeight; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString max-height; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString width; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString minWidth; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString min-width; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString maxWidth; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString max-width; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString zIndex; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString z-index; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString imageRendering; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString image-rendering; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString columnCount; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString column-count; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString columnWidth; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString column-width; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString columns; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString columnGap; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString column-gap; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString transition; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString transitionDuration; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString transition-duration; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString transitionTimingFunction; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString transition-timing-function; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString transitionProperty; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString transition-property; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString transitionDelay; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString transition-delay; [SetterThrows, TreatNullAs=EmptyString] attribute DOMString flexDirection; + [SetterThrows, TreatNullAs=EmptyString] attribute DOMString flex-direction; }; diff --git a/components/script/dom/webidls/Document.webidl b/components/script/dom/webidls/Document.webidl index b7e61248f85..203e8d00d1c 100644 --- a/components/script/dom/webidls/Document.webidl +++ b/components/script/dom/webidls/Document.webidl @@ -146,9 +146,10 @@ partial interface Document { [SameObject] readonly attribute HTMLCollection applets; - // void clear(); - // void captureEvents(); - // void releaseEvents(); + void clear(); + void captureEvents(); + void releaseEvents(); + // Tracking issue for document.all: https://github.com/servo/servo/issues/7396 // readonly attribute HTMLAllCollection all; }; diff --git a/components/script/dom/webidls/TestBinding.webidl b/components/script/dom/webidls/TestBinding.webidl index 08221f2ccc0..181909721aa 100644 --- a/components/script/dom/webidls/TestBinding.webidl +++ b/components/script/dom/webidls/TestBinding.webidl @@ -115,6 +115,8 @@ interface TestBinding { attribute (HTMLElement or long)? unionAttributeNullable; attribute (Event or DOMString)? union2AttributeNullable; [BinaryName="BinaryRenamedAttribute"] attribute DOMString attrToBinaryRename; + [BinaryName="BinaryRenamedAttribute2"] attribute DOMString attr-to-binary-rename; + attribute DOMString attr-to-automatically-rename; [PutForwards=booleanAttribute] readonly attribute TestBinding forwardedAttribute; diff --git a/components/script/dom/webidls/TestBindingProxy.webidl b/components/script/dom/webidls/TestBindingProxy.webidl index 64a15b35658..8293b7c06ae 100644 --- a/components/script/dom/webidls/TestBindingProxy.webidl +++ b/components/script/dom/webidls/TestBindingProxy.webidl @@ -15,9 +15,9 @@ interface TestBindingProxy : TestBinding { readonly attribute unsigned long length; - getter DOMString getNamedItem(DOMString name); + getter DOMString getNamedItem(DOMString item_name); - setter creator void setNamedItem(DOMString name, DOMString value); + setter creator void setNamedItem(DOMString item_name, DOMString value); getter DOMString getItem(unsigned long index); diff --git a/components/script/dom/webidls/URLUtils.webidl b/components/script/dom/webidls/URLUtils.webidl index 86e5140311b..1b8965f3d37 100644 --- a/components/script/dom/webidls/URLUtils.webidl +++ b/components/script/dom/webidls/URLUtils.webidl @@ -7,27 +7,19 @@ [NoInterfaceObject] interface URLUtils { //stringifier attribute USVString href; - readonly attribute USVString href; + [SetterThrows] + attribute USVString href; //readonly attribute USVString origin; - // attribute USVString protocol; - readonly attribute USVString protocol; - // attribute USVString username; - readonly attribute USVString username; - // attribute USVString password; - readonly attribute USVString password; - // attribute USVString host; - readonly attribute USVString host; - // attribute USVString hostname; - readonly attribute USVString hostname; - // attribute USVString port; - readonly attribute USVString port; - // attribute USVString pathname; - readonly attribute USVString pathname; - // attribute USVString search; - readonly attribute USVString search; + attribute USVString protocol; + attribute USVString username; + attribute USVString password; + attribute USVString host; + attribute USVString hostname; + attribute USVString port; + attribute USVString pathname; + attribute USVString search; // attribute URLSearchParams searchParams; - // attribute USVString hash; - readonly attribute USVString hash; + attribute USVString hash; // This is only doing as well as gecko right now, bug 824857 is on file for // adding attribute stringifier support. diff --git a/components/script/dom/webidls/Window.webidl b/components/script/dom/webidls/Window.webidl index b448ca4ffb1..f744397a379 100644 --- a/components/script/dom/webidls/Window.webidl +++ b/components/script/dom/webidls/Window.webidl @@ -93,6 +93,12 @@ partial interface Window { /*[Replaceable]*/ readonly attribute Performance performance; }; +// https://html.spec.whatwg.org/multipage/#Window-partial +partial interface Window { + void captureEvents(); + void releaseEvents(); +}; + // https://drafts.csswg.org/cssom/#extensions-to-the-window-interface partial interface Window { [NewObject] diff --git a/components/script/dom/webidls/Worker.webidl b/components/script/dom/webidls/Worker.webidl index 9e5d2c36ad9..481c2d44849 100644 --- a/components/script/dom/webidls/Worker.webidl +++ b/components/script/dom/webidls/Worker.webidl @@ -6,7 +6,7 @@ // https://www.whatwg.org/html/#abstractworker [NoInterfaceObject/*, Exposed=Window,Worker*/] interface AbstractWorker { - // attribute EventHandler onerror; + attribute EventHandler onerror; }; // https://www.whatwg.org/html/#worker diff --git a/components/script/dom/websocket.rs b/components/script/dom/websocket.rs index 9bd0610d666..4b614786efa 100644 --- a/components/script/dom/websocket.rs +++ b/components/script/dom/websocket.rs @@ -19,9 +19,10 @@ use dom::bindings::trace::JSTraceable; use dom::bindings::utils::{reflect_dom_object, Reflectable}; use dom::blob::Blob; use dom::closeevent::CloseEvent; -use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers}; -use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; +use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::messageevent::MessageEvent; +use script_task::ScriptTaskEventCategory::WebSocketEvent; use script_task::{Runnable, CommonScriptMsg}; use net_traits::hosts::replace_hosts; @@ -67,7 +68,6 @@ enum MessageData { } #[dom_struct] -#[derive(HeapSizeOf)] pub struct WebSocket { eventtarget: EventTarget, url: Url, @@ -183,7 +183,7 @@ impl WebSocket { let task = box CloseTask { addr: address, }; - sender.send(CommonScriptMsg::RunnableMsg(task)).unwrap(); + sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, task)).unwrap(); return; } }; @@ -193,7 +193,7 @@ impl WebSocket { addr: address.clone(), sender: ws_sender.clone(), }; - sender.send(CommonScriptMsg::RunnableMsg(open_task)).unwrap(); + sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, open_task)).unwrap(); for message in receiver.incoming_messages() { let message = match message { @@ -209,7 +209,7 @@ impl WebSocket { let task = box CloseTask { addr: address, }; - sender.send(CommonScriptMsg::RunnableMsg(task)).unwrap(); + sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, task)).unwrap(); break; }, Err(_) => break, @@ -218,7 +218,7 @@ impl WebSocket { address: address.clone(), message: message, }; - sender.send(CommonScriptMsg::RunnableMsg(message_task)).unwrap(); + sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, message_task)).unwrap(); } }); @@ -227,34 +227,41 @@ impl WebSocket { } } -impl<'a> WebSocketMethods for &'a WebSocket { +impl WebSocketMethods for WebSocket { + // https://html.spec.whatwg.org/multipage/#handler-websocket-onopen event_handler!(open, GetOnopen, SetOnopen); + + // https://html.spec.whatwg.org/multipage/#handler-websocket-onclose event_handler!(close, GetOnclose, SetOnclose); + + // https://html.spec.whatwg.org/multipage/#handler-websocket-onerror event_handler!(error, GetOnerror, SetOnerror); + + // https://html.spec.whatwg.org/multipage/#handler-websocket-onmessage event_handler!(message, GetOnmessage, SetOnmessage); // https://html.spec.whatwg.org/multipage/#dom-websocket-url - fn Url(self) -> DOMString { + fn Url(&self) -> DOMString { self.url.serialize() } // https://html.spec.whatwg.org/multipage/#dom-websocket-readystate - fn ReadyState(self) -> u16 { + fn ReadyState(&self) -> u16 { self.ready_state.get() as u16 } // https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype - fn BinaryType(self) -> BinaryType { + fn BinaryType(&self) -> BinaryType { self.binary_type.get() } // https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype - fn SetBinaryType(self, btype: BinaryType) { + fn SetBinaryType(&self, btype: BinaryType) { self.binary_type.set(btype) } // https://html.spec.whatwg.org/multipage/#dom-websocket-send - fn Send(self, data: Option) -> Fallible<()> { + fn Send(&self, data: Option) -> Fallible<()> { match self.ready_state.get() { WebSocketRequestState::Connecting => { return Err(Error::InvalidState); @@ -281,7 +288,7 @@ impl<'a> WebSocketMethods for &'a WebSocket { } // https://html.spec.whatwg.org/multipage/#dom-websocket-close - fn Close(self, code: Option, reason: Option) -> Fallible<()>{ + fn Close(&self, code: Option, reason: Option) -> Fallible<()>{ fn send_close(this: &WebSocket) { this.ready_state.set(WebSocketRequestState::Closing); diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index c6bfcd2519e..c463efa9f69 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -21,12 +21,12 @@ use dom::browsercontext::BrowsingContext; use dom::console::Console; use dom::crypto::Crypto; use dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration}; -use dom::document::{Document, DocumentHelpers}; +use dom::document::Document; use dom::element::Element; -use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::location::Location; use dom::navigator::Navigator; -use dom::node::{window_from_node, TrustedNodeAddress, NodeHelpers, from_untrusted_node_address}; +use dom::node::{window_from_node, TrustedNodeAddress, from_untrusted_node_address}; use dom::performance::Performance; use dom::screen::Screen; use dom::storage::Storage; @@ -40,7 +40,6 @@ use timers::{IsInterval, TimerId, TimerManager, TimerCallback}; use webdriver_handlers::jsval_to_webdriver; use devtools_traits::{ScriptToDevtoolsControlMsg, TimelineMarker, TimelineMarkerType}; -use devtools_traits::{TracingMetadata}; use msg::compositor_msg::ScriptToCompositorMsg; use msg::constellation_msg::{LoadData, PipelineId, SubpageId, ConstellationChan, WindowSizeData, WorkerId}; use msg::webdriver_msg::{WebDriverJSError, WebDriverJSResult}; @@ -105,7 +104,6 @@ pub enum ReflowReason { } #[dom_struct] -#[derive(HeapSizeOf)] pub struct Window { eventtarget: EventTarget, #[ignore_heap_size_of = "trait objects are hard"] @@ -357,9 +355,9 @@ pub fn base64_atob(input: DOMString) -> Fallible { } } -impl<'a> WindowMethods for &'a Window { +impl WindowMethods for Window { // https://html.spec.whatwg.org/#dom-alert - fn Alert(self, s: DOMString) { + fn Alert(&self, s: DOMString) { // Right now, just print to the console // Ensure that stderr doesn't trample through the alert() we use to // communicate test results. @@ -373,52 +371,52 @@ impl<'a> WindowMethods for &'a Window { } // https://html.spec.whatwg.org/multipage/#dom-window-close - fn Close(self) { + fn Close(&self) { self.main_thread_script_chan().send(MainThreadScriptMsg::ExitWindow(self.id.clone())).unwrap(); } // https://html.spec.whatwg.org/multipage/#dom-document-0 - fn Document(self) -> Root { + fn Document(&self) -> Root { self.browsing_context().as_ref().unwrap().active_document() } // https://html.spec.whatwg.org/#dom-location - fn Location(self) -> Root { + fn Location(&self) -> Root { self.Document().r().Location() } // https://html.spec.whatwg.org/#dom-sessionstorage - fn SessionStorage(self) -> Root { + fn SessionStorage(&self) -> Root { self.session_storage.or_init(|| Storage::new(&GlobalRef::Window(self), StorageType::Session)) } // https://html.spec.whatwg.org/#dom-localstorage - fn LocalStorage(self) -> Root { + fn LocalStorage(&self) -> Root { self.local_storage.or_init(|| Storage::new(&GlobalRef::Window(self), StorageType::Local)) } // https://developer.mozilla.org/en-US/docs/Web/API/Console - fn Console(self) -> Root { + fn Console(&self) -> Root { self.console.or_init(|| Console::new(GlobalRef::Window(self))) } // https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#dfn-GlobalCrypto - fn Crypto(self) -> Root { + fn Crypto(&self) -> Root { self.crypto.or_init(|| Crypto::new(GlobalRef::Window(self))) } // https://html.spec.whatwg.org/#dom-frameelement - fn GetFrameElement(self) -> Option> { + fn GetFrameElement(&self) -> Option> { self.browsing_context().as_ref().unwrap().frame_element() } // https://html.spec.whatwg.org/#dom-navigator - fn Navigator(self) -> Root { + fn Navigator(&self) -> Root { self.navigator.or_init(|| Navigator::new(self)) } // https://html.spec.whatwg.org/#dom-windowtimers-settimeout - fn SetTimeout(self, _cx: *mut JSContext, callback: Rc, timeout: i32, args: Vec) -> i32 { + fn SetTimeout(&self, _cx: *mut JSContext, callback: Rc, timeout: i32, args: Vec) -> i32 { self.timers.set_timeout_or_interval(TimerCallback::FunctionTimerCallback(callback), args, timeout, @@ -428,7 +426,7 @@ impl<'a> WindowMethods for &'a Window { } // https://html.spec.whatwg.org/#dom-windowtimers-settimeout - fn SetTimeout_(self, _cx: *mut JSContext, callback: DOMString, timeout: i32, args: Vec) -> i32 { + fn SetTimeout_(&self, _cx: *mut JSContext, callback: DOMString, timeout: i32, args: Vec) -> i32 { self.timers.set_timeout_or_interval(TimerCallback::StringTimerCallback(callback), args, timeout, @@ -438,12 +436,12 @@ impl<'a> WindowMethods for &'a Window { } // https://html.spec.whatwg.org/#dom-windowtimers-cleartimeout - fn ClearTimeout(self, handle: i32) { + fn ClearTimeout(&self, handle: i32) { self.timers.clear_timeout_or_interval(handle); } // https://html.spec.whatwg.org/#dom-windowtimers-setinterval - fn SetInterval(self, _cx: *mut JSContext, callback: Rc, timeout: i32, args: Vec) -> i32 { + fn SetInterval(&self, _cx: *mut JSContext, callback: Rc, timeout: i32, args: Vec) -> i32 { self.timers.set_timeout_or_interval(TimerCallback::FunctionTimerCallback(callback), args, timeout, @@ -453,7 +451,7 @@ impl<'a> WindowMethods for &'a Window { } // https://html.spec.whatwg.org/#dom-windowtimers-setinterval - fn SetInterval_(self, _cx: *mut JSContext, callback: DOMString, timeout: i32, args: Vec) -> i32 { + fn SetInterval_(&self, _cx: *mut JSContext, callback: DOMString, timeout: i32, args: Vec) -> i32 { self.timers.set_timeout_or_interval(TimerCallback::StringTimerCallback(callback), args, timeout, @@ -463,32 +461,32 @@ impl<'a> WindowMethods for &'a Window { } // https://html.spec.whatwg.org/#dom-windowtimers-clearinterval - fn ClearInterval(self, handle: i32) { + fn ClearInterval(&self, handle: i32) { self.ClearTimeout(handle); } // https://html.spec.whatwg.org/multipage/#dom-window - fn Window(self) -> Root { + fn Window(&self) -> Root { Root::from_ref(self) } // https://html.spec.whatwg.org/multipage/#dom-self - fn Self_(self) -> Root { + fn Self_(&self) -> Root { self.Window() } // https://www.whatwg.org/html/#dom-frames - fn Frames(self) -> Root { + fn Frames(&self) -> Root { self.Window() } // https://html.spec.whatwg.org/multipage/#dom-parent - fn Parent(self) -> Root { + fn Parent(&self) -> Root { self.parent().unwrap_or(self.Window()) } // https://html.spec.whatwg.org/multipage/#dom-top - fn Top(self) -> Root { + fn Top(&self) -> Root { let mut window = self.Window(); while let Some(parent) = window.parent() { window = parent; @@ -498,34 +496,39 @@ impl<'a> WindowMethods for &'a Window { // https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/ // NavigationTiming/Overview.html#sec-window.performance-attribute - fn Performance(self) -> Root { + fn Performance(&self) -> Root { self.performance.or_init(|| { Performance::new(self, self.navigation_start, self.navigation_start_precise) }) } + // https://html.spec.whatwg.org/multipage/#globaleventhandlers global_event_handlers!(); + + // https://html.spec.whatwg.org/multipage/#handler-window-onunload event_handler!(unload, GetOnunload, SetOnunload); + + // https://html.spec.whatwg.org/multipage/#handler-onerror error_event_handler!(error, GetOnerror, SetOnerror); // https://developer.mozilla.org/en-US/docs/Web/API/Window/screen - fn Screen(self) -> Root { + fn Screen(&self) -> Root { self.screen.or_init(|| Screen::new(self)) } // https://html.spec.whatwg.org/multipage/#dom-windowbase64-btoa - fn Btoa(self, btoa: DOMString) -> Fallible { + fn Btoa(&self, btoa: DOMString) -> Fallible { base64_btoa(btoa) } // https://html.spec.whatwg.org/multipage/#dom-windowbase64-atob - fn Atob(self, atob: DOMString) -> Fallible { + fn Atob(&self, atob: DOMString) -> Fallible { base64_atob(atob) } /// https://html.spec.whatwg.org/multipage/#dom-window-requestanimationframe - fn RequestAnimationFrame(self, callback: Rc) -> i32 { + fn RequestAnimationFrame(&self, callback: Rc) -> i32 { let doc = self.Document(); let callback = move |now: f64| { @@ -538,28 +541,38 @@ impl<'a> WindowMethods for &'a Window { } /// https://html.spec.whatwg.org/multipage/#dom-window-cancelanimationframe - fn CancelAnimationFrame(self, ident: i32) { + fn CancelAnimationFrame(&self, ident: i32) { let doc = self.Document(); doc.r().cancel_animation_frame(ident); } + // https://html.spec.whatwg.org/multipage/#dom-window-captureevents + fn CaptureEvents(&self) { + // This method intentionally does nothing + } + + // https://html.spec.whatwg.org/multipage/#dom-window-releaseevents + fn ReleaseEvents(&self) { + // This method intentionally does nothing + } + // check-tidy: no specs after this line - fn Debug(self, message: DOMString) { + fn Debug(&self, message: DOMString) { debug!("{}", message); } #[allow(unsafe_code)] - fn Gc(self) { + fn Gc(&self) { unsafe { JS_GC(JS_GetRuntime(self.get_cx())); } } - fn Trap(self) { + fn Trap(&self) { breakpoint(); } - fn WebdriverCallback(self, cx: *mut JSContext, val: HandleValue) { + fn WebdriverCallback(&self, cx: *mut JSContext, val: HandleValue) { let rv = jsval_to_webdriver(cx, val); let opt_chan = self.webdriver_script_chan.borrow_mut().take(); if let Some(chan) = opt_chan { @@ -567,7 +580,7 @@ impl<'a> WindowMethods for &'a Window { } } - fn WebdriverTimeout(self) { + fn WebdriverTimeout(&self) { let opt_chan = self.webdriver_script_chan.borrow_mut().take(); if let Some(chan) = opt_chan { chan.send(Err(WebDriverJSError::Timeout)).unwrap(); @@ -575,7 +588,7 @@ impl<'a> WindowMethods for &'a Window { } // https://drafts.csswg.org/cssom/#dom-window-getcomputedstyle - fn GetComputedStyle(self, + fn GetComputedStyle(&self, element: &Element, pseudo: Option) -> Root { // Steps 1-4. @@ -592,54 +605,6 @@ impl<'a> WindowMethods for &'a Window { } } -pub trait WindowHelpers { - fn clear_js_runtime(self); - fn init_browsing_context(self, doc: &Document, frame_element: Option<&Element>); - fn load_url(self, url: Url); - fn handle_fire_timer(self, timer_id: TimerId); - fn force_reflow(self, goal: ReflowGoal, query_type: ReflowQueryType, reason: ReflowReason); - fn reflow(self, goal: ReflowGoal, query_type: ReflowQueryType, reason: ReflowReason); - fn join_layout(self); - fn layout(&self) -> &LayoutRPC; - fn content_box_query(self, content_box_request: TrustedNodeAddress) -> Rect; - fn content_boxes_query(self, content_boxes_request: TrustedNodeAddress) -> Vec>; - fn client_rect_query(self, node_geometry_request: TrustedNodeAddress) -> Rect; - fn resolved_style_query(self, element: TrustedNodeAddress, - pseudo: Option, property: &Atom) -> Option; - fn offset_parent_query(self, node: TrustedNodeAddress) -> (Option>, Rect); - fn handle_reflow_complete_msg(self, reflow_id: u32); - fn set_fragment_name(self, fragment: Option); - fn steal_fragment_name(self) -> Option; - fn set_window_size(self, size: WindowSizeData); - fn window_size(self) -> Option; - fn get_url(self) -> Url; - fn resource_task(self) -> ResourceTask; - fn mem_profiler_chan(self) -> mem::ProfilerChan; - fn devtools_chan(self) -> Option>; - fn layout_chan(self) -> LayoutChan; - fn constellation_chan(self) -> ConstellationChan; - fn windowproxy_handler(self) -> WindowProxyHandler; - fn get_next_subpage_id(self) -> SubpageId; - fn layout_is_idle(self) -> bool; - fn get_pending_reflow_count(self) -> u32; - fn add_pending_reflow(self); - fn set_resize_event(self, event: WindowSizeData); - fn steal_resize_event(self) -> Option; - fn set_page_clip_rect_with_new_viewport(self, viewport: Rect) -> bool; - fn set_devtools_wants_updates(self, value: bool); - fn IndexedGetter(self, _index: u32, _found: &mut bool) -> Option>; - fn thaw(self); - fn freeze(self); - fn need_emit_timeline_marker(self, timeline_type: TimelineMarkerType) -> bool; - fn emit_timeline_marker(self, marker: TimelineMarker); - fn set_devtools_timeline_marker(self, - marker: TimelineMarkerType, - reply: IpcSender); - fn drop_devtools_timeline_markers(self); - fn set_webdriver_script_chan(self, chan: Option>); - fn is_alive(self) -> bool; - fn parent(self) -> Option>; -} pub trait ScriptHelpers { fn evaluate_js_on_global_with_result(self, code: &str, @@ -678,8 +643,8 @@ impl<'a, T: Reflectable> ScriptHelpers for &'a T { } } -impl<'a> WindowHelpers for &'a Window { - fn clear_js_runtime(self) { +impl Window { + pub fn clear_js_runtime(&self) { let document = self.Document(); NodeCast::from_ref(document.r()).teardown(); @@ -704,7 +669,7 @@ impl<'a> WindowHelpers for &'a Window { /// and no reflow is performed. /// /// TODO(pcwalton): Only wait for style recalc, since we have off-main-thread layout. - fn force_reflow(self, goal: ReflowGoal, query_type: ReflowQueryType, reason: ReflowReason) { + pub fn force_reflow(&self, goal: ReflowGoal, query_type: ReflowQueryType, reason: ReflowReason) { let document = self.Document(); let root = document.r().GetDocumentElement(); let root = match root.r() { @@ -720,10 +685,11 @@ impl<'a> WindowHelpers for &'a Window { debug!("script: performing reflow for goal {:?} reason {:?}", goal, reason); - if self.need_emit_timeline_marker(TimelineMarkerType::Reflow) { - let marker = TimelineMarker::new("Reflow".to_owned(), TracingMetadata::IntervalStart); - self.emit_timeline_marker(marker); - } + let marker = if self.need_emit_timeline_marker(TimelineMarkerType::Reflow) { + Some(TimelineMarker::start("Reflow".to_owned())) + } else { + None + }; // Layout will let us know when it's done. let (join_chan, join_port) = channel(); @@ -764,9 +730,8 @@ impl<'a> WindowHelpers for &'a Window { self.pending_reflow_count.set(0); - if self.need_emit_timeline_marker(TimelineMarkerType::Reflow) { - let marker = TimelineMarker::new("Reflow".to_owned(), TracingMetadata::IntervalEnd); - self.emit_timeline_marker(marker); + if let Some(marker) = marker { + self.emit_timeline_marker(marker.end()); } } @@ -775,7 +740,7 @@ impl<'a> WindowHelpers for &'a Window { /// yet, the page is presumed invisible and no reflow is performed. /// /// TODO(pcwalton): Only wait for style recalc, since we have off-main-thread layout. - fn reflow(self, goal: ReflowGoal, query_type: ReflowQueryType, reason: ReflowReason) { + pub fn reflow(&self, goal: ReflowGoal, query_type: ReflowQueryType, reason: ReflowReason) { let document = self.Document(); let root = document.r().GetDocumentElement(); let root = match root.r() { @@ -798,7 +763,7 @@ impl<'a> WindowHelpers for &'a Window { /// Sends a ping to layout and waits for the response. The response will arrive when the /// layout task has finished any pending request messages. - fn join_layout(self) { + pub fn join_layout(&self) { let mut layout_join_port = self.layout_join_port.borrow_mut(); if let Some(join_port) = std_mem::replace(&mut *layout_join_port, None) { match join_port.try_recv() { @@ -816,11 +781,11 @@ impl<'a> WindowHelpers for &'a Window { } } - fn layout(&self) -> &LayoutRPC { + pub fn layout(&self) -> &LayoutRPC { &*self.layout_rpc } - fn content_box_query(self, content_box_request: TrustedNodeAddress) -> Rect { + pub fn content_box_query(&self, content_box_request: TrustedNodeAddress) -> Rect { self.reflow(ReflowGoal::ForScriptQuery, ReflowQueryType::ContentBoxQuery(content_box_request), ReflowReason::Query); @@ -829,7 +794,7 @@ impl<'a> WindowHelpers for &'a Window { rect } - fn content_boxes_query(self, content_boxes_request: TrustedNodeAddress) -> Vec> { + pub fn content_boxes_query(&self, content_boxes_request: TrustedNodeAddress) -> Vec> { self.reflow(ReflowGoal::ForScriptQuery, ReflowQueryType::ContentBoxesQuery(content_boxes_request), ReflowReason::Query); @@ -838,14 +803,14 @@ impl<'a> WindowHelpers for &'a Window { rects } - fn client_rect_query(self, node_geometry_request: TrustedNodeAddress) -> Rect { + pub fn client_rect_query(&self, node_geometry_request: TrustedNodeAddress) -> Rect { self.reflow(ReflowGoal::ForScriptQuery, ReflowQueryType::NodeGeometryQuery(node_geometry_request), ReflowReason::Query); self.layout_rpc.node_geometry().client_rect } - fn resolved_style_query(self, + pub fn resolved_style_query(&self, element: TrustedNodeAddress, pseudo: Option, property: &Atom) -> Option { @@ -856,7 +821,7 @@ impl<'a> WindowHelpers for &'a Window { resolved } - fn offset_parent_query(self, node: TrustedNodeAddress) -> (Option>, Rect) { + pub fn offset_parent_query(&self, node: TrustedNodeAddress) -> (Option>, Rect) { self.reflow(ReflowGoal::ForScriptQuery, ReflowQueryType::OffsetParentQuery(node), ReflowReason::Query); @@ -877,105 +842,105 @@ impl<'a> WindowHelpers for &'a Window { (element, response.rect) } - fn handle_reflow_complete_msg(self, reflow_id: u32) { + pub fn handle_reflow_complete_msg(&self, reflow_id: u32) { let last_reflow_id = self.last_reflow_id.get(); if last_reflow_id == reflow_id { *self.layout_join_port.borrow_mut() = None; } } - fn init_browsing_context(self, doc: &Document, frame_element: Option<&Element>) { + pub fn init_browsing_context(&self, doc: &Document, frame_element: Option<&Element>) { let mut browsing_context = self.browsing_context.borrow_mut(); *browsing_context = Some(BrowsingContext::new(doc, frame_element)); (*browsing_context).as_mut().unwrap().create_window_proxy(); } /// Commence a new URL load which will either replace this window or scroll to a fragment. - fn load_url(self, url: Url) { + pub fn load_url(&self, url: Url) { self.main_thread_script_chan().send( MainThreadScriptMsg::Navigate(self.id, LoadData::new(url))).unwrap(); } - fn handle_fire_timer(self, timer_id: TimerId) { + pub fn handle_fire_timer(&self, timer_id: TimerId) { self.timers.fire_timer(timer_id, self); self.reflow(ReflowGoal::ForDisplay, ReflowQueryType::NoQuery, ReflowReason::Timer); } - fn set_fragment_name(self, fragment: Option) { + pub fn set_fragment_name(&self, fragment: Option) { *self.fragment_name.borrow_mut() = fragment; } - fn steal_fragment_name(self) -> Option { + pub fn steal_fragment_name(&self) -> Option { self.fragment_name.borrow_mut().take() } - fn set_window_size(self, size: WindowSizeData) { + pub fn set_window_size(&self, size: WindowSizeData) { self.window_size.set(Some(size)); } - fn window_size(self) -> Option { + pub fn window_size(&self) -> Option { self.window_size.get() } - fn get_url(self) -> Url { + pub fn get_url(&self) -> Url { let doc = self.Document(); doc.r().url() } - fn resource_task(self) -> ResourceTask { + pub fn resource_task(&self) -> ResourceTask { (*self.resource_task).clone() } - fn mem_profiler_chan(self) -> mem::ProfilerChan { + pub fn mem_profiler_chan(&self) -> mem::ProfilerChan { self.mem_profiler_chan.clone() } - fn devtools_chan(self) -> Option> { + pub fn devtools_chan(&self) -> Option> { self.devtools_chan.clone() } - fn layout_chan(self) -> LayoutChan { + pub fn layout_chan(&self) -> LayoutChan { self.layout_chan.clone() } - fn constellation_chan(self) -> ConstellationChan { + pub fn constellation_chan(&self) -> ConstellationChan { self.constellation_chan.clone() } - fn windowproxy_handler(self) -> WindowProxyHandler { + pub fn windowproxy_handler(&self) -> WindowProxyHandler { WindowProxyHandler(self.dom_static.windowproxy_handler.0) } - fn get_next_subpage_id(self) -> SubpageId { + pub fn get_next_subpage_id(&self) -> SubpageId { let subpage_id = self.next_subpage_id.get(); let SubpageId(id_num) = subpage_id; self.next_subpage_id.set(SubpageId(id_num + 1)); subpage_id } - fn layout_is_idle(self) -> bool { + pub fn layout_is_idle(&self) -> bool { self.layout_join_port.borrow().is_none() } - fn get_pending_reflow_count(self) -> u32 { + pub fn get_pending_reflow_count(&self) -> u32 { self.pending_reflow_count.get() } - fn add_pending_reflow(self) { + pub fn add_pending_reflow(&self) { self.pending_reflow_count.set(self.pending_reflow_count.get() + 1); } - fn set_resize_event(self, event: WindowSizeData) { + pub fn set_resize_event(&self, event: WindowSizeData) { self.resize_event.set(Some(event)); } - fn steal_resize_event(self) -> Option { + pub fn steal_resize_event(&self) -> Option { let event = self.resize_event.get(); self.resize_event.set(None); event } - fn set_page_clip_rect_with_new_viewport(self, viewport: Rect) -> bool { + pub fn set_page_clip_rect_with_new_viewport(&self, viewport: Rect) -> bool { // We use a clipping rectangle that is five times the size of the of the viewport, // 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. @@ -1000,16 +965,16 @@ impl<'a> WindowHelpers for &'a Window { had_clip_rect } - fn set_devtools_wants_updates(self, value: bool) { + pub fn set_devtools_wants_updates(&self, value: bool) { self.devtools_wants_updates.set(value); } // https://html.spec.whatwg.org/multipage/#accessing-other-browsing-contexts - fn IndexedGetter(self, _index: u32, _found: &mut bool) -> Option> { + pub fn IndexedGetter(&self, _index: u32, _found: &mut bool) -> Option> { None } - fn thaw(self) { + pub fn thaw(&self) { self.timers.resume(); // Push the document title to the compositor since we are @@ -1018,42 +983,42 @@ impl<'a> WindowHelpers for &'a Window { document.r().title_changed(); } - fn freeze(self) { + pub fn freeze(&self) { self.timers.suspend(); } - fn need_emit_timeline_marker(self, timeline_type: TimelineMarkerType) -> bool { + pub fn need_emit_timeline_marker(&self, timeline_type: TimelineMarkerType) -> bool { let markers = self.devtools_markers.borrow(); markers.contains(&timeline_type) } - fn emit_timeline_marker(self, marker: TimelineMarker) { + pub fn emit_timeline_marker(&self, marker: TimelineMarker) { let sender = self.devtools_marker_sender.borrow(); let sender = sender.as_ref().expect("There is no marker sender"); sender.send(marker).unwrap(); } - fn set_devtools_timeline_marker(self, + pub fn set_devtools_timeline_marker(&self, marker: TimelineMarkerType, reply: IpcSender) { *self.devtools_marker_sender.borrow_mut() = Some(reply); self.devtools_markers.borrow_mut().insert(marker); } - fn drop_devtools_timeline_markers(self) { + pub fn drop_devtools_timeline_markers(&self) { self.devtools_markers.borrow_mut().clear(); *self.devtools_marker_sender.borrow_mut() = None; } - fn set_webdriver_script_chan(self, chan: Option>) { + pub fn set_webdriver_script_chan(&self, chan: Option>) { *self.webdriver_script_chan.borrow_mut() = chan; } - fn is_alive(self) -> bool { + pub fn is_alive(&self) -> bool { self.current_state.get() == WindowState::Alive } - fn parent(self) -> Option> { + pub fn parent(&self) -> Option> { let browsing_context = self.browsing_context(); let browsing_context = browsing_context.as_ref().unwrap(); diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index 2ba0e1e3f62..2711e8502db 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -16,10 +16,9 @@ use dom::bindings::trace::JSTraceable; use dom::bindings::utils::{Reflectable, reflect_dom_object}; use dom::dedicatedworkerglobalscope::{DedicatedWorkerGlobalScope, WorkerScriptMsg}; use dom::errorevent::ErrorEvent; -use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers}; -use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; +use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::messageevent::MessageEvent; -use dom::window::WindowHelpers; use dom::workerglobalscope::WorkerGlobalScopeInit; use devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg}; @@ -39,7 +38,6 @@ pub type TrustedWorkerAddress = Trusted; // https://html.spec.whatwg.org/multipage/#worker #[dom_struct] -#[derive(HeapSizeOf)] pub struct Worker { eventtarget: EventTarget, global: GlobalField, @@ -155,16 +153,20 @@ impl Worker { } } -impl<'a> WorkerMethods for &'a Worker { +impl WorkerMethods for Worker { // https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-postmessage - fn PostMessage(self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { + fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { let data = try!(StructuredCloneData::write(cx, message)); let address = Trusted::new(cx, self, self.global.root().r().script_chan().clone()); self.sender.send((address, WorkerScriptMsg::DOMMessage(data))).unwrap(); Ok(()) } + // https://html.spec.whatwg.org/multipage/#handler-dedicatedworkerglobalscope-onmessage event_handler!(message, GetOnmessage, SetOnmessage); + + // https://html.spec.whatwg.org/multipage/#handler-workerglobalscope-onerror + event_handler!(error, GetOnerror, SetOnerror); } pub struct WorkerMessageHandler { @@ -188,20 +190,20 @@ impl Runnable for WorkerMessageHandler { } } -pub struct WorkerEventHandler { +pub struct SimpleWorkerErrorHandler { addr: TrustedWorkerAddress, } -impl WorkerEventHandler { - pub fn new(addr: TrustedWorkerAddress) -> WorkerEventHandler { - WorkerEventHandler { +impl SimpleWorkerErrorHandler { + pub fn new(addr: TrustedWorkerAddress) -> SimpleWorkerErrorHandler { + SimpleWorkerErrorHandler { addr: addr } } } -impl Runnable for WorkerEventHandler { - fn handler(self: Box) { +impl Runnable for SimpleWorkerErrorHandler { + fn handler(self: Box) { let this = *self; Worker::dispatch_simple_error(this.addr); } diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 18f7f442d30..3bc805a67e6 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -12,7 +12,6 @@ use dom::bindings::js::{JS, Root, MutNullableHeap}; use dom::bindings::utils::Reflectable; use dom::console::Console; use dom::crypto::Crypto; -use dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScopeHelpers; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::window::{base64_atob, base64_btoa}; use dom::workerlocation::WorkerLocation; @@ -53,7 +52,6 @@ pub struct WorkerGlobalScopeInit { // https://html.spec.whatwg.org/multipage/#the-workerglobalscope-common-interface #[dom_struct] -#[derive(HeapSizeOf)] pub struct WorkerGlobalScope { eventtarget: EventTarget, worker_id: WorkerId, @@ -163,21 +161,21 @@ impl WorkerGlobalScope { } } -impl<'a> WorkerGlobalScopeMethods for &'a WorkerGlobalScope { +impl WorkerGlobalScopeMethods for WorkerGlobalScope { // https://html.spec.whatwg.org/multipage/#dom-workerglobalscope-self - fn Self_(self) -> Root { + fn Self_(&self) -> Root { Root::from_ref(self) } // https://html.spec.whatwg.org/multipage/#dom-workerglobalscope-location - fn Location(self) -> Root { + fn Location(&self) -> Root { self.location.or_init(|| { WorkerLocation::new(self, self.worker_url.clone()) }) } // https://html.spec.whatwg.org/multipage/#dom-workerglobalscope-importscripts - fn ImportScripts(self, url_strings: Vec) -> ErrorResult { + fn ImportScripts(&self, url_strings: Vec) -> ErrorResult { let mut urls = Vec::with_capacity(url_strings.len()); for url in url_strings { let url = UrlParser::new().base_url(&self.worker_url) @@ -210,32 +208,32 @@ impl<'a> WorkerGlobalScopeMethods for &'a WorkerGlobalScope { } // https://html.spec.whatwg.org/multipage/#dom-worker-navigator - fn Navigator(self) -> Root { + fn Navigator(&self) -> Root { self.navigator.or_init(|| WorkerNavigator::new(self)) } // https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/console - fn Console(self) -> Root { + fn Console(&self) -> Root { self.console.or_init(|| Console::new(GlobalRef::Worker(self))) } // https://html.spec.whatwg.org/multipage/#dfn-Crypto - fn Crypto(self) -> Root { + fn Crypto(&self) -> Root { self.crypto.or_init(|| Crypto::new(GlobalRef::Worker(self))) } // https://html.spec.whatwg.org/multipage/#dom-windowbase64-btoa - fn Btoa(self, btoa: DOMString) -> Fallible { + fn Btoa(&self, btoa: DOMString) -> Fallible { base64_btoa(btoa) } // https://html.spec.whatwg.org/multipage/#dom-windowbase64-atob - fn Atob(self, atob: DOMString) -> Fallible { + fn Atob(&self, atob: DOMString) -> Fallible { base64_atob(atob) } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - fn SetTimeout(self, _cx: *mut JSContext, callback: Rc, timeout: i32, args: Vec) -> i32 { + fn SetTimeout(&self, _cx: *mut JSContext, callback: Rc, timeout: i32, args: Vec) -> i32 { self.timers.set_timeout_or_interval(TimerCallback::FunctionTimerCallback(callback), args, timeout, @@ -245,7 +243,7 @@ impl<'a> WorkerGlobalScopeMethods for &'a WorkerGlobalScope { } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - fn SetTimeout_(self, _cx: *mut JSContext, callback: DOMString, timeout: i32, args: Vec) -> i32 { + fn SetTimeout_(&self, _cx: *mut JSContext, callback: DOMString, timeout: i32, args: Vec) -> i32 { self.timers.set_timeout_or_interval(TimerCallback::StringTimerCallback(callback), args, timeout, @@ -255,12 +253,12 @@ impl<'a> WorkerGlobalScopeMethods for &'a WorkerGlobalScope { } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-clearinterval - fn ClearTimeout(self, handle: i32) { + fn ClearTimeout(&self, handle: i32) { self.timers.clear_timeout_or_interval(handle); } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - fn SetInterval(self, _cx: *mut JSContext, callback: Rc, timeout: i32, args: Vec) -> i32 { + fn SetInterval(&self, _cx: *mut JSContext, callback: Rc, timeout: i32, args: Vec) -> i32 { self.timers.set_timeout_or_interval(TimerCallback::FunctionTimerCallback(callback), args, timeout, @@ -270,7 +268,7 @@ impl<'a> WorkerGlobalScopeMethods for &'a WorkerGlobalScope { } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval - fn SetInterval_(self, _cx: *mut JSContext, callback: DOMString, timeout: i32, args: Vec) -> i32 { + fn SetInterval_(&self, _cx: *mut JSContext, callback: DOMString, timeout: i32, args: Vec) -> i32 { self.timers.set_timeout_or_interval(TimerCallback::StringTimerCallback(callback), args, timeout, @@ -280,24 +278,14 @@ impl<'a> WorkerGlobalScopeMethods for &'a WorkerGlobalScope { } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-clearinterval - fn ClearInterval(self, handle: i32) { + fn ClearInterval(&self, handle: i32) { self.ClearTimeout(handle); } } -pub trait WorkerGlobalScopeHelpers { - fn execute_script(self, source: DOMString); - fn handle_fire_timer(self, timer_id: TimerId); - fn script_chan(self) -> Box; - fn pipeline(self) -> PipelineId; - fn new_script_pair(self) -> (Box, Box); - fn process_event(self, msg: CommonScriptMsg); - fn get_cx(self) -> *mut JSContext; - fn set_devtools_wants_updates(self, value: bool); -} -impl<'a> WorkerGlobalScopeHelpers for &'a WorkerGlobalScope { - fn execute_script(self, source: DOMString) { +impl WorkerGlobalScope { + pub fn execute_script(&self, source: DOMString) { match self.runtime.evaluate_script( self.reflector().get_jsobject(), source, self.worker_url.serialize(), 1) { Ok(_) => (), @@ -311,7 +299,7 @@ impl<'a> WorkerGlobalScopeHelpers for &'a WorkerGlobalScope { } } - fn script_chan(self) -> Box { + pub fn script_chan(&self) -> Box { let dedicated = DedicatedWorkerGlobalScopeCast::to_ref(self); match dedicated { @@ -320,7 +308,7 @@ impl<'a> WorkerGlobalScopeHelpers for &'a WorkerGlobalScope { } } - fn pipeline(self) -> PipelineId { + pub fn pipeline(&self) -> PipelineId { let dedicated = DedicatedWorkerGlobalScopeCast::to_ref(self); match dedicated { @@ -329,7 +317,7 @@ impl<'a> WorkerGlobalScopeHelpers for &'a WorkerGlobalScope { } } - fn new_script_pair(self) -> (Box, Box) { + pub fn new_script_pair(&self) -> (Box, Box) { let dedicated = DedicatedWorkerGlobalScopeCast::to_ref(self); match dedicated { @@ -338,7 +326,7 @@ impl<'a> WorkerGlobalScopeHelpers for &'a WorkerGlobalScope { } } - fn process_event(self, msg: CommonScriptMsg) { + pub fn process_event(&self, msg: CommonScriptMsg) { let dedicated = DedicatedWorkerGlobalScopeCast::to_ref(self); match dedicated { @@ -347,15 +335,11 @@ impl<'a> WorkerGlobalScopeHelpers for &'a WorkerGlobalScope { } } - fn handle_fire_timer(self, timer_id: TimerId) { + pub fn handle_fire_timer(&self, timer_id: TimerId) { self.timers.fire_timer(timer_id, self); } - fn get_cx(self) -> *mut JSContext { - self.runtime.cx() - } - - fn set_devtools_wants_updates(self, value: bool) { + pub fn set_devtools_wants_updates(&self, value: bool) { self.devtools_wants_updates.set(value); } } diff --git a/components/script/dom/workerlocation.rs b/components/script/dom/workerlocation.rs index f4f9209445a..bd62cc57043 100644 --- a/components/script/dom/workerlocation.rs +++ b/components/script/dom/workerlocation.rs @@ -16,7 +16,6 @@ use util::str::DOMString; // https://html.spec.whatwg.org/multipage/#worker-locations #[dom_struct] -#[derive(HeapSizeOf)] pub struct WorkerLocation { reflector_: Reflector, url: Url, @@ -37,50 +36,49 @@ impl WorkerLocation { } } -impl<'a> WorkerLocationMethods for &'a WorkerLocation { +impl WorkerLocationMethods for WorkerLocation { // https://url.spec.whatwg.org/#dom-urlutils-hash - fn Hash(self) -> USVString { + fn Hash(&self) -> USVString { UrlHelper::Hash(&self.url) } // https://url.spec.whatwg.org/#dom-urlutils-host - fn Host(self) -> USVString { + fn Host(&self) -> USVString { UrlHelper::Host(&self.url) } // https://url.spec.whatwg.org/#dom-urlutils-hostname - fn Hostname(self) -> USVString { + fn Hostname(&self) -> USVString { UrlHelper::Hostname(&self.url) } // https://url.spec.whatwg.org/#dom-urlutils-href - fn Href(self) -> USVString { + fn Href(&self) -> USVString { UrlHelper::Href(&self.url) } // https://url.spec.whatwg.org/#dom-urlutils-pathname - fn Pathname(self) -> USVString { + fn Pathname(&self) -> USVString { UrlHelper::Pathname(&self.url) } // https://url.spec.whatwg.org/#dom-urlutils-port - fn Port(self) -> USVString { + fn Port(&self) -> USVString { UrlHelper::Port(&self.url) } // https://url.spec.whatwg.org/#dom-urlutils-protocol - fn Protocol(self) -> USVString { + fn Protocol(&self) -> USVString { UrlHelper::Protocol(&self.url) } // https://url.spec.whatwg.org/#dom-urlutils-search - fn Search(self) -> USVString { + fn Search(&self) -> USVString { UrlHelper::Search(&self.url) } // https://url.spec.whatwg.org/#URLUtils-stringification-behavior - fn Stringifier(self) -> DOMString { + fn Stringifier(&self) -> DOMString { self.Href().0 } } - diff --git a/components/script/dom/workernavigator.rs b/components/script/dom/workernavigator.rs index f7330f7db69..6bef4bdb048 100644 --- a/components/script/dom/workernavigator.rs +++ b/components/script/dom/workernavigator.rs @@ -13,7 +13,6 @@ use util::str::DOMString; // https://html.spec.whatwg.org/multipage/#workernavigator #[dom_struct] -#[derive(HeapSizeOf)] pub struct WorkerNavigator { reflector_: Reflector, } @@ -32,40 +31,39 @@ impl WorkerNavigator { } } -impl<'a> WorkerNavigatorMethods for &'a WorkerNavigator { +impl WorkerNavigatorMethods for WorkerNavigator { // https://html.spec.whatwg.org/multipage/#dom-navigator-product - fn Product(self) -> DOMString { + fn Product(&self) -> DOMString { navigatorinfo::Product() } // https://html.spec.whatwg.org/multipage/#dom-navigator-taintenabled - fn TaintEnabled(self) -> bool { + fn TaintEnabled(&self) -> bool { navigatorinfo::TaintEnabled() } // https://html.spec.whatwg.org/multipage/#dom-navigator-appname - fn AppName(self) -> DOMString { + fn AppName(&self) -> DOMString { navigatorinfo::AppName() } // https://html.spec.whatwg.org/multipage/#dom-navigator-appcodename - fn AppCodeName(self) -> DOMString { + fn AppCodeName(&self) -> DOMString { navigatorinfo::AppCodeName() } // https://html.spec.whatwg.org/multipage/#dom-navigator-platform - fn Platform(self) -> DOMString { + fn Platform(&self) -> DOMString { navigatorinfo::Platform() } // https://html.spec.whatwg.org/multipage/#dom-navigator-useragent - fn UserAgent(self) -> DOMString { + fn UserAgent(&self) -> DOMString { navigatorinfo::UserAgent() } // https://html.spec.whatwg.org/multipage/#dom-navigator-appversion - fn AppVersion(self) -> DOMString { + fn AppVersion(&self) -> DOMString { navigatorinfo::AppVersion() } } - diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index 40325fdcf49..5ab625c1d48 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -20,14 +20,14 @@ use dom::bindings::refcounted::Trusted; use dom::bindings::str::ByteString; use dom::bindings::utils::{Reflectable, reflect_dom_object}; use dom::document::Document; -use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers}; -use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; +use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::progressevent::ProgressEvent; -use dom::urlsearchparams::URLSearchParamsHelpers; use dom::xmlhttprequesteventtarget::XMLHttpRequestEventTarget; use dom::xmlhttprequesteventtarget::XMLHttpRequestEventTargetTypeId; use dom::xmlhttprequestupload::XMLHttpRequestUpload; use network_listener::{NetworkListener, PreInvoke}; +use script_task::ScriptTaskEventCategory::XhrEvent; use script_task::{ScriptChan, Runnable, ScriptPort, CommonScriptMsg}; use encoding::all::UTF_8; @@ -116,7 +116,6 @@ impl XHRProgress { } #[dom_struct] -#[derive(HeapSizeOf)] pub struct XMLHttpRequest { eventtarget: XMLHttpRequestEventTarget, ready_state: Cell, @@ -293,16 +292,17 @@ impl XMLHttpRequest { } } -impl<'a> XMLHttpRequestMethods for &'a XMLHttpRequest { +impl XMLHttpRequestMethods for XMLHttpRequest { + // https://xhr.spec.whatwg.org/#handler-xhr-onreadystatechange event_handler!(readystatechange, GetOnreadystatechange, SetOnreadystatechange); // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate - fn ReadyState(self) -> u16 { + fn ReadyState(&self) -> u16 { self.ready_state.get() as u16 } // https://xhr.spec.whatwg.org/#the-open()-method - fn Open(self, method: ByteString, url: DOMString) -> ErrorResult { + fn Open(&self, method: ByteString, url: DOMString) -> ErrorResult { //FIXME(seanmonstar): use a Trie instead? let maybe_method = method.as_str().and_then(|s| { // Note: hyper tests against the uppercase versions @@ -367,14 +367,14 @@ impl<'a> XMLHttpRequestMethods for &'a XMLHttpRequest { } // https://xhr.spec.whatwg.org/#the-open()-method - fn Open_(self, method: ByteString, url: DOMString, async: bool, + fn Open_(&self, method: ByteString, url: DOMString, async: bool, _username: Option, _password: Option) -> ErrorResult { self.sync.set(!async); self.Open(method, url) } // https://xhr.spec.whatwg.org/#the-setrequestheader()-method - fn SetRequestHeader(self, name: ByteString, mut value: ByteString) -> ErrorResult { + fn SetRequestHeader(&self, name: ByteString, mut value: ByteString) -> ErrorResult { if self.ready_state.get() != XMLHttpRequestState::Opened || self.send_flag.get() { return Err(InvalidState); // Step 1, 2 } @@ -424,12 +424,12 @@ impl<'a> XMLHttpRequestMethods for &'a XMLHttpRequest { } // https://xhr.spec.whatwg.org/#the-timeout-attribute - fn Timeout(self) -> u32 { + fn Timeout(&self) -> u32 { self.timeout.get() } // https://xhr.spec.whatwg.org/#the-timeout-attribute - fn SetTimeout(self, timeout: u32) -> ErrorResult { + fn SetTimeout(&self, timeout: u32) -> ErrorResult { if self.sync.get() { // FIXME: Not valid for a worker environment Err(InvalidAccess) @@ -453,12 +453,12 @@ impl<'a> XMLHttpRequestMethods for &'a XMLHttpRequest { } // https://xhr.spec.whatwg.org/#the-withcredentials-attribute - fn WithCredentials(self) -> bool { + fn WithCredentials(&self) -> bool { self.with_credentials.get() } // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-withcredentials - fn SetWithCredentials(self, with_credentials: bool) -> ErrorResult { + fn SetWithCredentials(&self, with_credentials: bool) -> ErrorResult { match self.ready_state.get() { XMLHttpRequestState::HeadersReceived | XMLHttpRequestState::Loading | @@ -475,12 +475,12 @@ impl<'a> XMLHttpRequestMethods for &'a XMLHttpRequest { } // https://xhr.spec.whatwg.org/#the-upload-attribute - fn Upload(self) -> Root { + fn Upload(&self) -> Root { self.upload.root() } // https://xhr.spec.whatwg.org/#the-send()-method - fn Send(self, data: Option) -> ErrorResult { + fn Send(&self, data: Option) -> ErrorResult { if self.ready_state.get() != XMLHttpRequestState::Opened || self.send_flag.get() { return Err(InvalidState); // Step 1, 2 } @@ -612,7 +612,7 @@ impl<'a> XMLHttpRequestMethods for &'a XMLHttpRequest { } // https://xhr.spec.whatwg.org/#the-abort()-method - fn Abort(self) { + fn Abort(&self) { self.terminate_ongoing_fetch(); let state = self.ready_state.get(); if (state == XMLHttpRequestState::Opened && self.send_flag.get()) || @@ -630,22 +630,22 @@ impl<'a> XMLHttpRequestMethods for &'a XMLHttpRequest { } // https://xhr.spec.whatwg.org/#the-responseurl-attribute - fn ResponseURL(self) -> DOMString { + fn ResponseURL(&self) -> DOMString { self.response_url.clone() } // https://xhr.spec.whatwg.org/#the-status-attribute - fn Status(self) -> u16 { + fn Status(&self) -> u16 { self.status.get() } // https://xhr.spec.whatwg.org/#the-statustext-attribute - fn StatusText(self) -> ByteString { + fn StatusText(&self) -> ByteString { self.status_text.borrow().clone() } // https://xhr.spec.whatwg.org/#the-getresponseheader()-method - fn GetResponseHeader(self, name: ByteString) -> Option { + fn GetResponseHeader(&self, name: ByteString) -> Option { self.filter_response_headers().iter().find(|h| { name.eq_ignore_case(&h.name().parse().unwrap()) }).map(|h| { @@ -654,17 +654,17 @@ impl<'a> XMLHttpRequestMethods for &'a XMLHttpRequest { } // https://xhr.spec.whatwg.org/#the-getallresponseheaders()-method - fn GetAllResponseHeaders(self) -> ByteString { + fn GetAllResponseHeaders(&self) -> ByteString { ByteString::new(self.filter_response_headers().to_string().into_bytes()) } // https://xhr.spec.whatwg.org/#the-responsetype-attribute - fn ResponseType(self) -> XMLHttpRequestResponseType { + fn ResponseType(&self) -> XMLHttpRequestResponseType { self.response_type.get() } // https://xhr.spec.whatwg.org/#the-responsetype-attribute - fn SetResponseType(self, response_type: XMLHttpRequestResponseType) -> ErrorResult { + fn SetResponseType(&self, response_type: XMLHttpRequestResponseType) -> ErrorResult { match self.global.root() { GlobalRoot::Worker(_) if response_type == XMLHttpRequestResponseType::Document => return Ok(()), @@ -682,7 +682,7 @@ impl<'a> XMLHttpRequestMethods for &'a XMLHttpRequest { #[allow(unsafe_code)] // https://xhr.spec.whatwg.org/#the-response-attribute - fn Response(self, cx: *mut JSContext) -> JSVal { + fn Response(&self, cx: *mut JSContext) -> JSVal { let mut rval = RootedValue::new(cx, UndefinedValue()); match self.response_type.get() { _empty | Text => { @@ -718,7 +718,7 @@ impl<'a> XMLHttpRequestMethods for &'a XMLHttpRequest { } // https://xhr.spec.whatwg.org/#the-responsetext-attribute - fn GetResponseText(self) -> Fallible { + fn GetResponseText(&self) -> Fallible { match self.response_type.get() { _empty | Text => { match self.ready_state.get() { @@ -731,7 +731,7 @@ impl<'a> XMLHttpRequestMethods for &'a XMLHttpRequest { } // https://xhr.spec.whatwg.org/#the-responsexml-attribute - fn GetResponseXML(self) -> Option> { + fn GetResponseXML(&self) -> Option> { self.response_xml.get().map(Root::from_rooted) } } @@ -748,29 +748,9 @@ impl XMLHttpRequestDerived for EventTarget { pub type TrustedXHRAddress = Trusted; -trait PrivateXMLHttpRequestHelpers { - fn change_ready_state(self, XMLHttpRequestState); - fn process_headers_available(self, cors_request: Option, - gen_id: GenerationId, metadata: Metadata) -> Result<(), Error>; - fn process_data_available(self, gen_id: GenerationId, payload: Vec); - fn process_response_complete(self, gen_id: GenerationId, status: Result<(), String>) -> ErrorResult; - fn process_partial_response(self, progress: XHRProgress); - fn terminate_ongoing_fetch(self); - fn insert_trusted_header(self, name: String, value: String); - fn dispatch_progress_event(self, upload: bool, type_: DOMString, loaded: u64, total: Option); - fn dispatch_upload_progress_event(self, type_: DOMString, partial_load: Option); - fn dispatch_response_progress_event(self, type_: DOMString); - fn text_response(self) -> DOMString; - fn set_timeout(self, timeout: u32); - fn cancel_timeout(self); - fn filter_response_headers(self) -> Headers; - fn discard_subsequent_responses(self); - fn fetch(self, load_data: LoadData, cors_request: Result,()>, - global: GlobalRef) -> ErrorResult; -} -impl<'a> PrivateXMLHttpRequestHelpers for &'a XMLHttpRequest { - fn change_ready_state(self, rs: XMLHttpRequestState) { +impl XMLHttpRequest { + fn change_ready_state(&self, rs: XMLHttpRequestState) { assert!(self.ready_state.get() != rs); self.ready_state.set(rs); let global = self.global.root(); @@ -782,7 +762,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for &'a XMLHttpRequest { event.r().fire(target); } - fn process_headers_available(self, cors_request: Option, + fn process_headers_available(&self, cors_request: Option, gen_id: GenerationId, metadata: Metadata) -> Result<(), Error> { if let Some(ref req) = cors_request { @@ -802,11 +782,11 @@ impl<'a> PrivateXMLHttpRequestHelpers for &'a XMLHttpRequest { Ok(()) } - fn process_data_available(self, gen_id: GenerationId, payload: Vec) { + fn process_data_available(&self, gen_id: GenerationId, payload: Vec) { self.process_partial_response(XHRProgress::Loading(gen_id, ByteString::new(payload))); } - fn process_response_complete(self, gen_id: GenerationId, status: Result<(), String>) + fn process_response_complete(&self, gen_id: GenerationId, status: Result<(), String>) -> ErrorResult { match status { Ok(()) => { @@ -820,7 +800,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for &'a XMLHttpRequest { } } - fn process_partial_response(self, progress: XHRProgress) { + fn process_partial_response(&self, progress: XHRProgress) { let msg_id = progress.generation_id(); // Aborts processing if abort() or open() was called @@ -942,20 +922,20 @@ impl<'a> PrivateXMLHttpRequestHelpers for &'a XMLHttpRequest { } } - fn terminate_ongoing_fetch(self) { + fn terminate_ongoing_fetch(&self) { let GenerationId(prev_id) = self.generation_id.get(); self.generation_id.set(GenerationId(prev_id + 1)); *self.timeout_target.borrow_mut() = None; self.response_status.set(Ok(())); } - fn insert_trusted_header(self, name: String, value: String) { + fn insert_trusted_header(&self, name: String, value: String) { // Insert a header without checking spec-compliance // Use for hardcoded headers self.request_headers.borrow_mut().set_raw(name, vec![value.into_bytes()]); } - fn dispatch_progress_event(self, upload: bool, type_: DOMString, loaded: u64, total: Option) { + fn dispatch_progress_event(&self, upload: bool, type_: DOMString, loaded: u64, total: Option) { let global = self.global.root(); let upload_target = self.upload.root(); let progressevent = ProgressEvent::new(global.r(), @@ -971,19 +951,19 @@ impl<'a> PrivateXMLHttpRequestHelpers for &'a XMLHttpRequest { event.fire(target); } - fn dispatch_upload_progress_event(self, type_: DOMString, partial_load: Option) { + fn dispatch_upload_progress_event(&self, type_: DOMString, partial_load: Option) { // If partial_load is None, loading has completed and we can just use the value from the request body let total = self.request_body_len.get() as u64; self.dispatch_progress_event(true, type_, partial_load.unwrap_or(total), Some(total)); } - fn dispatch_response_progress_event(self, type_: DOMString) { + fn dispatch_response_progress_event(&self, type_: DOMString) { let len = self.response.borrow().len() as u64; - let total = self.response_headers.borrow().get::().map(|x| {**x as u64}); + let total = self.response_headers.borrow().get::().map(|x| { **x as u64 }); self.dispatch_progress_event(false, type_, len, total); } - fn set_timeout(self, duration_ms: u32) { + fn set_timeout(&self, duration_ms: u32) { struct XHRTimeout { xhr: TrustedXHRAddress, gen_id: GenerationId, @@ -1011,7 +991,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for &'a XMLHttpRequest { sleep_ms(duration_ms); match cancel_rx.try_recv() { Err(TryRecvError::Empty) => { - timeout_target.send(CommonScriptMsg::RunnableMsg(box XHRTimeout { + timeout_target.send(CommonScriptMsg::RunnableMsg(XhrEvent, box XHRTimeout { xhr: xhr, gen_id: gen_id, })).unwrap(); @@ -1026,13 +1006,13 @@ impl<'a> PrivateXMLHttpRequestHelpers for &'a XMLHttpRequest { ); } - fn cancel_timeout(self) { + fn cancel_timeout(&self) { if let Some(cancel_tx) = self.timeout_cancel.borrow_mut().take() { let _ = cancel_tx.send(()); } } - fn text_response(self) -> DOMString { + fn text_response(&self) -> DOMString { let mut encoding = UTF_8 as EncodingRef; match self.response_headers.borrow().get() { Some(&ContentType(mime::Mime(_, _, ref params))) => { @@ -1050,7 +1030,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for &'a XMLHttpRequest { // the result should be fine. XXXManishearth have a closer look at this later encoding.decode(&self.response.borrow(), DecoderTrap::Replace).unwrap().to_owned() } - fn filter_response_headers(self) -> Headers { + fn filter_response_headers(&self) -> Headers { // https://fetch.spec.whatwg.org/#concept-response-header-list use hyper::error::Result; use hyper::header::SetCookie; @@ -1082,11 +1062,11 @@ impl<'a> PrivateXMLHttpRequestHelpers for &'a XMLHttpRequest { headers } - fn discard_subsequent_responses(self) { + fn discard_subsequent_responses(&self) { self.response_status.set(Err(())); } - fn fetch(self, + fn fetch(&self, load_data: LoadData, cors_request: Result,()>, global: GlobalRef) -> ErrorResult { diff --git a/components/script/dom/xmlhttprequesteventtarget.rs b/components/script/dom/xmlhttprequesteventtarget.rs index 031d0cd3641..627e4882dde 100644 --- a/components/script/dom/xmlhttprequesteventtarget.rs +++ b/components/script/dom/xmlhttprequesteventtarget.rs @@ -6,7 +6,7 @@ use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::XMLHttpRequestEventTargetBinding::XMLHttpRequestEventTargetMethods; use dom::bindings::codegen::InheritTypes::EventTargetCast; use dom::bindings::codegen::InheritTypes::XMLHttpRequestEventTargetDerived; -use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; #[derive(JSTraceable, Copy, Clone, PartialEq, HeapSizeOf)] pub enum XMLHttpRequestEventTargetTypeId { @@ -15,7 +15,6 @@ pub enum XMLHttpRequestEventTargetTypeId { } #[dom_struct] -#[derive(HeapSizeOf)] pub struct XMLHttpRequestEventTarget { eventtarget: EventTarget, } @@ -38,12 +37,25 @@ impl XMLHttpRequestEventTargetDerived for EventTarget { } -impl<'a> XMLHttpRequestEventTargetMethods for &'a XMLHttpRequestEventTarget { +impl XMLHttpRequestEventTargetMethods for XMLHttpRequestEventTarget { + // https://xhr.spec.whatwg.org/#handler-xhr-onloadstart event_handler!(loadstart, GetOnloadstart, SetOnloadstart); + + // https://xhr.spec.whatwg.org/#handler-xhr-onprogress event_handler!(progress, GetOnprogress, SetOnprogress); + + // https://xhr.spec.whatwg.org/#handler-xhr-onabort event_handler!(abort, GetOnabort, SetOnabort); + + // https://xhr.spec.whatwg.org/#handler-xhr-onerror event_handler!(error, GetOnerror, SetOnerror); + + // https://xhr.spec.whatwg.org/#handler-xhr-onload event_handler!(load, GetOnload, SetOnload); + + // https://xhr.spec.whatwg.org/#handler-xhr-ontimeout event_handler!(timeout, GetOntimeout, SetOntimeout); + + // https://xhr.spec.whatwg.org/#handler-xhr-onloadend event_handler!(loadend, GetOnloadend, SetOnloadend); } diff --git a/components/script/dom/xmlhttprequestupload.rs b/components/script/dom/xmlhttprequestupload.rs index 5753117863b..d112d9d1e08 100644 --- a/components/script/dom/xmlhttprequestupload.rs +++ b/components/script/dom/xmlhttprequestupload.rs @@ -12,7 +12,6 @@ use dom::xmlhttprequesteventtarget::XMLHttpRequestEventTarget; use dom::xmlhttprequesteventtarget::XMLHttpRequestEventTargetTypeId; #[dom_struct] -#[derive(HeapSizeOf)] pub struct XMLHttpRequestUpload { eventtarget: XMLHttpRequestEventTarget } diff --git a/components/script/lib.rs b/components/script/lib.rs index 3c68c18d27a..ab2f0b94669 100644 --- a/components/script/lib.rs +++ b/components/script/lib.rs @@ -18,12 +18,14 @@ #![feature(drain)] #![feature(fnbox)] #![feature(hashmap_hasher)] +#![feature(iter_arith)] #![feature(mpsc_select)] #![feature(nonzero)] #![feature(plugin)] #![feature(ref_slice)] #![feature(rc_unique)] #![feature(slice_patterns)] +#![feature(str_split_at)] #![feature(str_utf16)] #![feature(unicode)] #![feature(vec_push_all)] @@ -31,7 +33,7 @@ #![deny(unsafe_code)] #![allow(non_snake_case)] -#![doc="The script crate contains all matters DOM."] +#![doc = "The script crate contains all matters DOM."] #![plugin(string_cache_plugin)] #![plugin(plugins)] @@ -76,6 +78,7 @@ extern crate url; extern crate uuid; extern crate string_cache; extern crate offscreen_gl_context; +extern crate angle; extern crate tendril; pub mod cors; @@ -100,7 +103,7 @@ mod webdriver_handlers; use dom::bindings::codegen::RegisterBindings; -#[cfg(target_os="linux")] +#[cfg(target_os = "linux")] #[allow(unsafe_code)] fn perform_platform_specific_initialization() { use std::mem; @@ -116,7 +119,7 @@ fn perform_platform_specific_initialization() { } } -#[cfg(not(target_os="linux"))] +#[cfg(not(target_os = "linux"))] fn perform_platform_specific_initialization() {} #[allow(unsafe_code)] diff --git a/components/script/network_listener.rs b/components/script/network_listener.rs index a65fec9a689..ec5abe2d5a5 100644 --- a/components/script/network_listener.rs +++ b/components/script/network_listener.rs @@ -3,6 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use net_traits::{AsyncResponseListener, ResponseAction}; +use script_task::ScriptTaskEventCategory::NetworkEvent; use script_task::{ScriptChan, Runnable, CommonScriptMsg}; use std::sync::{Arc, Mutex}; @@ -15,7 +16,7 @@ pub struct NetworkListener NetworkListener { pub fn notify(&self, action: ResponseAction) { - if let Err(err) = self.script_chan.send(CommonScriptMsg::RunnableMsg(box ListenerRunnable { + if let Err(err) = self.script_chan.send(CommonScriptMsg::RunnableMsg(NetworkEvent, box ListenerRunnable { context: self.context.clone(), action: action, })) { diff --git a/components/script/page.rs b/components/script/page.rs index cea63c08a38..25dd39cad6e 100644 --- a/components/script/page.rs +++ b/components/script/page.rs @@ -4,8 +4,7 @@ use dom::bindings::cell::DOMRefCell; use dom::bindings::js::{JS, Root}; -use dom::document::{Document, DocumentHelpers}; -use dom::node::NodeHelpers; +use dom::document::Document; use dom::window::Window; use msg::constellation_msg::PipelineId; diff --git a/components/script/parse/html.rs b/components/script/parse/html.rs index 872fd334ab4..a2dd0109ed1 100644 --- a/components/script/parse/html.rs +++ b/components/script/parse/html.rs @@ -5,7 +5,6 @@ #![allow(unsafe_code, unrooted_must_root)] use document_loader::DocumentLoader; -use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::codegen::InheritTypes::ProcessingInstructionCast; @@ -14,20 +13,17 @@ use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLScriptElementCast}; use dom::bindings::codegen::InheritTypes::{HTMLFormElementDerived, NodeCast}; use dom::bindings::js::{JS, Root}; use dom::bindings::js::{RootedReference}; -use dom::characterdata::{CharacterDataHelpers, CharacterDataTypeId}; +use dom::characterdata::CharacterDataTypeId; use dom::comment::Comment; -use dom::document::{Document, DocumentHelpers}; +use dom::document::Document; use dom::document::{DocumentSource, IsHTMLDocument}; use dom::documenttype::DocumentType; -use dom::element::{Element, AttributeHandlers, ElementHelpers, ElementCreator}; +use dom::element::{Element, ElementCreator}; use dom::htmlscriptelement::HTMLScriptElement; -use dom::htmlscriptelement::HTMLScriptElementHelpers; -use dom::node::{Node, NodeHelpers, NodeTypeId}; +use dom::node::{Node, NodeTypeId}; use dom::node::{document_from_node, window_from_node}; -use dom::processinginstruction::ProcessingInstructionHelpers; use dom::servohtmlparser; use dom::servohtmlparser::{ServoHTMLParser, FragmentContext}; -use dom::text::Text; use parse::Parser; use encoding::types::Encoding; @@ -36,7 +32,7 @@ use html5ever::Attribute; use html5ever::serialize::TraversalScope; use html5ever::serialize::TraversalScope::{IncludeNode, ChildrenOnly}; use html5ever::serialize::{Serializable, Serializer, AttrRef}; -use html5ever::tree_builder::{TreeSink, QuirksMode, NodeOrText, AppendNode, AppendText, NextParserState}; +use html5ever::tree_builder::{NextParserState, NodeOrText, QuirksMode, TreeSink}; use msg::constellation_msg::PipelineId; use std::borrow::Cow; use std::io::{self, Write}; @@ -45,23 +41,6 @@ use tendril::StrTendril; use url::Url; use util::str::DOMString; -trait SinkHelpers { - fn get_or_create(&self, child: NodeOrText>) -> Root; -} - -impl SinkHelpers for servohtmlparser::Sink { - fn get_or_create(&self, child: NodeOrText>) -> Root { - match child { - AppendNode(n) => n.root(), - AppendText(t) => { - let doc = self.document.root(); - let text = Text::new(t.into(), doc.r()); - NodeCast::from_root(text) - } - } - } -} - impl<'a> TreeSink for servohtmlparser::Sink { type Handle = JS; fn get_document(&mut self) -> JS { diff --git a/components/script/script_task.rs b/components/script/script_task.rs index 17e0a58314f..1ab86d67570 100644 --- a/components/script/script_task.rs +++ b/components/script/script_task.rs @@ -33,15 +33,14 @@ use dom::bindings::js::{RootCollectionPtr, Root, RootedReference}; use dom::bindings::refcounted::{LiveDOMReferences, Trusted, TrustedReference, trace_refcounted_objects}; use dom::bindings::trace::{JSTraceable, trace_traceables, RootedVec}; use dom::bindings::utils::{WRAP_CALLBACKS, DOM_CALLBACKS}; -use dom::document::{Document, IsHTMLDocument, DocumentHelpers, DocumentProgressHandler}; +use dom::document::{Document, IsHTMLDocument, DocumentProgressHandler}; use dom::document::{DocumentProgressTask, DocumentSource, MouseEventType}; -use dom::element::{Element, AttributeHandlers}; -use dom::event::{EventHelpers, EventBubbles, EventCancelable}; -use dom::htmliframeelement::HTMLIFrameElementHelpers; -use dom::node::{Node, NodeHelpers, NodeDamage, window_from_node}; +use dom::element::Element; +use dom::event::{EventBubbles, EventCancelable}; +use dom::node::{Node, NodeDamage, window_from_node}; use dom::servohtmlparser::{ServoHTMLParser, ParserContext}; use dom::uievent::UIEvent; -use dom::window::{Window, WindowHelpers, ScriptHelpers, ReflowReason}; +use dom::window::{Window, ScriptHelpers, ReflowReason}; use dom::worker::TrustedWorkerAddress; use layout_interface::{ReflowQueryType}; use layout_interface::{self, NewLayoutTaskInfo, ScriptLayoutChan, LayoutChan, ReflowGoal}; @@ -53,8 +52,8 @@ use timers::TimerId; use webdriver_handlers; use devtools_traits::{DevtoolsPageInfo, DevtoolScriptControlMsg}; -use devtools_traits::{ScriptToDevtoolsControlMsg, TimelineMarker, TimelineMarkerType}; -use devtools_traits::{TracingMetadata}; +use devtools_traits::{ScriptToDevtoolsControlMsg, TimelineMarker}; +use devtools_traits::{StartedTimelineMarker, TimelineMarkerType}; use msg::compositor_msg::{LayerId, ScriptToCompositorMsg}; use msg::constellation_msg::Msg as ConstellationMsg; use msg::constellation_msg::{ConstellationChan, FocusType}; @@ -95,11 +94,12 @@ use js::jsval::UndefinedValue; use js::rust::Runtime; use url::{Url, UrlParser}; +use core::ops::Deref; use libc; use std::any::Any; use std::borrow::ToOwned; use std::cell::{Cell, RefCell}; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::io::{stdout, Write}; use std::mem as std_mem; use std::option::Option; @@ -179,6 +179,13 @@ pub trait MainThreadRunnable { fn handler(self: Box, script_task: &ScriptTask); } +enum MixedMessage { + FromConstellation(ConstellationControlMsg), + FromScript(MainThreadScriptMsg), + FromDevtools(DevtoolScriptControlMsg), + FromImageCache(ImageCacheResult), +} + /// Common messages used to control the event loops in both the script and the worker pub enum CommonScriptMsg { /// Requests that the script task measure its memory usage. The results are sent back via the @@ -191,7 +198,27 @@ pub enum CommonScriptMsg { /// A DOM object's last pinned reference was removed (dispatched to all tasks). RefcountCleanup(TrustedReference), /// Generic message that encapsulates event handling. - RunnableMsg(Box), + RunnableMsg(ScriptTaskEventCategory, Box), +} + +#[derive(Clone, Copy, Debug, Eq, Hash, JSTraceable, PartialEq)] +pub enum ScriptTaskEventCategory { + AttachLayout, + ConstellationMsg, + DevtoolsMsg, + DocumentEvent, + DomEvent, + FileRead, + ImageCacheMsg, + InputEvent, + NetworkEvent, + Resize, + ScriptEvent, + UpdateReplacedElement, + SetViewport, + WebSocketEvent, + WorkerEvent, + XhrEvent, } /// Messages used to control the script event loop @@ -391,6 +418,11 @@ pub struct ScriptTask { /// List of pipelines that have been owned and closed by this script task. closed_pipelines: RefCell>, + + /// When profiling data should be written out to stdout. + perf_profiler_next_report: Cell>, + /// How much time was spent on what since the last report. + perf_profiler_times: RefCell>, } /// In the event of task failure, all data on the stack runs its destructor. However, there @@ -636,6 +668,9 @@ impl ScriptTask { js_runtime: Rc::new(runtime), mouse_over_targets: DOMRefCell::new(vec!()), closed_pipelines: RefCell::new(HashSet::new()), + + perf_profiler_next_report: Cell::new(None), + perf_profiler_times: RefCell::new(HashMap::new()), } } @@ -714,13 +749,6 @@ impl ScriptTask { self.handle_event(id, ResizeEvent(size)); } - enum MixedMessage { - FromConstellation(ConstellationControlMsg), - FromScript(MainThreadScriptMsg), - FromDevtools(DevtoolScriptControlMsg), - FromImageCache(ImageCacheResult), - } - // Store new resizes, and gather all other events. let mut sequential = vec!(); @@ -763,13 +791,19 @@ impl ScriptTask { // child list yet, causing the find() to fail. MixedMessage::FromConstellation(ConstellationControlMsg::AttachLayout( new_layout_info)) => { - self.handle_new_layout(new_layout_info); + self.profile_event(ScriptTaskEventCategory::AttachLayout, || { + self.handle_new_layout(new_layout_info); + }) } MixedMessage::FromConstellation(ConstellationControlMsg::Resize(id, size)) => { - self.handle_resize(id, size); + self.profile_event(ScriptTaskEventCategory::Resize, || { + self.handle_resize(id, size); + }) } MixedMessage::FromConstellation(ConstellationControlMsg::Viewport(id, rect)) => { - self.handle_viewport(id, rect); + self.profile_event(ScriptTaskEventCategory::SetViewport, || { + self.handle_viewport(id, rect); + }) } MixedMessage::FromConstellation(ConstellationControlMsg::TickAllAnimations( pipeline_id)) => { @@ -816,16 +850,26 @@ impl ScriptTask { // Process the gathered events. for msg in sequential { - match msg { - MixedMessage::FromConstellation(ConstellationControlMsg::ExitPipeline(id, exit_type)) => { - if self.handle_exit_pipeline_msg(id, exit_type) { - return false - } - }, - MixedMessage::FromConstellation(inner_msg) => self.handle_msg_from_constellation(inner_msg), - MixedMessage::FromScript(inner_msg) => self.handle_msg_from_script(inner_msg), - MixedMessage::FromDevtools(inner_msg) => self.handle_msg_from_devtools(inner_msg), - MixedMessage::FromImageCache(inner_msg) => self.handle_msg_from_image_cache(inner_msg), + let category = self.categorize_msg(&msg); + + let result = self.profile_event(category, move || { + match msg { + MixedMessage::FromConstellation(ConstellationControlMsg::ExitPipeline(id, exit_type)) => { + if self.handle_exit_pipeline_msg(id, exit_type) { + return Some(false) + } + }, + MixedMessage::FromConstellation(inner_msg) => self.handle_msg_from_constellation(inner_msg), + MixedMessage::FromScript(inner_msg) => self.handle_msg_from_script(inner_msg), + MixedMessage::FromDevtools(inner_msg) => self.handle_msg_from_devtools(inner_msg), + MixedMessage::FromImageCache(inner_msg) => self.handle_msg_from_image_cache(inner_msg), + } + + None + }); + + if let Some(retval) = result { + return retval } } @@ -848,6 +892,76 @@ impl ScriptTask { true } + fn categorize_msg(&self, msg: &MixedMessage) -> ScriptTaskEventCategory { + match *msg { + MixedMessage::FromConstellation(ref inner_msg) => { + match *inner_msg { + ConstellationControlMsg::SendEvent(_, _) => + ScriptTaskEventCategory::DomEvent, + _ => ScriptTaskEventCategory::ConstellationMsg + } + }, + MixedMessage::FromDevtools(_) => ScriptTaskEventCategory::DevtoolsMsg, + MixedMessage::FromImageCache(_) => ScriptTaskEventCategory::ImageCacheMsg, + MixedMessage::FromScript(ref inner_msg) => { + match *inner_msg { + MainThreadScriptMsg::Common(CommonScriptMsg::RunnableMsg(ref category, _)) => + *category, + _ => ScriptTaskEventCategory::ScriptEvent + } + } + } + } + + fn profile_event(&self, category: ScriptTaskEventCategory, f: F) -> R + where F: FnOnce() -> R { + + if opts::get().profile_script_events { + let start = time::precise_time_ns(); + let result = f(); + let end = time::precise_time_ns(); + + let duration = end - start; + + let aggregate = { + let zero = 0; + let perf_profiler_times = self.perf_profiler_times.borrow(); + let so_far = perf_profiler_times.get(&category).unwrap_or(&zero); + + so_far + duration + }; + + self.perf_profiler_times.borrow_mut().insert(category, aggregate); + + const NANO: u64 = 1000 * 1000 * 1000; + const REPORT_INTERVAL: u64 = 10 * NANO; + + match self.perf_profiler_next_report.get() { + None => self.perf_profiler_next_report.set(Some(start + REPORT_INTERVAL)), + Some(time) if time <= end => { + self.perf_profiler_next_report.set(Some(end + REPORT_INTERVAL)); + + let stdout = stdout(); + let mut stdout = stdout.lock(); + writeln!(&mut stdout, "Script task time distribution:").unwrap(); + for (c, t) in self.perf_profiler_times.borrow().deref() { + let secs = t / NANO; + let nanos = t % NANO; + writeln!(&mut stdout, " {:?}: {}.{}s", c, secs, nanos).unwrap(); + } + stdout.flush().unwrap(); + + self.perf_profiler_times.borrow_mut().clear(); + }, + Some(_) => {} + } + + result + } else { + f() + } + } + fn handle_msg_from_constellation(&self, msg: ConstellationControlMsg) { match msg { ConstellationControlMsg::AttachLayout(_) => @@ -915,7 +1029,9 @@ impl ScriptTask { MainThreadScriptMsg::Common( CommonScriptMsg::FireTimer(TimerSource::FromWorker, _)) => panic!("Worker timeouts must not be sent to script task"), - MainThreadScriptMsg::Common(CommonScriptMsg::RunnableMsg(runnable)) => + MainThreadScriptMsg::Common(CommonScriptMsg::RunnableMsg(_, runnable)) => + // The category of the runnable is ignored by the pattern, however + // it is still respected by profiling (see categorize_msg). runnable.handler(), MainThreadScriptMsg::Common(CommonScriptMsg::RefcountCleanup(addr)) => LiveDOMReferences::cleanup(addr), @@ -1129,7 +1245,7 @@ impl ScriptTask { // https://html.spec.whatwg.org/multipage/#the-end step 7 let addr: Trusted = Trusted::new(self.get_cx(), doc, self.chan.clone()); let handler = box DocumentProgressHandler::new(addr.clone(), DocumentProgressTask::Load); - self.chan.send(CommonScriptMsg::RunnableMsg(handler)).unwrap(); + self.chan.send(CommonScriptMsg::RunnableMsg(ScriptTaskEventCategory::DocumentEvent, handler)).unwrap(); let ConstellationChan(ref chan) = self.constellation_chan; chan.send(ConstellationMsg::LoadComplete(pipeline)).unwrap(); @@ -1882,7 +1998,7 @@ impl ScriptTask { // https://html.spec.whatwg.org/multipage/#the-end step 4 let addr: Trusted = Trusted::new(self.get_cx(), document.r(), self.chan.clone()); let handler = box DocumentProgressHandler::new(addr, DocumentProgressTask::DOMContentLoaded); - self.chan.send(CommonScriptMsg::RunnableMsg(handler)).unwrap(); + self.chan.send(CommonScriptMsg::RunnableMsg(ScriptTaskEventCategory::DocumentEvent, handler)).unwrap(); window.r().set_fragment_name(final_url.fragment.clone()); @@ -1900,23 +2016,22 @@ impl Drop for ScriptTask { } struct AutoDOMEventMarker<'a> { - script_task: &'a ScriptTask + script_task: &'a ScriptTask, + marker: Option, } impl<'a> AutoDOMEventMarker<'a> { fn new(script_task: &'a ScriptTask) -> AutoDOMEventMarker<'a> { - let marker = TimelineMarker::new("DOMEvent".to_owned(), TracingMetadata::IntervalStart); - script_task.emit_timeline_marker(marker); AutoDOMEventMarker { - script_task: script_task + script_task: script_task, + marker: Some(TimelineMarker::start("DOMEvent".to_owned())), } } } impl<'a> Drop for AutoDOMEventMarker<'a> { fn drop(&mut self) { - let marker = TimelineMarker::new("DOMEvent".to_owned(), TracingMetadata::IntervalEnd); - self.script_task.emit_timeline_marker(marker); + self.script_task.emit_timeline_marker(self.marker.take().unwrap().end()); } } diff --git a/components/script/textinput.rs b/components/script/textinput.rs index b2c2afdec0f..c647f63d4d8 100644 --- a/components/script/textinput.rs +++ b/components/script/textinput.rs @@ -5,11 +5,11 @@ //! Common handling of keyboard input and state management for text input controls use clipboard_provider::ClipboardProvider; -use dom::keyboardevent::{KeyboardEvent, KeyboardEventHelpers, key_value}; +use dom::keyboardevent::{KeyboardEvent, key_value}; use msg::constellation_msg::{Key, KeyModifiers}; use msg::constellation_msg::{SHIFT, CONTROL, ALT, SUPER}; use util::mem::HeapSizeOf; -use util::str::{DOMString, slice_chars}; +use util::str::DOMString; use std::borrow::ToOwned; use std::cmp::{min, max}; @@ -26,7 +26,7 @@ pub enum Selection { pub struct TextPoint { /// 0-based line number pub line: usize, - /// 0-based column number + /// 0-based column number in UTF-8 bytes pub index: usize, } @@ -62,15 +62,15 @@ impl Default for TextPoint { } /// Control whether this control should allow multiple lines. -#[derive(PartialEq)] +#[derive(PartialEq, Eq)] pub enum Lines { Single, Multiple, } /// The direction in which to delete a character. -#[derive(PartialEq)] -pub enum DeleteDir { +#[derive(PartialEq, Eq, Copy, Clone)] +pub enum Direction { Forward, Backward } @@ -78,12 +78,12 @@ pub enum DeleteDir { /// Was the keyboard event accompanied by the standard control modifier, /// i.e. cmd on Mac OS or ctrl on other platforms. -#[cfg(target_os="macos")] +#[cfg(target_os = "macos")] fn is_control_key(mods: KeyModifiers) -> bool { mods.contains(SUPER) && !mods.contains(CONTROL | ALT) } -#[cfg(not(target_os="macos"))] +#[cfg(not(target_os = "macos"))] fn is_control_key(mods: KeyModifiers) -> bool { mods.contains(CONTROL) && !mods.contains(SUPER | ALT) } @@ -121,13 +121,9 @@ impl TextInput { } /// Remove a character at the current editing point - pub fn delete_char(&mut self, dir: DeleteDir) { + pub fn delete_char(&mut self, dir: Direction) { if self.selection_begin.is_none() { - self.adjust_horizontal(if dir == DeleteDir::Forward { - 1 - } else { - -1 - }, Selection::Selected); + self.adjust_horizontal_by_one(dir, Selection::Selected); } self.replace_selection("".to_owned()); } @@ -161,16 +157,16 @@ impl TextInput { self.get_sorted_selection().map(|(begin, end)| { if begin.line != end.line { let mut s = String::new(); - s.push_str(slice_chars(&self.lines[begin.line], begin.index, self.lines[begin.line].len())); + s.push_str(&self.lines[begin.line][begin.index..]); for (_, line) in self.lines.iter().enumerate().filter(|&(i,_)| begin.line < i && i < end.line) { s.push_str("\n"); s.push_str(line); } s.push_str("\n"); - s.push_str(slice_chars(&self.lines[end.line], 0, end.index)); + s.push_str(&self.lines[end.line][..end.index]); s } else { - slice_chars(&self.lines[begin.line], begin.index, end.index).to_owned() + self.lines[begin.line][begin.index..end.index].to_owned() } }) } @@ -180,8 +176,8 @@ impl TextInput { self.clear_selection(); let new_lines = { - let prefix = slice_chars(&self.lines[begin.line], 0, begin.index); - let suffix = slice_chars(&self.lines[end.line], end.index, self.lines[end.line].chars().count()); + let prefix = &self.lines[begin.line][..begin.index]; + let suffix = &self.lines[end.line][end.index..]; let lines_prefix = &self.lines[..begin.line]; let lines_suffix = &self.lines[end.line + 1..]; @@ -196,7 +192,7 @@ impl TextInput { insert_lines[0] = new_line; let last_insert_lines_index = insert_lines.len() - 1; - self.edit_point.index = insert_lines[last_insert_lines_index].chars().count(); + self.edit_point.index = insert_lines[last_insert_lines_index].len(); self.edit_point.line = begin.line + last_insert_lines_index; insert_lines[last_insert_lines_index].push_str(suffix); @@ -212,9 +208,9 @@ impl TextInput { } } - /// Return the length of the current line under the editing point. + /// Return the length in UTF-8 bytes of the current line under the editing point. pub fn current_line_length(&self) -> usize { - self.lines[self.edit_point.line].chars().count() + self.lines[self.edit_point.line].len() } /// Adjust the editing point position by a given of lines. The resulting column is @@ -254,18 +250,60 @@ impl TextInput { /// requested is larger than is available in the current line, the editing point is /// adjusted vertically and the process repeats with the remaining adjustment requested. pub fn adjust_horizontal(&mut self, adjust: isize, select: Selection) { + let direction = if adjust >= 0 { Direction::Forward } else { Direction::Backward }; + if self.adjust_selection_for_horizontal_change(direction, select) { + return + } + self.perform_horizontal_adjustment(adjust, select); + } + + pub fn adjust_horizontal_by_one(&mut self, direction: Direction, select: Selection) { + if self.adjust_selection_for_horizontal_change(direction, select) { + return + } + let adjust = { + let current_line = &self.lines[self.edit_point.line]; + // FIXME: We adjust by one code point, but it proably should be one grapheme cluster + // https://github.com/unicode-rs/unicode-segmentation + match direction { + Direction::Forward => { + match current_line[self.edit_point.index..].chars().next() { + Some(c) => c.len_utf8() as isize, + None => 1, // Going to the next line is a "one byte" offset + } + } + Direction::Backward => { + match current_line[..self.edit_point.index].chars().next_back() { + Some(c) => -(c.len_utf8() as isize), + None => -1, // Going to the previous line is a "one byte" offset + } + } + } + }; + self.perform_horizontal_adjustment(adjust, select); + } + + // Return whether to cancel the caret move + fn adjust_selection_for_horizontal_change(&mut self, adjust: Direction, select: Selection) + -> bool { if select == Selection::Selected { if self.selection_begin.is_none() { self.selection_begin = Some(self.edit_point); } } else { if let Some((begin, end)) = self.get_sorted_selection() { - self.edit_point = if adjust < 0 {begin} else {end}; + self.edit_point = match adjust { + Direction::Backward => begin, + Direction::Forward => end, + }; self.clear_selection(); - return + return true } } + false + } + fn perform_horizontal_adjustment(&mut self, adjust: isize, select: Selection) { if adjust < 0 { let remaining = self.edit_point.index; if adjust.abs() as usize > remaining && self.edit_point.line > 0 { @@ -307,7 +345,7 @@ impl TextInput { }); let last_line = self.lines.len() - 1; self.edit_point.line = last_line; - self.edit_point.index = self.lines[last_line].chars().count(); + self.edit_point.index = self.lines[last_line].len(); } /// Remove the current selection. @@ -350,19 +388,19 @@ impl TextInput { KeyReaction::DispatchInput } Key::Delete => { - self.delete_char(DeleteDir::Forward); + self.delete_char(Direction::Forward); KeyReaction::DispatchInput } Key::Backspace => { - self.delete_char(DeleteDir::Backward); + self.delete_char(Direction::Backward); KeyReaction::DispatchInput } Key::Left => { - self.adjust_horizontal(-1, maybe_select); + self.adjust_horizontal_by_one(Direction::Backward, maybe_select); KeyReaction::Nothing } Key::Right => { - self.adjust_horizontal(1, maybe_select); + self.adjust_horizontal_by_one(Direction::Forward, maybe_select); KeyReaction::Nothing } Key::Up => { diff --git a/components/script/timers.rs b/components/script/timers.rs index f18b2231417..8fd712e7ac6 100644 --- a/components/script/timers.rs +++ b/components/script/timers.rs @@ -183,7 +183,7 @@ impl TimerManager { if is_interval == IsInterval::NonInterval { break; } - } else if id == control_handle.id() {; + } else if id == control_handle.id() { match control_port.recv().unwrap() { TimerControlMsg::Suspend => { let msg = control_port.recv().unwrap(); @@ -194,7 +194,7 @@ impl TimerManager { break; }, } - }, + }, TimerControlMsg::Resume => panic!("Nothing to resume!"), TimerControlMsg::Cancel => { break; diff --git a/components/script/webdriver_handlers.rs b/components/script/webdriver_handlers.rs index e25e1fb247c..5c97eca42cb 100644 --- a/components/script/webdriver_handlers.rs +++ b/components/script/webdriver_handlers.rs @@ -11,9 +11,8 @@ use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast, HTMLIFrameElem use dom::bindings::conversions::FromJSValConvertible; use dom::bindings::conversions::StringificationBehavior; use dom::bindings::js::Root; -use dom::document::DocumentHelpers; -use dom::node::{Node, NodeHelpers}; -use dom::window::{ScriptHelpers, WindowHelpers}; +use dom::node::Node; +use dom::window::ScriptHelpers; use js::jsapi::JSContext; use js::jsapi::{RootedValue, HandleValue}; use js::jsval::UndefinedValue; diff --git a/components/servo/Cargo.lock b/components/servo/Cargo.lock index 3e880ad7a2e..5acf07fafc6 100644 --- a/components/servo/Cargo.lock +++ b/components/servo/Cargo.lock @@ -4,13 +4,18 @@ version = "0.0.1" dependencies = [ "android_glue 0.0.2", "bitflags 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "canvas 0.0.1", + "canvas_traits 0.0.1", "compositing 0.0.1", "devtools 0.0.1", "devtools_traits 0.0.1", "env_logger 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "euclid 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", "gfx 0.0.1", "gfx_tests 0.0.1", + "gleam 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", "glutin_app 0.0.1", + "layers 0.1.0 (git+https://github.com/servo/rust-layers)", "layout 0.0.1", "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "msg 0.0.1", @@ -22,6 +27,8 @@ dependencies = [ "profile_traits 0.0.1", "script 0.0.1", "script_tests 0.0.1", + "script_traits 0.0.1", + "style 0.0.1", "style_tests 0.0.1", "time 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", "url 0.2.37 (registry+https://github.com/rust-lang/crates.io-index)", @@ -56,6 +63,14 @@ name = "android_glue" version = "0.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "angle" +version = "0.1.0" +source = "git+https://github.com/ecoal95/angle?branch=servo#77288884bd7a89bf3019ca94dcda6c94cb178aa4" +dependencies = [ + "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "aster" version = "0.4.1" @@ -161,7 +176,7 @@ dependencies = [ [[package]] name = "clipboard" version = "0.0.3" -source = "git+https://github.com/aweinstock314/rust-clipboard#b0092c8630d4362e4618533822bea90a034b0792" +source = "git+https://github.com/aweinstock314/rust-clipboard#8c4c31e73a5ac5afd97825acc4c534dccfc0ab9b" dependencies = [ "clipboard-win 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", @@ -620,7 +635,7 @@ dependencies = [ [[package]] name = "glutin" version = "0.3.5" -source = "git+https://github.com/servo/glutin?branch=servo#22a561c30a0560f445f50abcebf8439d264e0c67" +source = "git+https://github.com/servo/glutin?branch=servo#0b055f889ce0baaa0fc186da4f3b5c31b7c6fd18" dependencies = [ "android_glue 0.0.2 (registry+https://github.com/rust-lang/crates.io-index)", "cgl 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1053,6 +1068,7 @@ name = "net_tests" version = "0.0.1" dependencies = [ "cookie 0.1.21 (registry+https://github.com/rust-lang/crates.io-index)", + "flate2 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)", "hyper 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)", "ipc-channel 0.1.0 (git+https://github.com/pcwalton/ipc-channel)", "net 0.0.1", @@ -1349,6 +1365,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" name = "script" version = "0.0.1" dependencies = [ + "angle 0.1.0 (git+https://github.com/ecoal95/angle?branch=servo)", "bitflags 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", "canvas 0.0.1", "canvas_traits 0.0.1", diff --git a/components/servo/Cargo.toml b/components/servo/Cargo.toml index 00a30da7962..8d454044d4e 100644 --- a/components/servo/Cargo.toml +++ b/components/servo/Cargo.toml @@ -41,9 +41,10 @@ git = "https://github.com/servo/rust-png" features = [ "serde-serialization" ] [features] -default = ["glutin_app", "window"] +default = ["glutin_app", "window", "webdriver"] window = ["glutin_app/window"] headless = ["glutin_app/headless"] +webdriver = ["webdriver_server"] # Uncomment to profile on Linux: # @@ -77,17 +78,30 @@ path = "../util" [dependencies.script] path = "../script" +[dependencies.script_traits] +path = "../script_traits" + [dependencies.layout] path = "../layout" [dependencies.gfx] path = "../gfx" +[dependencies.style] +path = "../style" + +[dependencies.canvas] +path = "../canvas" + +[dependencies.canvas_traits] +path = "../canvas_traits" + [dependencies.devtools] path = "../devtools" [dependencies.webdriver_server] -path = "../webdriver_server" +path = "../webdriver_server" +optional = true [dependencies.devtools_traits] path = "../devtools_traits" @@ -104,6 +118,15 @@ optional = true version = "0.2" features = [ "serde_serialization" ] +[dependencies.euclid] +version = "0.1" + +[dependencies.layers] +git = "https://github.com/servo/rust-layers" + +[dependencies.gleam] +version = "0.1" + [dependencies] env_logger = "0.3" time = "0.1.12" diff --git a/components/servo/lib.rs b/components/servo/lib.rs index dbf127803d3..8dd05d6f6f4 100644 --- a/components/servo/lib.rs +++ b/components/servo/lib.rs @@ -17,22 +17,67 @@ // The `Browser` is fed events from a generic type that implements the // `WindowMethods` trait. -extern crate compositing; -extern crate devtools; -extern crate devtools_traits; -extern crate net; -extern crate net_traits; -extern crate msg; -extern crate profile; -extern crate profile_traits; #[macro_use] -extern crate util; -extern crate script; -extern crate layout; -extern crate gfx; +extern crate util as _util; + +mod export { + extern crate compositing; + extern crate devtools; + extern crate devtools_traits; + extern crate net; + extern crate net_traits; + extern crate msg; + extern crate profile; + extern crate profile_traits; + extern crate script; + extern crate script_traits; + extern crate layout; + extern crate gfx; + extern crate style; + extern crate canvas; + extern crate canvas_traits; + + extern crate euclid; + extern crate url; + extern crate layers; + extern crate gleam; +} + extern crate libc; + +#[cfg(feature = "webdriver")] extern crate webdriver_server; +#[cfg(feature = "webdriver")] +fn webdriver(port: u16, constellation: msg::constellation_msg::ConstellationChan) { + webdriver_server::start_server(port, constellation.clone()); +} + +#[cfg(not(feature = "webdriver"))] +fn webdriver(_port: u16, _constellation: msg::constellation_msg::ConstellationChan) { } + +pub use _util as util; +pub use export::compositing; +pub use export::devtools; +pub use export::devtools_traits; +pub use export::net; +pub use export::net_traits; +pub use export::msg; +pub use export::profile; +pub use export::profile_traits; +pub use export::script; +pub use export::script_traits; +pub use export::layout; +pub use export::gfx; +pub use export::style; +pub use export::canvas; +pub use export::canvas_traits; + +pub use export::euclid; +pub use export::url; +pub use export::layers; +pub use export::gleam::gl; + use compositing::CompositorEventListener; use compositing::windowing::WindowEvent; @@ -110,9 +155,11 @@ impl Browser { devtools_chan, supports_clipboard); - if let Some(port) = opts.webdriver_port { - webdriver_server::start_server(port, constellation_chan.clone()); - }; + if cfg!(feature = "webdriver") { + if let Some(port) = opts.webdriver_port { + webdriver(port, constellation_chan.clone()); + } + } // The compositor coordinates with the client window to create the final // rendered page and display it somewhere. diff --git a/components/servo/main.rs b/components/servo/main.rs index e96703026fe..afefe23f591 100644 --- a/components/servo/main.rs +++ b/components/servo/main.rs @@ -19,29 +19,23 @@ // The Servo engine extern crate servo; -// Window graphics compositing and message dispatch -extern crate compositing; -// Servo networking -extern crate net; -extern crate net_traits; -// Servo common utilitiess -extern crate util; + // The window backed by glutin extern crate glutin_app as app; extern crate time; extern crate env_logger; -#[cfg(target_os="android")] +#[cfg(target_os = "android")] #[macro_use] extern crate android_glue; -use compositing::windowing::WindowEvent; -use net_traits::hosts; use servo::Browser; +use servo::compositing::windowing::WindowEvent; +use servo::net_traits::hosts; +use servo::util::opts; use std::rc::Rc; -use util::opts; -#[cfg(target_os="android")] +#[cfg(target_os = "android")] use std::borrow::ToOwned; fn main() { @@ -134,16 +128,16 @@ impl app::NestedEventLoopListener for BrowserWrapper { } } -#[cfg(target_os="android")] +#[cfg(target_os = "android")] fn setup_logging() { android::setup_logging(); } -#[cfg(not(target_os="android"))] +#[cfg(not(target_os = "android"))] fn setup_logging() { } -#[cfg(target_os="android")] +#[cfg(target_os = "android")] fn get_args() -> Vec { vec![ "servo".to_owned(), @@ -151,7 +145,7 @@ fn get_args() -> Vec { ] } -#[cfg(not(target_os="android"))] +#[cfg(not(target_os = "android"))] fn get_args() -> Vec { use std::env; env::args().collect() @@ -189,10 +183,10 @@ mod android { use self::libc::funcs::c95::stdio::fgets; use self::libc::funcs::posix88::stdio::fdopen; use self::libc::funcs::posix88::unistd::{pipe, dup2}; + use servo::util::task::spawn_named; use std::ffi::CStr; use std::ffi::CString; use std::str::from_utf8; - use util::task::spawn_named; unsafe { let mut pipes: [c_int; 2] = [ 0, 0 ]; diff --git a/components/style/properties.mako.rs b/components/style/properties.mako.rs index b2cfe39d013..ddb70e83d87 100644 --- a/components/style/properties.mako.rs +++ b/components/style/properties.mako.rs @@ -51,7 +51,7 @@ class Longhand(object): self.ident = to_rust_ident(name) self.camel_case = to_camel_case(self.ident) self.style_struct = THIS_STYLE_STRUCT - self.experimental = experimental + self.experimental = ("layout.%s.enabled" % name) if experimental else None self.custom_cascade = custom_cascade if derived_from is None: self.derived_from = None @@ -64,7 +64,7 @@ class Shorthand(object): self.ident = to_rust_ident(name) self.camel_case = to_camel_case(self.ident) self.derived_from = None - self.experimental = experimental + self.experimental = ("layout.%s.enabled" % name) if experimental else None self.sub_properties = [LONGHANDS_BY_NAME[s] for s in sub_properties] class StyleStruct(object): @@ -450,7 +450,9 @@ pub mod longhands { % for value in values[:-1]: "${value}" => { % if value in experimental_values: - if !::util::opts::experimental_enabled() { return Err(()) } + if !::util::prefs::get_pref("layout.${value}.enabled", false) { + return Err(()) + } % endif Ok(computed_value::T::${to_rust_ident(value)}) }, @@ -458,7 +460,9 @@ pub mod longhands { % for value in values[-1:]: "${value}" => { % if value in experimental_values: - if !::util::opts::experimental_enabled() { return Err(()) } + if !::util::prefs::get_pref("layout.${value}.enabled", false) { + return Err(()) + } % endif Ok(computed_value::T::${to_rust_ident(value)}) } @@ -5726,7 +5730,7 @@ impl PropertyDeclaration { % if property.derived_from is None: "${property.name}" => { % if property.experimental: - if !::util::opts::experimental_enabled() { + if !::util::prefs::get_pref("${property.experimental}", false) { return PropertyDeclarationParseResult::ExperimentalProperty } % endif @@ -5745,7 +5749,7 @@ impl PropertyDeclaration { % for shorthand in SHORTHANDS: "${shorthand.name}" => { % if shorthand.experimental: - if !::util::opts::experimental_enabled() { + if !::util::prefs::get_pref("${shorthand.experimental}", false) { return PropertyDeclarationParseResult::ExperimentalProperty } % endif @@ -6587,6 +6591,9 @@ macro_rules! css_properties_accessors { $macro_name! { % for property in SHORTHANDS + LONGHANDS: % if property.derived_from is None: + % if '-' in property.name: + [${property.ident.capitalize()}, Set${property.ident.capitalize()}, "${property.name}"], + % endif % if property != LONGHANDS[-1]: [${property.camel_case}, Set${property.camel_case}, "${property.name}"], % else: diff --git a/components/style/stylesheets.rs b/components/style/stylesheets.rs index 839f002955e..7f625af7282 100644 --- a/components/style/stylesheets.rs +++ b/components/style/stylesheets.rs @@ -429,7 +429,7 @@ impl<'a, 'b> AtRuleParser for NestedRuleParser<'a, 'b> { Ok(AtRuleType::WithBlock(AtRulePrelude::FontFace)) }, "viewport" => { - if ::util::opts::experimental_enabled() { + if ::util::prefs::get_pref("layout.viewport.enabled", false) { Ok(AtRuleType::WithBlock(AtRulePrelude::Viewport)) } else { Err(()) diff --git a/components/style/values.rs b/components/style/values.rs index 9b74427368f..a9addcae8c4 100644 --- a/components/style/values.rs +++ b/components/style/values.rs @@ -151,6 +151,7 @@ pub mod specified { pub enum FontRelativeLength { Em(CSSFloat), Ex(CSSFloat), + Ch(CSSFloat), Rem(CSSFloat) } @@ -159,6 +160,7 @@ pub mod specified { match self { &FontRelativeLength::Em(length) => write!(dest, "{}em", length), &FontRelativeLength::Ex(length) => write!(dest, "{}ex", length), + &FontRelativeLength::Ch(length) => write!(dest, "{}ch", length), &FontRelativeLength::Rem(length) => write!(dest, "{}rem", length) } } @@ -172,9 +174,10 @@ pub mod specified { { match self { &FontRelativeLength::Em(length) => reference_font_size.scale_by(length), - &FontRelativeLength::Ex(length) => { - let x_height = 0.5; // TODO: find that from the font - reference_font_size.scale_by(length * x_height) + &FontRelativeLength::Ex(length) | &FontRelativeLength::Ch(length) => { + // https://github.com/servo/servo/issues/7462 + let em_factor = 0.5; + reference_font_size.scale_by(length * em_factor) }, &FontRelativeLength::Rem(length) => root_font_size.scale_by(length) } @@ -284,6 +287,7 @@ pub mod specified { match self { FontRelativeLength::Em(v) => FontRelativeLength::Em(v * scalar), FontRelativeLength::Ex(v) => FontRelativeLength::Ex(v * scalar), + FontRelativeLength::Ch(v) => FontRelativeLength::Ch(v * scalar), FontRelativeLength::Rem(v) => FontRelativeLength::Rem(v * scalar), } } @@ -338,6 +342,7 @@ pub mod specified { // font-relative "em" => Ok(Length::FontRelative(FontRelativeLength::Em(value))), "ex" => Ok(Length::FontRelative(FontRelativeLength::Ex(value))), + "ch" => Ok(Length::FontRelative(FontRelativeLength::Ch(value))), "rem" => Ok(Length::FontRelative(FontRelativeLength::Rem(value))), // viewport percentages "vw" => Ok(Length::ViewportPercentage(ViewportPercentageLength::Vw(value))), diff --git a/components/util/lib.rs b/components/util/lib.rs index 4c2ef7f6746..b10d5b2a2d1 100644 --- a/components/util/lib.rs +++ b/components/util/lib.rs @@ -60,6 +60,7 @@ pub mod logical_geometry; pub mod mem; pub mod opts; pub mod persistent_list; +pub mod prefs; pub mod range; pub mod resource_files; pub mod str; diff --git a/components/util/opts.rs b/components/util/opts.rs index 65b40e77b73..8a8459f687c 100644 --- a/components/util/opts.rs +++ b/components/util/opts.rs @@ -10,6 +10,7 @@ use geometry::ScreenPx; use euclid::size::{Size2D, TypedSize2D}; use getopts::Options; use num_cpus; +use prefs; use std::cmp; use std::default::Default; use std::env; @@ -17,7 +18,6 @@ use std::fs::{File, PathExt}; use std::io::{self, Read, Write}; use std::path::Path; use std::process; -use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; use url::{self, Url}; /// Global flags for Servo, currently set on the command line. @@ -50,17 +50,12 @@ pub struct Opts { /// and cause it to produce output on that interval (`-m`). pub mem_profiler_period: Option, - /// Enable experimental web features (`-e`). - pub enable_experimental: bool, - /// The number of threads to use for layout (`-y`). Defaults to 1, which results in a recursive /// sequential algorithm. pub layout_threads: usize, pub nonincremental_layout: bool, - pub nossl: bool, - /// Where to load userscripts from, if any. An empty string will load from /// the resources/user-agent-js directory, and if the option isn't passed userscripts /// won't be loaded @@ -123,6 +118,9 @@ pub struct Opts { /// profile viewer. pub profile_tasks: bool, + /// Periodically print out on which events script tasks spend their processing time. + pub profile_script_events: bool, + /// `None` to disable devtools or `Some` with a port number to start a server to listen to /// remote Firefox devtools connections. pub devtools_port: Option, @@ -213,6 +211,9 @@ pub struct DebugOptions { /// Instrument each task, writing the output to a file. pub profile_tasks: bool, + /// Profile which events script tasks spend their time on. + pub profile_script_events: bool, + /// Paint borders along layer and tile boundaries. pub show_compositor_borders: bool, @@ -265,6 +266,7 @@ impl DebugOptions { "dump-display-list-optimized" => debug_options.dump_display_list_optimized = true, "relayout-event" => debug_options.relayout_event = true, "profile-tasks" => debug_options.profile_tasks = true, + "profile-script-events" => debug_options.profile_script_events = true, "show-compositor-borders" => debug_options.show_compositor_borders = true, "show-fragment-borders" => debug_options.show_fragment_borders = true, "show-parallel-paint" => debug_options.show_parallel_paint = true, @@ -331,10 +333,10 @@ fn args_fail(msg: &str) -> ! { // Always use CPU painting on android. -#[cfg(target_os="android")] +#[cfg(target_os = "android")] static FORCE_CPU_PAINTING: bool = true; -#[cfg(not(target_os="android"))] +#[cfg(not(target_os = "android"))] static FORCE_CPU_PAINTING: bool = false; enum UserAgent { @@ -357,15 +359,15 @@ fn default_user_agent_string(agent: UserAgent) -> String { }.to_owned() } -#[cfg(target_os="android")] +#[cfg(target_os = "android")] const DEFAULT_USER_AGENT: UserAgent = UserAgent::Android; // FIXME: This requires https://github.com/servo/servo/issues/7138 to provide the // correct string in Gonk builds (i.e., it will never be chosen today). -#[cfg(target_os="gonk")] +#[cfg(target_os = "gonk")] const DEFAULT_USER_AGENT: UserAgent = UserAgent::Gonk; -#[cfg(not(any(target_os="android", target_os="gonk")))] +#[cfg(not(any(target_os = "android", target_os = "gonk")))] const DEFAULT_USER_AGENT: UserAgent = UserAgent::Desktop; pub fn default_opts() -> Opts { @@ -377,10 +379,8 @@ pub fn default_opts() -> Opts { device_pixels_per_px: None, time_profiler_period: None, mem_profiler_period: None, - enable_experimental: false, layout_threads: 1, nonincremental_layout: false, - nossl: false, userscripts: None, user_stylesheets: Vec::new(), output_file: None, @@ -409,6 +409,7 @@ pub fn default_opts() -> Opts { relayout_event: false, validate_display_list_geometry: false, profile_tasks: false, + profile_script_events: false, resources_path: None, sniff_mime_types: false, disable_share_style_cache: false, @@ -426,7 +427,6 @@ pub fn from_cmdline_args(args: &[String]) { opts.optopt("o", "output", "Output file", "output.png"); opts.optopt("s", "size", "Size of tiles", "512"); opts.optopt("", "device-pixel-ratio", "Device pixels per px", ""); - opts.optflag("e", "experimental", "Enable experimental web features"); opts.optopt("t", "threads", "Number of paint threads", "1"); opts.optflagopt("p", "profile", "Profiler flag and output interval", "10"); opts.optflagopt("m", "memory-profile", "Memory profiler flag and output interval", "10"); @@ -453,6 +453,8 @@ pub fn from_cmdline_args(args: &[String]) { opts.optflag("h", "help", "Print this message"); opts.optopt("", "resources-path", "Path to find static resources", "/home/servo/resources"); opts.optflag("", "sniff-mime-types" , "Enable MIME sniffing"); + opts.optmulti("", "pref", + "A preference to set to enable", "dom.mozbrowser.enabled"); let opt_match = match opts.parse(args) { Ok(m) => m, @@ -527,7 +529,6 @@ pub fn from_cmdline_args(args: &[String]) { }; let nonincremental_layout = opt_match.opt_present("i"); - let nossl = opt_match.opt_present("no-ssl"); let mut bubble_inline_sizes_separately = debug_options.bubble_widths; if debug_options.trace_layout { @@ -581,10 +582,8 @@ pub fn from_cmdline_args(args: &[String]) { device_pixels_per_px: device_pixels_per_px, time_profiler_period: time_profiler_period, mem_profiler_period: mem_profiler_period, - enable_experimental: opt_match.opt_present("e"), layout_threads: layout_threads, nonincremental_layout: nonincremental_layout, - nossl: nossl, userscripts: opt_match.opt_default("userscripts", ""), user_stylesheets: user_stylesheets, output_file: opt_match.opt_str("o"), @@ -594,6 +593,7 @@ pub fn from_cmdline_args(args: &[String]) { hard_fail: opt_match.opt_present("f"), bubble_inline_sizes_separately: bubble_inline_sizes_separately, profile_tasks: debug_options.profile_tasks, + profile_script_events: debug_options.profile_script_events, trace_layout: debug_options.trace_layout, devtools_port: devtools_port, webdriver_port: webdriver_port, @@ -621,19 +621,12 @@ pub fn from_cmdline_args(args: &[String]) { }; set_defaults(opts); -} -static EXPERIMENTAL_ENABLED: AtomicBool = ATOMIC_BOOL_INIT; - -/// Turn on experimental features globally. Normally this is done -/// during initialization by `set` or `from_cmdline_args`, but -/// tests that require experimental features will also set it. -pub fn set_experimental_enabled(new_value: bool) { - EXPERIMENTAL_ENABLED.store(new_value, Ordering::SeqCst); -} - -pub fn experimental_enabled() -> bool { - EXPERIMENTAL_ENABLED.load(Ordering::SeqCst) + // This must happen after setting the default options, since the prefs rely on + // on the resource path. + for pref in opt_match.opt_strs("pref").iter() { + prefs::set_pref(pref, true); + } } // Make Opts available globally. This saves having to clone and pass @@ -644,7 +637,7 @@ const INVALID_OPTIONS: *mut Opts = 0x01 as *mut Opts; lazy_static! { static ref OPTIONS: Opts = { - let opts = unsafe { + unsafe { let initial = if !DEFAULT_OPTIONS.is_null() { let opts = Box::from_raw(DEFAULT_OPTIONS); *opts @@ -653,9 +646,7 @@ lazy_static! { }; DEFAULT_OPTIONS = INVALID_OPTIONS; initial - }; - set_experimental_enabled(opts.enable_experimental); - opts + } }; } diff --git a/components/util/prefs.rs b/components/util/prefs.rs new file mode 100644 index 00000000000..357d7d1481f --- /dev/null +++ b/components/util/prefs.rs @@ -0,0 +1,50 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use resource_files::resources_dir_path; +use rustc_serialize::json::Json; +use std::collections::HashMap; +use std::fs::File; +use std::sync::{Arc, Mutex}; + +lazy_static! { + static ref PREFS: Arc>> = { + let prefs = read_prefs().unwrap_or(HashMap::new()); + Arc::new(Mutex::new(prefs)) + }; +} + +fn read_prefs() -> Result, ()> { + let mut path = resources_dir_path(); + path.push("prefs.json"); + + let mut file = try!(File::open(path).or_else(|e| { + println!("Error opening preferences: {:?}.", e); + Err(()) + })); + let json = try!(Json::from_reader(&mut file).or_else(|e| { + println!("Ignoring invalid JSON in preferences: {:?}.", e); + Err(()) + })); + + let mut prefs = HashMap::new(); + if let Some(obj) = json.as_object() { + for (name, value) in obj.iter() { + if let Some(bool_value) = value.as_boolean() { + prefs.insert(name.clone(), bool_value); + } else { + println!("Ignoring non-boolean preference value for {:?}", name); + } + } + } + Ok(prefs) +} + +pub fn get_pref(name: &str, default: bool) -> bool { + *PREFS.lock().unwrap().get(name).unwrap_or(&default) +} + +pub fn set_pref(name: &str, value: bool) { + let _ = PREFS.lock().unwrap().insert(name.to_owned(), value); +} diff --git a/ports/cef/Cargo.lock b/ports/cef/Cargo.lock index 78284ce5378..a2365e9a784 100644 --- a/ports/cef/Cargo.lock +++ b/ports/cef/Cargo.lock @@ -55,6 +55,14 @@ name = "android_glue" version = "0.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "angle" +version = "0.1.0" +source = "git+https://github.com/ecoal95/angle?branch=servo#77288884bd7a89bf3019ca94dcda6c94cb178aa4" +dependencies = [ + "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "aster" version = "0.4.1" @@ -160,7 +168,7 @@ dependencies = [ [[package]] name = "clipboard" version = "0.0.3" -source = "git+https://github.com/aweinstock314/rust-clipboard#b0092c8630d4362e4618533822bea90a034b0792" +source = "git+https://github.com/aweinstock314/rust-clipboard#8c4c31e73a5ac5afd97825acc4c534dccfc0ab9b" dependencies = [ "clipboard-win 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", @@ -612,7 +620,7 @@ dependencies = [ [[package]] name = "glutin" version = "0.3.5" -source = "git+https://github.com/servo/glutin?branch=servo#22a561c30a0560f445f50abcebf8439d264e0c67" +source = "git+https://github.com/servo/glutin?branch=servo#0b055f889ce0baaa0fc186da4f3b5c31b7c6fd18" dependencies = [ "android_glue 0.0.2 (registry+https://github.com/rust-lang/crates.io-index)", "cgl 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1327,6 +1335,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" name = "script" version = "0.0.1" dependencies = [ + "angle 0.1.0 (git+https://github.com/ecoal95/angle?branch=servo)", "bitflags 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", "canvas 0.0.1", "canvas_traits 0.0.1", diff --git a/ports/glutin/lib.rs b/ports/glutin/lib.rs index 0bd7fffff8e..cb611153be0 100644 --- a/ports/glutin/lib.rs +++ b/ports/glutin/lib.rs @@ -7,7 +7,7 @@ #![feature(box_syntax, result_expect)] #[macro_use] extern crate bitflags; -#[cfg(target_os="macos")] extern crate cgl; +#[cfg(target_os = "macos")] extern crate cgl; extern crate compositing; extern crate euclid; extern crate gleam; @@ -19,9 +19,9 @@ extern crate net_traits; #[cfg(feature = "window")] extern crate script_traits; extern crate time; extern crate util; -#[cfg(target_os="android")] extern crate egl; +#[cfg(target_os = "android")] extern crate egl; extern crate url; -#[cfg(target_os="linux")] extern crate x11; +#[cfg(target_os = "linux")] extern crate x11; use compositing::windowing::WindowEvent; use euclid::scale_factor::ScaleFactor; diff --git a/ports/glutin/window.rs b/ports/glutin/window.rs index a01987ee1f7..ec96727d811 100644 --- a/ports/glutin/window.rs +++ b/ports/glutin/window.rs @@ -35,7 +35,7 @@ use std::cell::{Cell, RefCell}; #[cfg(feature = "window")] use util::opts; -#[cfg(all(feature = "headless", target_os="linux"))] +#[cfg(all(feature = "headless", target_os = "linux"))] use std::ptr; #[cfg(feature = "window")] @@ -56,15 +56,15 @@ bitflags! { } // Some shortcuts use Cmd on Mac and Control on other systems. -#[cfg(all(feature = "window", target_os="macos"))] +#[cfg(all(feature = "window", target_os = "macos"))] const CMD_OR_CONTROL: constellation_msg::KeyModifiers = SUPER; -#[cfg(all(feature = "window", not(target_os="macos")))] +#[cfg(all(feature = "window", not(target_os = "macos")))] const CMD_OR_CONTROL: constellation_msg::KeyModifiers = CONTROL; // Some shortcuts use Cmd on Mac and Alt on other systems. -#[cfg(all(feature = "window", target_os="macos"))] +#[cfg(all(feature = "window", target_os = "macos"))] const CMD_OR_ALT: constellation_msg::KeyModifiers = SUPER; -#[cfg(all(feature = "window", not(target_os="macos")))] +#[cfg(all(feature = "window", not(target_os = "macos")))] const CMD_OR_ALT: constellation_msg::KeyModifiers = ALT; // This should vary by zoom level and maybe actual text size (focused or under cursor) @@ -138,22 +138,22 @@ impl Window { } } - #[cfg(not(target_os="android"))] + #[cfg(not(target_os = "android"))] fn gl_version() -> GlRequest { GlRequest::Specific(Api::OpenGl, (3, 0)) } - #[cfg(target_os="android")] + #[cfg(target_os = "android")] fn gl_version() -> GlRequest { GlRequest::Specific(Api::OpenGlEs, (2, 0)) } - #[cfg(not(target_os="android"))] + #[cfg(not(target_os = "android"))] fn load_gl_functions(window: &glutin::Window) { gl::load_with(|s| window.get_proc_address(s)); } - #[cfg(target_os="android")] + #[cfg(target_os = "android")] fn load_gl_functions(_: &glutin::Window) { } @@ -290,7 +290,7 @@ impl Window { self.event_queue.borrow_mut().push(WindowEvent::MouseWindowEventClass(event)); } - #[cfg(target_os="macos")] + #[cfg(target_os = "macos")] fn handle_next_event(&self) -> bool { let event = self.window.wait_events().next().unwrap(); let mut close = self.handle_window_event(event); @@ -305,7 +305,7 @@ impl Window { close } - #[cfg(any(target_os="linux", target_os="android"))] + #[cfg(any(target_os = "linux", target_os = "android"))] fn handle_next_event(&self) -> bool { use std::thread::sleep_ms; @@ -478,7 +478,7 @@ impl Window { result } - #[cfg(all(feature = "window", not(target_os="win")))] + #[cfg(all(feature = "window", not(target_os = "win")))] fn platform_handle_key(&self, key: Key, mods: constellation_msg::KeyModifiers) { match (mods, key) { (CMD_OR_CONTROL, Key::LeftBracket) => { @@ -491,19 +491,19 @@ impl Window { } } - #[cfg(all(feature = "window", target_os="win"))] + #[cfg(all(feature = "window", target_os = "win"))] fn platform_handle_key(&self, key: Key, mods: constellation_msg::KeyModifiers) { } } // WindowProxy is not implemented for android yet -#[cfg(all(feature = "window", target_os="android"))] +#[cfg(all(feature = "window", target_os = "android"))] fn create_window_proxy(_: &Rc) -> Option { None } -#[cfg(all(feature = "window", not(target_os="android")))] +#[cfg(all(feature = "window", not(target_os = "android")))] fn create_window_proxy(window: &Rc) -> Option { Some(window.window.create_window_proxy()) } @@ -623,7 +623,7 @@ impl WindowMethods for Window { true } - #[cfg(target_os="linux")] + #[cfg(target_os = "linux")] fn native_display(&self) -> NativeDisplay { use x11::xlib; unsafe { @@ -631,7 +631,7 @@ impl WindowMethods for Window { } } - #[cfg(not(target_os="linux"))] + #[cfg(not(target_os = "linux"))] fn native_display(&self) -> NativeDisplay { NativeDisplay::new() } @@ -791,7 +791,7 @@ impl WindowMethods for Window { true } - #[cfg(target_os="linux")] + #[cfg(target_os = "linux")] fn native_display(&self) -> NativeDisplay { NativeDisplay::new(ptr::null_mut()) } diff --git a/ports/gonk/Cargo.lock b/ports/gonk/Cargo.lock index df88f068672..0f810c0de64 100644 --- a/ports/gonk/Cargo.lock +++ b/ports/gonk/Cargo.lock @@ -41,6 +41,14 @@ dependencies = [ "memchr 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "angle" +version = "0.1.0" +source = "git+https://github.com/ecoal95/angle?branch=servo#77288884bd7a89bf3019ca94dcda6c94cb178aa4" +dependencies = [ + "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "aster" version = "0.4.1" @@ -141,7 +149,7 @@ dependencies = [ [[package]] name = "clipboard" version = "0.0.3" -source = "git+https://github.com/aweinstock314/rust-clipboard#b0092c8630d4362e4618533822bea90a034b0792" +source = "git+https://github.com/aweinstock314/rust-clipboard#8c4c31e73a5ac5afd97825acc4c534dccfc0ab9b" dependencies = [ "clipboard-win 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1193,6 +1201,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" name = "script" version = "0.0.1" dependencies = [ + "angle 0.1.0 (git+https://github.com/ecoal95/angle?branch=servo)", "bitflags 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", "canvas 0.0.1", "canvas_traits 0.0.1", diff --git a/python/servo/build_commands.py b/python/servo/build_commands.py index d49632882e5..73d9b9046fa 100644 --- a/python/servo/build_commands.py +++ b/python/servo/build_commands.py @@ -242,9 +242,6 @@ class MachCommands(CommandBase): notify_build_done(elapsed) print("Build completed in %0.2fs" % elapsed) - # XXX(#7339) Android build is broken - if android: - return 0 return status @Command('build-cef', diff --git a/python/servo/devenv_commands.py b/python/servo/devenv_commands.py index 7972b3b3978..65251323bbb 100644 --- a/python/servo/devenv_commands.py +++ b/python/servo/devenv_commands.py @@ -119,8 +119,9 @@ class MachCommands(CommandBase): params = [] # get all directories under tests/ tests_dirs = listdir('tests') - # Remove 'wpt' from obtained dir list - tests_dirs = filter(lambda dir: dir != 'wpt', tests_dirs) + # Directories to be excluded under tests/ + excluded_tests_dirs = ['wpt', 'jquery'] + tests_dirs = filter(lambda dir: dir not in excluded_tests_dirs, tests_dirs) # Set of directories in project root root_dirs = ['components', 'ports', 'python', 'etc', 'resources'] # Generate absolute paths for directories in tests/ and project-root/ @@ -128,4 +129,6 @@ class MachCommands(CommandBase): root_dirs_abs = [path.join(self.context.topdir, s) for s in root_dirs] # Absolute paths for all directories to be considered grep_paths = root_dirs_abs + tests_dirs_abs - return subprocess.call(["git"] + ["grep"] + params + ['--'] + grep_paths, env=self.build_env()) + return subprocess.call( + ["git"] + ["grep"] + params + ['--'] + grep_paths + [':(exclude)*.min.js'], + env=self.build_env()) diff --git a/python/tidy.py b/python/tidy.py index 43ff23aeff5..1185a08e759 100644 --- a/python/tidy.py +++ b/python/tidy.py @@ -188,33 +188,35 @@ def check_rust(file_name, contents): line = merged_lines + line merged_lines = '' - # get rid of strings and chars because cases like regex expression - line = re.sub('".*?"|\'.*?\'', '', line) + # get rid of strings and chars because cases like regex expression, keep attributes + if not line_is_attribute(line): + line = re.sub('".*?"|\'.*?\'', '', line) - # get rid of comments and attributes - line = re.sub('//.*?$|/\*.*?$|^\*.*?$|^#.*?$', '', line) + # get rid of comments + line = re.sub('//.*?$|/\*.*?$|^\*.*?$', '', line) + + # get rid of attributes that do not contain = + line = re.sub('^#[A-Za-z0-9\(\)\[\]_]*?$', '', line) match = re.search(r",[A-Za-z0-9]", line) if match: yield (idx + 1, "missing space after ,") - # Avoid flagging constructs - def is_associated_type(match, line, index): - open_angle = line[0:match.end()].rfind('<') - close_angle = line[open_angle:].find('>') if open_angle != -1 else -1 - is_equals = match.group(0)[index] == '=' - generic_open = open_angle != -1 and open_angle < match.start() - generic_close = close_angle != -1 and close_angle + open_angle >= match.end() - return is_equals and generic_open and generic_close + if line_is_attribute(line): + pre_space_re = r"[A-Za-z0-9]=" + post_space_re = r"=[A-Za-z0-9\"]" + else: + # - not included because of scientific notation (1e-6) + pre_space_re = r"[A-Za-z0-9][\+/\*%=]" + # * not included because of dereferencing and casting + # - not included because of unary negation + post_space_re = r"[\+/\%=][A-Za-z0-9\"]" - # - not included because of scientific notation (1e-6) - match = re.search(r"[A-Za-z0-9][\+/\*%=]", line) + match = re.search(pre_space_re, line) if match and not is_associated_type(match, line, 1): yield (idx + 1, "missing space before %s" % match.group(0)[1]) - # * not included because of dereferencing and casting - # - not included because of unary negation - match = re.search(r"[\+/\%=][A-Za-z0-9]", line) + match = re.search(post_space_re, line) if match and not is_associated_type(match, line, 0): yield (idx + 1, "missing space after %s" % match.group(0)[0]) @@ -243,6 +245,16 @@ def check_rust(file_name, contents): if match: yield (idx + 1, "missing space before {") + # ignored cases like {} and }} + match = re.search(r"[^\s{}]}", line) + if match and not (line.startswith("use") or line.startswith("pub use")): + yield (idx + 1, "missing space before }") + + # ignored cases like {} and {{ + match = re.search(r"{[^\s{}]", line) + if match and not (line.startswith("use") or line.startswith("pub use")): + yield (idx + 1, "missing space after {") + # imports must be in the same line and alphabetically sorted if line.startswith("use "): use = line[4:] @@ -253,10 +265,27 @@ def check_rust(file_name, contents): sorted_uses = sorted(uses) for i in range(len(uses)): if sorted_uses[i] != uses[i]: - yield (idx + 1 - len(uses) + i, "use statement is not in alphabetical order") + message = "use statement is not in alphabetical order" + expected = "\n\t\033[93mexpected: {}\033[0m".format(sorted_uses[i]) + found = "\n\t\033[91mfound: {}\033[0m".format(uses[i]) + yield (idx + 1 - len(uses) + i, message + expected + found) uses = [] +# Avoid flagging constructs +def is_associated_type(match, line, index): + open_angle = line[0:match.end()].rfind('<') + close_angle = line[open_angle:].find('>') if open_angle != -1 else -1 + is_equals = match.group(0)[index] == '=' + generic_open = open_angle != -1 and open_angle < match.start() + generic_close = close_angle != -1 and close_angle + open_angle >= match.end() + return is_equals and generic_open and generic_close + + +def line_is_attribute(line): + return re.search(r"#\[.*\]", line) + + def check_webidl_spec(file_name, contents): # Sorted by this function (in pseudo-Rust). The idea is to group the same # organization together. @@ -310,7 +339,17 @@ def check_spec(file_name, contents): raise StopIteration file_name = os.path.relpath(os.path.splitext(file_name)[0], base_path) patt = re.compile("^\s*\/\/.+") - pattern = "impl<'a> %sMethods for &'a %s {" % (file_name, file_name) + + # Pattern representing a line with a macro + macro_patt = re.compile("^\s*\S+!(.*)$") + + # Pattern representing a line with comment containing a spec link + link_patt = re.compile("^\s*///? https://.+$") + + # Pattern representing a line with comment + comment_patt = re.compile("^\s*///?.+$") + + pattern = "impl %sMethods for %s {" % (file_name, file_name) contents = contents.splitlines(True) brace_count = 0 in_impl = False @@ -320,9 +359,16 @@ def check_spec(file_name, contents): if not patt.match(line): if pattern.lower() in line.lower(): in_impl = True - if "fn " in line and brace_count == 1: - if "// https://" not in contents[idx - 1] and "// https://" not in contents[idx - 2]: - yield (idx + 1, "method declared in webidl is missing a comment with a specification link") + if ("fn " in line or macro_patt.match(line)) and brace_count == 1: + for up_idx in range(1, idx + 1): + up_line = contents[idx - up_idx] + if link_patt.match(up_line): + # Comment with spec link exists + break + if not comment_patt.match(up_line): + # No more comments exist above, yield warning + yield (idx + 1, "method declared in webidl is missing a comment with a specification link") + break if '{' in line and in_impl: brace_count += 1 if '}' in line and in_impl: diff --git a/resources/prefs.json b/resources/prefs.json new file mode 100644 index 00000000000..3f7ad3a9cbb --- /dev/null +++ b/resources/prefs.json @@ -0,0 +1,13 @@ +{ + "dom.mouseevent.which.enabled": false, + "dom.mozbrowser.enabled": false, + "layout.columns.enabled": false, + "layout.column-width.enabled": false, + "layout.column-count.enabled": false, + "layout.column-gap.enabled": false, + "layout.flex.enabled": false, + "layout.flex-direction.enabled": false, + "layout.text-orientation.enabled": false, + "layout.viewport.enabled": false, + "layout.writing-mode.enabled": false +} diff --git a/tests/ref/absolute_table.html b/tests/ref/absolute_table.html new file mode 100644 index 00000000000..b0dc978e34f --- /dev/null +++ b/tests/ref/absolute_table.html @@ -0,0 +1,7 @@ + + +
+XXX +
diff --git a/tests/ref/absolute_table_ref.html b/tests/ref/absolute_table_ref.html new file mode 100644 index 00000000000..40018562574 --- /dev/null +++ b/tests/ref/absolute_table_ref.html @@ -0,0 +1,7 @@ + + +
+XXX +
diff --git a/tests/ref/basic.list b/tests/ref/basic.list index 2c85fe77f99..8018fb4f62e 100644 --- a/tests/ref/basic.list +++ b/tests/ref/basic.list @@ -12,6 +12,7 @@ fragment=top != ../html/acid2.html acid2_ref.html == abs_rel_explicit_height.html abs_rel_explicit_height_ref.html == absolute_hypothetical_with_intervening_inline_block_a.html absolute_hypothetical_with_intervening_inline_block_ref.html == absolute_inline_containing_block_a.html absolute_inline_containing_block_ref.html +== absolute_table.html absolute_table_ref.html == absolute_z_index_auto_paint_order_a.html absolute_z_index_auto_paint_order_ref.html == acid1_a.html acid1_b.html == acid2_noscroll.html acid2_ref_broken.html @@ -61,6 +62,7 @@ flaky_cpu == append_style_a.html append_style_b.html == border_code_tag.html border_code_tag_ref.html == border_collapse_missing_cell_a.html border_collapse_missing_cell_ref.html == border_collapse_simple_a.html border_collapse_simple_ref.html +== border_radius_asymmetric_sizes_a.html border_radius_asymmetric_sizes_ref.html == border_radius_clip_a.html border_radius_clip_ref.html != border_radius_dashed_a.html border_radius_dashed_ref.html == border_radius_overlapping_a.html border_radius_overlapping_ref.html @@ -99,8 +101,8 @@ flaky_cpu == append_style_a.html append_style_b.html == first_child_pseudo_a.html first_child_pseudo_b.html == first_of_type_pseudo_a.html first_of_type_pseudo_b.html == fixed_width_overrides_child_intrinsic_width_a.html fixed_width_overrides_child_intrinsic_width_ref.html -experimental == flex_column_direction.html flex_column_direction_ref.html -experimental == flex_row_direction.html flex_row_direction_ref.html +prefs:"layout.flex-direction.enabled,layout.flex.enabled" == flex_column_direction.html flex_column_direction_ref.html +prefs:"layout.flex.enabled" == flex_row_direction.html flex_row_direction_ref.html == float_clearance_a.html float_clearance_ref.html == float_clearance_intrinsic_width_a.html float_clearance_intrinsic_width_ref.html == float_intrinsic_height.html float_intrinsic_height_ref.html @@ -139,7 +141,7 @@ experimental == flex_row_direction.html flex_row_direction_ref.html == iframe/simple_inline_width_height.html iframe/simple_inline_width_height_ref.html == iframe/simple_inline_width_percentage.html iframe/simple_inline_width_percentage_ref.html == iframe/size_attributes.html iframe/size_attributes_ref.html -experimental == iframe/size_attributes_vertical_writing_mode.html iframe/size_attributes_vertical_writing_mode_ref.html +prefs:"layout.writing-mode.enabled" == iframe/size_attributes_vertical_writing_mode.html iframe/size_attributes_vertical_writing_mode_ref.html == iframe/stacking_context.html iframe/stacking_context_ref.html != image_rendering_auto_a.html image_rendering_pixelated_a.html @@ -358,7 +360,7 @@ flaky_cpu == linebreak_simple_a.html linebreak_simple_b.html == transform_simple_a.html transform_simple_ref.html == transform_stacking_context_a.html transform_stacking_context_ref.html == upper_id_attr.html upper_id_attr_ref.html -flaky_cpu,experimental == vertical-lr-blocks.html vertical-lr-blocks_ref.html +flaky_cpu,prefs:"layout.writing-mode.enabled" == vertical-lr-blocks.html vertical-lr-blocks_ref.html == vertical_align_bottom_a.html vertical_align_bottom_ref.html == vertical_align_inline_block_a.html vertical_align_inline_block_ref.html == vertical_align_inside_table_a.html vertical_align_inside_table_ref.html @@ -374,7 +376,7 @@ resolution=800x600 == viewport_percentage_vmin_vmax.html viewport_percentage_vmi # resolution=600x800 == viewport_percentage_vmin_vmax.html viewport_percentage_vmin_vmax_b.html resolution=800x600 == viewport_percentage_vw_vh.html viewport_percentage_vw_vh_a.html # resolution=600x800 == viewport_percentage_vw_vh.html viewport_percentage_vw_vh_b.html -experimental == viewport_rule.html viewport_rule_ref.html +prefs:"layout.viewport.enabled" == viewport_rule.html viewport_rule_ref.html == visibility_hidden.html visibility_hidden_ref.html == webgl-context/clearcolor.html webgl-context/clearcolor_ref.html diff --git a/tests/ref/border_radius_asymmetric_sizes_a.html b/tests/ref/border_radius_asymmetric_sizes_a.html new file mode 100644 index 00000000000..94676b11941 --- /dev/null +++ b/tests/ref/border_radius_asymmetric_sizes_a.html @@ -0,0 +1,71 @@ + + + + + + + + +

Border Radius - 10px

+ Box#1

+ Box#2

+ Box#3

+ Box#4

+ +

Border Radius - 20px

+ Box#5

+ Box#6

+ Box#7

+ Box#8

+ +

Border Radius - 30px

+ Box#9

+ Box#10

+ Box#11

+ Box#12

+ +

Border Radius - 40px

+ Box#13

+ Box#14

+ Box#15

+ Box#16

+ + diff --git a/tests/ref/border_radius_asymmetric_sizes_ref.html b/tests/ref/border_radius_asymmetric_sizes_ref.html new file mode 100644 index 00000000000..4993ae6fd7d --- /dev/null +++ b/tests/ref/border_radius_asymmetric_sizes_ref.html @@ -0,0 +1,217 @@ + + + + + + + + +

Border Radius - 10px

+ Box#1 +
+
+
+
+ + Box#2 +
+
+
+
+ + Box#3 +
+
+
+
+ + Box#4 +
+
+
+
+ +

Border Radius - 20px

+ Box#5 +
+
+
+
+ + Box#6 +
+
+
+
+ + Box#7 +
+
+
+
+ + Box#8 +
+
+
+
+ +

Border Radius - 30px

+ Box#9 +
+
+
+
+ + Box#10 +
+
+
+
+ + Box#11 +
+
+
+
+ + Box#12 +
+
+
+
+ +

Border Radius - 40px

+ Box#13 +
+
+
+
+ + Box#14 +
+
+
+
+ + Box#15 +
+
+
+
+ + Box#16 +
+
+
+
+ + diff --git a/tests/ref/webgl-context/tex_image_2d_simple.html b/tests/ref/webgl-context/tex_image_2d_simple.html index 9ba19e2e6dc..60ea4674530 100644 --- a/tests/ref/webgl-context/tex_image_2d_simple.html +++ b/tests/ref/webgl-context/tex_image_2d_simple.html @@ -10,6 +10,7 @@ diff --git a/tests/wpt/web-platform-tests/dom/nodes/CharacterData-data.html b/tests/wpt/web-platform-tests/dom/nodes/CharacterData-data.html index a8a98d41233..b3b29ea4d76 100644 --- a/tests/wpt/web-platform-tests/dom/nodes/CharacterData-data.html +++ b/tests/wpt/web-platform-tests/dom/nodes/CharacterData-data.html @@ -66,6 +66,15 @@ function testNode(create, type) { assert_equals(node.data, "資料") assert_equals(node.length, 2) }, type + ".data = '資料'") + + test(function() { + var node = create() + assert_equals(node.data, "test") + + node.data = "🌠 test 🌠 TEST"; + assert_equals(node.data, "🌠 test 🌠 TEST") + assert_equals(node.length, 15) // Counting UTF-16 code units + }, type + ".data = '🌠 test 🌠 TEST'") } testNode(function() { return document.createTextNode("test") }, "Text") diff --git a/tests/wpt/web-platform-tests/dom/nodes/CharacterData-deleteData.html b/tests/wpt/web-platform-tests/dom/nodes/CharacterData-deleteData.html index ef31a79dcf4..02ecbe6abfa 100644 --- a/tests/wpt/web-platform-tests/dom/nodes/CharacterData-deleteData.html +++ b/tests/wpt/web-platform-tests/dom/nodes/CharacterData-deleteData.html @@ -78,6 +78,16 @@ function testNode(create, type) { node.deleteData(45, 2); assert_equals(node.data, "This is the character data test, append 資料,更多資料"); }, type + ".deleteData() with non-ascii data") + + test(function() { + var node = create() + assert_equals(node.data, "test") + + node.data = "🌠 test 🌠 TEST" + + node.deleteData(5, 8); // Counting UTF-16 code units + assert_equals(node.data, "🌠 teST"); + }, type + ".deleteData() with non-BMP data") } testNode(function() { return document.createTextNode("test") }, "Text") diff --git a/tests/wpt/web-platform-tests/dom/nodes/CharacterData-insertData.html b/tests/wpt/web-platform-tests/dom/nodes/CharacterData-insertData.html index 983e791dca2..5777327c26f 100644 --- a/tests/wpt/web-platform-tests/dom/nodes/CharacterData-insertData.html +++ b/tests/wpt/web-platform-tests/dom/nodes/CharacterData-insertData.html @@ -73,6 +73,16 @@ function testNode(create, type) { node.insertData(48, "更多"); assert_equals(node.data, "This is the character data test, append more 資料,更多測試資料"); }, type + ".insertData() with non-ascii data") + + test(function() { + var node = create() + assert_equals(node.data, "test") + + node.data = "🌠 test 🌠 TEST" + + node.insertData(5, "--"); // Counting UTF-16 code units + assert_equals(node.data, "🌠 te--st 🌠 TEST"); + }, type + ".insertData() with non-BMP data") } testNode(function() { return document.createTextNode("test") }, "Text") diff --git a/tests/wpt/web-platform-tests/dom/nodes/CharacterData-replaceData.html b/tests/wpt/web-platform-tests/dom/nodes/CharacterData-replaceData.html index 78cdc8a9f08..624ee5f237f 100644 --- a/tests/wpt/web-platform-tests/dom/nodes/CharacterData-replaceData.html +++ b/tests/wpt/web-platform-tests/dom/nodes/CharacterData-replaceData.html @@ -146,6 +146,16 @@ function testNode(create, type) { node.replaceData(44, 2, "文字"); assert_equals(node.data, "This is the character data test, other 資料,更多文字"); }, type + ".replaceData() with non-ASCII data") + + test(function() { + var node = create() + assert_equals(node.data, "test") + + node.data = "🌠 test 🌠 TEST" + + node.replaceData(5, 8, "--"); // Counting UTF-16 code units + assert_equals(node.data, "🌠 te--ST"); + }, type + ".replaceData() with non-BMP data") } testNode(function() { return document.createTextNode("test") }, "Text") diff --git a/tests/wpt/web-platform-tests/dom/nodes/CharacterData-substringData.html b/tests/wpt/web-platform-tests/dom/nodes/CharacterData-substringData.html index 84795d0e043..f20b4b202ba 100644 --- a/tests/wpt/web-platform-tests/dom/nodes/CharacterData-substringData.html +++ b/tests/wpt/web-platform-tests/dom/nodes/CharacterData-substringData.html @@ -121,6 +121,15 @@ function testNode(create, type) { assert_equals(node.substringData(12, 4), "char") assert_equals(node.substringData(39, 2), "資料") }, type + ".substringData() with non-ASCII data") + + test(function() { + var node = create() + assert_equals(node.data, "test") + + node.data = "🌠 test 🌠 TEST" + + assert_equals(node.substringData(5, 8), "st 🌠 TE") // Counting UTF-16 code units + }, type + ".substringData() with non-BMP data") } testNode(function() { return document.createTextNode("test") }, "Text") diff --git a/tests/wpt/web-platform-tests/dom/nodes/CharacterData-surrogates.html b/tests/wpt/web-platform-tests/dom/nodes/CharacterData-surrogates.html new file mode 100644 index 00000000000..ff1014c5fdd --- /dev/null +++ b/tests/wpt/web-platform-tests/dom/nodes/CharacterData-surrogates.html @@ -0,0 +1,74 @@ + + +Splitting and joining surrogate pairs in CharacterData methods + + + + + + + +
+