diff options
225 files changed, 4494 insertions, 4175 deletions
diff --git a/components/canvas/canvas_paint_task.rs b/components/canvas/canvas_paint_task.rs index ee71bd16483..4d8adef0478 100644 --- a/components/canvas/canvas_paint_task.rs +++ b/components/canvas/canvas_paint_task.rs @@ -42,11 +42,11 @@ impl CanvasPaintTask { loop { match port.recv() { - FillRect(ref rect) => painter.fill_rect(rect), - StrokeRect(ref rect) => painter.stroke_rect(rect), - ClearRect(ref rect) => painter.clear_rect(rect), - Recreate(size) => painter.recreate(size), - Close => break, + CanvasMsg::FillRect(ref rect) => painter.fill_rect(rect), + CanvasMsg::StrokeRect(ref rect) => painter.stroke_rect(rect), + CanvasMsg::ClearRect(ref rect) => painter.clear_rect(rect), + CanvasMsg::Recreate(size) => painter.recreate(size), + CanvasMsg::Close => break, } } }); diff --git a/components/compositing/Cargo.toml b/components/compositing/Cargo.toml index d24be54918e..6fb0ed57ca1 100644 --- a/components/compositing/Cargo.toml +++ b/components/compositing/Cargo.toml @@ -54,3 +54,6 @@ git = "https://github.com/servo/rust-core-text" [dependencies.gleam] git = "https://github.com/servo/gleam" + +[dependencies.time] +git = "https://github.com/rust-lang/time" diff --git a/components/compositing/compositor.rs b/components/compositing/compositor.rs index 21cfcfdcd86..0b18124f53a 100644 --- a/components/compositing/compositor.rs +++ b/components/compositing/compositor.rs @@ -2,25 +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 compositor_layer::{CompositorData, CompositorLayer, DoesntWantScrollEvents}; -use compositor_layer::{WantsScrollEvents}; -use compositor_task; -use compositor_task::{ChangePageLoadData, ChangePageTitle, ChangePaintState, ChangeReadyState}; -use compositor_task::{CompositorEventListener, CompositorProxy, CompositorReceiver}; -use compositor_task::{CompositorTask, CreateOrUpdateDescendantLayer, CreateOrUpdateRootLayer}; -use compositor_task::{Exit, FrameTreeUpdateMsg, GetGraphicsMetadata, LayerProperties}; -use compositor_task::{LoadComplete, Msg, Paint, PaintMsgDiscarded, ScrollFragmentPoint}; -use compositor_task::{ScrollTimeout, SetIds, SetLayerOrigin, ShutdownComplete}; +use compositor_layer::{CompositorData, CompositorLayer, WantsScrollEventsFlag}; +use compositor_task::{CompositorEventListener, CompositorProxy, CompositorReceiver, CompositorTask}; +use compositor_task::{LayerProperties, Msg}; use constellation::{FrameId, FrameTreeDiff, SendableFrameTree}; use pipeline::CompositionPipeline; use scrolling::ScrollingTimerProxy; use windowing; -use windowing::{IdleWindowEvent, InitializeCompositingWindowEvent}; -use windowing::{KeyEvent, LoadUrlWindowEvent, MouseWindowClickEvent, MouseWindowEvent}; -use windowing::{MouseWindowEventClass, MouseWindowMouseDownEvent, MouseWindowMouseUpEvent}; -use windowing::{MouseWindowMoveEventClass, NavigationWindowEvent, PinchZoomWindowEvent}; -use windowing::{QuitWindowEvent, RefreshWindowEvent, ResizeWindowEvent, ScrollWindowEvent}; -use windowing::{WindowEvent, WindowMethods, WindowNavigateMsg, ZoomWindowEvent}; +use windowing::{MouseWindowEvent, WindowEvent, WindowMethods, WindowNavigateMsg}; use azure::azure_hl; use std::cmp; @@ -54,6 +43,7 @@ use servo_util::{memory, time}; use std::collections::HashMap; use std::collections::hash_map::{Occupied, Vacant}; use std::path::Path; +use std::num::FloatMath; use std::rc::Rc; use std::slice::bytes::copy_memory; use time::{precise_time_ns, precise_time_s}; @@ -192,9 +182,9 @@ impl<Window: WindowMethods> IOCompositor<Window> { window_size: window_size, hidpi_factor: hidpi_factor, scrolling_timer: ScrollingTimerProxy::new(sender), - composition_request: NoCompositingNecessary, + composition_request: CompositionRequest::NoCompositingNecessary, pending_scroll_events: Vec::new(), - shutdown_state: NotShuttingDown, + shutdown_state: ShutdownState::NotShuttingDown, page_zoom: ScaleFactor(1.0), viewport_zoom: ScaleFactor(1.0), zoom_action: false, @@ -237,83 +227,88 @@ impl<Window: WindowMethods> IOCompositor<Window> { fn handle_browser_message(&mut self, msg: Msg) -> bool { match (msg, self.shutdown_state) { - (_, FinishedShuttingDown) => + (_, ShutdownState::FinishedShuttingDown) => panic!("compositor shouldn't be handling messages after shutting down"), - (Exit(chan), _) => { + (Msg::Exit(chan), _) => { debug!("shutting down the constellation"); let ConstellationChan(ref con_chan) = self.constellation_chan; con_chan.send(ExitMsg); chan.send(()); - self.shutdown_state = ShuttingDown; + self.shutdown_state = ShutdownState::ShuttingDown; } - (ShutdownComplete, _) => { + (Msg::ShutdownComplete, _) => { debug!("constellation completed shutdown"); - self.shutdown_state = FinishedShuttingDown; + self.shutdown_state = ShutdownState::FinishedShuttingDown; return false; } - (ChangeReadyState(pipeline_id, ready_state), NotShuttingDown) => { + (Msg::ChangeReadyState(pipeline_id, ready_state), ShutdownState::NotShuttingDown) => { self.change_ready_state(pipeline_id, ready_state); } - (ChangePaintState(pipeline_id, paint_state), NotShuttingDown) => { + (Msg::ChangePaintState(pipeline_id, paint_state), ShutdownState::NotShuttingDown) => { self.change_paint_state(pipeline_id, paint_state); } - (ChangePageTitle(pipeline_id, title), NotShuttingDown) => { + (Msg::ChangePageTitle(pipeline_id, title), ShutdownState::NotShuttingDown) => { self.change_page_title(pipeline_id, title); } - (ChangePageLoadData(frame_id, load_data), NotShuttingDown) => { + (Msg::ChangePageLoadData(frame_id, load_data), ShutdownState::NotShuttingDown) => { self.change_page_load_data(frame_id, load_data); } - (PaintMsgDiscarded, NotShuttingDown) => { + (Msg::PaintMsgDiscarded, ShutdownState::NotShuttingDown) => { self.remove_outstanding_paint_msg(); } - (SetIds(frame_tree, response_chan, new_constellation_chan), NotShuttingDown) => { + (Msg::SetIds(frame_tree, response_chan, new_constellation_chan), + ShutdownState::NotShuttingDown) => { self.set_frame_tree(&frame_tree, response_chan, new_constellation_chan); self.send_viewport_rects_for_all_layers(); } - (FrameTreeUpdateMsg(frame_tree_diff, response_channel), NotShuttingDown) => { + (Msg::FrameTreeUpdate(frame_tree_diff, response_channel), + ShutdownState::NotShuttingDown) => { self.update_frame_tree(&frame_tree_diff); response_channel.send(()); } - (CreateOrUpdateRootLayer(layer_properties), NotShuttingDown) => { + (Msg::CreateOrUpdateRootLayer(layer_properties), ShutdownState::NotShuttingDown) => { self.create_or_update_root_layer(layer_properties); } - (CreateOrUpdateDescendantLayer(layer_properties), NotShuttingDown) => { + (Msg::CreateOrUpdateDescendantLayer(layer_properties), + ShutdownState::NotShuttingDown) => { self.create_or_update_descendant_layer(layer_properties); } - (GetGraphicsMetadata(chan), NotShuttingDown) => { + (Msg::GetGraphicsMetadata(chan), ShutdownState::NotShuttingDown) => { chan.send(Some(self.window.native_metadata())); } - (SetLayerOrigin(pipeline_id, layer_id, origin), NotShuttingDown) => { + (Msg::SetLayerOrigin(pipeline_id, layer_id, origin), + ShutdownState::NotShuttingDown) => { self.set_layer_origin(pipeline_id, layer_id, origin); } - (Paint(pipeline_id, epoch, replies), NotShuttingDown) => { + (Msg::Paint(pipeline_id, epoch, replies), ShutdownState::NotShuttingDown) => { for (layer_id, new_layer_buffer_set) in replies.into_iter() { self.paint(pipeline_id, layer_id, new_layer_buffer_set, epoch); } self.remove_outstanding_paint_msg(); } - (ScrollFragmentPoint(pipeline_id, layer_id, point), NotShuttingDown) => { + (Msg::ScrollFragmentPoint(pipeline_id, layer_id, point), + ShutdownState::NotShuttingDown) => { self.scroll_fragment_to_point(pipeline_id, layer_id, point); } - (LoadComplete, NotShuttingDown) => { + (Msg::LoadComplete, ShutdownState::NotShuttingDown) => { self.got_load_complete_message = true; // If we're painting in headless mode, schedule a recomposite. @@ -327,24 +322,26 @@ impl<Window: WindowMethods> IOCompositor<Window> { self.window.load_end(); } - (ScrollTimeout(timestamp), NotShuttingDown) => { + (Msg::ScrollTimeout(timestamp), ShutdownState::NotShuttingDown) => { debug!("scroll timeout, drawing unpainted content!"); match self.composition_request { - CompositeOnScrollTimeout(this_timestamp) if timestamp == this_timestamp => { - self.composition_request = CompositeNow + CompositionRequest::CompositeOnScrollTimeout(this_timestamp) => { + if timestamp == this_timestamp { + self.composition_request = CompositionRequest::CompositeNow + } } _ => {} } } - (compositor_task::KeyEvent(key, modified), NotShuttingDown) => { + (Msg::KeyEvent(key, modified), ShutdownState::NotShuttingDown) => { self.window.handle_key(key, modified); } // When we are shutting_down, we need to avoid performing operations // such as Paint that may crash because we have begun tearing down // the rest of our resources. - (_, ShuttingDown) => { } + (_, ShutdownState::ShuttingDown) => { } } true @@ -502,10 +499,11 @@ impl<Window: WindowMethods> IOCompositor<Window> { root_layer.update_layer_except_size(layer_properties); let root_layer_pipeline = root_layer.extra_data.borrow().pipeline.clone(); - let first_child = CompositorData::new_layer(root_layer_pipeline.clone(), - layer_properties, - DoesntWantScrollEvents, - opts::get().tile_size); + let first_child = CompositorData::new_layer( + root_layer_pipeline.clone(), + layer_properties, + WantsScrollEventsFlag::DoesntWantScrollEvents, + opts::get().tile_size); // Add the first child / base layer to the front of the child list, so that // child iframe layers are painted on top of the base layer. These iframe @@ -533,7 +531,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { let root_layer_pipeline = root_layer.extra_data.borrow().pipeline.clone(); let new_layer = CompositorData::new_layer(root_layer_pipeline, layer_properties, - DoesntWantScrollEvents, + WantsScrollEventsFlag::DoesntWantScrollEvents, root_layer.tile_size); root_layer.add_child(new_layer); } @@ -558,7 +556,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { -> bool { match self.find_layer_with_pipeline_and_layer_id(pipeline_id, layer_id) { Some(ref layer) => { - if layer.extra_data.borrow().wants_scroll_events == WantsScrollEvents { + if layer.wants_scroll_events() == WantsScrollEventsFlag::WantsScrollEvents { layer.clamp_scroll_offset_and_scroll_layer(TypedPoint2D(0f32, 0f32) - origin); } true @@ -584,13 +582,14 @@ impl<Window: WindowMethods> IOCompositor<Window> { fn start_scrolling_timer_if_necessary(&mut self) { match self.composition_request { - CompositeNow | CompositeOnScrollTimeout(_) => return, - NoCompositingNecessary => {} + CompositionRequest::CompositeNow | CompositionRequest::CompositeOnScrollTimeout(_) => + return, + CompositionRequest::NoCompositingNecessary => {} } let timestamp = precise_time_ns(); self.scrolling_timer.scroll_event_processed(timestamp); - self.composition_request = CompositeOnScrollTimeout(timestamp); + self.composition_request = CompositionRequest::CompositeOnScrollTimeout(timestamp); } fn set_layer_origin(&mut self, @@ -651,57 +650,57 @@ impl<Window: WindowMethods> IOCompositor<Window> { fn handle_window_message(&mut self, event: WindowEvent) { match event { - IdleWindowEvent => {} + WindowEvent::Idle => {} - RefreshWindowEvent => { + WindowEvent::Refresh => { self.composite(); } - InitializeCompositingWindowEvent => { + WindowEvent::InitializeCompositing => { self.initialize_compositing(); } - ResizeWindowEvent(size) => { + WindowEvent::Resize(size) => { self.on_resize_window_event(size); } - LoadUrlWindowEvent(url_string) => { + WindowEvent::LoadUrl(url_string) => { self.on_load_url_window_event(url_string); } - MouseWindowEventClass(mouse_window_event) => { + WindowEvent::MouseWindowEventClass(mouse_window_event) => { self.on_mouse_window_event_class(mouse_window_event); } - MouseWindowMoveEventClass(cursor) => { + WindowEvent::MouseWindowMoveEventClass(cursor) => { self.on_mouse_window_move_event_class(cursor); } - ScrollWindowEvent(delta, cursor) => { + WindowEvent::Scroll(delta, cursor) => { self.on_scroll_window_event(delta, cursor); } - ZoomWindowEvent(magnification) => { + WindowEvent::Zoom(magnification) => { self.on_zoom_window_event(magnification); } - PinchZoomWindowEvent(magnification) => { + WindowEvent::PinchZoom(magnification) => { self.on_pinch_zoom_window_event(magnification); } - NavigationWindowEvent(direction) => { + WindowEvent::Navigation(direction) => { self.on_navigation_window_event(direction); } - KeyEvent(key, state, modifiers) => { + WindowEvent::KeyEvent(key, state, modifiers) => { self.on_key_event(key, state, modifiers); } - QuitWindowEvent => { - debug!("shutting down the constellation for QuitWindowEvent"); + WindowEvent::Quit => { + debug!("shutting down the constellation for WindowEvent::Quit"); let ConstellationChan(ref chan) = self.constellation_chan; chan.send(ExitMsg); - self.shutdown_state = ShuttingDown; + self.shutdown_state = ShutdownState::ShuttingDown; } } } @@ -731,7 +730,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { self.got_load_complete_message = false; let root_pipeline_id = match self.scene.root { Some(ref layer) => layer.extra_data.borrow().pipeline.id.clone(), - None => panic!("Compositor: Received LoadUrlWindowEvent without initialized compositor \ + None => panic!("Compositor: Received WindowEvent::LoadUrl without initialized compositor \ layers"), }; @@ -743,9 +742,9 @@ impl<Window: WindowMethods> IOCompositor<Window> { fn on_mouse_window_event_class(&self, mouse_window_event: MouseWindowEvent) { let point = match mouse_window_event { - MouseWindowClickEvent(_, p) => p, - MouseWindowMouseDownEvent(_, p) => p, - MouseWindowMouseUpEvent(_, p) => p, + MouseWindowEvent::MouseWindowClickEvent(_, p) => p, + MouseWindowEvent::MouseWindowMouseDownEvent(_, p) => p, + MouseWindowEvent::MouseWindowMouseUpEvent(_, p) => p, }; match self.find_topmost_layer_at_point(point / self.scene.scale) { Some(result) => result.layer.send_mouse_event(mouse_window_event, result.point), @@ -853,8 +852,8 @@ impl<Window: WindowMethods> IOCompositor<Window> { fn on_navigation_window_event(&self, direction: WindowNavigateMsg) { let direction = match direction { - windowing::Forward => constellation_msg::Forward, - windowing::Back => constellation_msg::Back, + windowing::WindowNavigateMsg::Forward => constellation_msg::Forward, + windowing::WindowNavigateMsg::Back => constellation_msg::Back, }; let ConstellationChan(ref chan) = self.constellation_chan; chan.send(NavigateMsg(direction)) @@ -1077,7 +1076,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { debug!("shutting down the constellation after generating an output file"); let ConstellationChan(ref chan) = self.constellation_chan; chan.send(ExitMsg); - self.shutdown_state = ShuttingDown; + self.shutdown_state = ShutdownState::ShuttingDown; } // Perform the page flip. This will likely block for a while. @@ -1085,13 +1084,13 @@ impl<Window: WindowMethods> IOCompositor<Window> { self.last_composite_time = precise_time_ns(); - self.composition_request = NoCompositingNecessary; + self.composition_request = CompositionRequest::NoCompositingNecessary; self.process_pending_scroll_events(); } fn composite_if_necessary(&mut self) { - if self.composition_request == NoCompositingNecessary { - self.composition_request = CompositeNow + if self.composition_request == CompositionRequest::NoCompositingNecessary { + self.composition_request = CompositionRequest::CompositeNow } } @@ -1208,7 +1207,7 @@ fn create_root_layer_for_pipeline_and_rect(pipeline: &CompositionPipeline, let root_layer = CompositorData::new_layer(pipeline.clone(), layer_properties, - WantsScrollEvents, + WantsScrollEventsFlag::WantsScrollEvents, opts::get().tile_size); // All root layers mask to bounds. @@ -1239,7 +1238,7 @@ impl<Window> CompositorEventListener for IOCompositor<Window> where Window: Wind } } - if self.shutdown_state == FinishedShuttingDown { + if self.shutdown_state == ShutdownState::FinishedShuttingDown { // We have exited the compositor and passing window // messages to script may crash. debug!("Exiting the compositor due to a request from script."); @@ -1257,11 +1256,11 @@ impl<Window> CompositorEventListener for IOCompositor<Window> where Window: Wind } match self.composition_request { - NoCompositingNecessary | CompositeOnScrollTimeout(_) => {} - CompositeNow => self.composite(), + CompositionRequest::NoCompositingNecessary | CompositionRequest::CompositeOnScrollTimeout(_) => {} + CompositionRequest::CompositeNow => self.composite(), } - self.shutdown_state != FinishedShuttingDown + self.shutdown_state != ShutdownState::FinishedShuttingDown } /// Repaints and recomposites synchronously. You must be careful when calling this, as if a @@ -1269,10 +1268,10 @@ impl<Window> CompositorEventListener for IOCompositor<Window> where Window: Wind /// /// This is used when resizing the window. fn repaint_synchronously(&mut self) { - while self.shutdown_state != ShuttingDown { + while self.shutdown_state != ShutdownState::ShuttingDown { let msg = self.port.recv_compositor_msg(); let is_paint = match msg { - Paint(..) => true, + Msg::Paint(..) => true, _ => false, }; let keep_going = self.handle_browser_message(msg); @@ -1299,10 +1298,10 @@ impl<Window> CompositorEventListener for IOCompositor<Window> where Window: Wind // Tell the profiler, memory profiler, and scrolling timer to shut down. let TimeProfilerChan(ref time_profiler_chan) = self.time_profiler_chan; - time_profiler_chan.send(time::ExitMsg); + time_profiler_chan.send(time::TimeProfilerMsg::Exit); let MemoryProfilerChan(ref memory_profiler_chan) = self.memory_profiler_chan; - memory_profiler_chan.send(memory::ExitMsg); + memory_profiler_chan.send(memory::MemoryProfilerMsg::Exit); self.scrolling_timer.shutdown(); } diff --git a/components/compositing/compositor_layer.rs b/components/compositing/compositor_layer.rs index 804ebb8625a..00324bd34c4 100644 --- a/components/compositing/compositor_layer.rs +++ b/components/compositing/compositor_layer.rs @@ -4,9 +4,7 @@ use compositor_task::LayerProperties; use pipeline::CompositionPipeline; -use windowing::{MouseWindowEvent, MouseWindowClickEvent, MouseWindowMouseDownEvent}; -use windowing::MouseWindowMouseUpEvent; -use windowing::WindowMethods; +use windowing::{MouseWindowEvent, WindowMethods}; use azure::azure_hl; use geom::length::Length; @@ -22,6 +20,8 @@ use layers::platform::surface::NativeSurfaceMethods; use script_traits::{ClickEvent, MouseDownEvent, MouseMoveEvent, MouseUpEvent, SendEventMsg}; use script_traits::{ScriptControlChan}; use servo_msg::compositor_msg::{Epoch, FixedPosition, LayerId, ScrollPolicy}; +use std::num::Float; +use std::num::FloatMath; use std::rc::Rc; pub struct CompositorData { @@ -117,6 +117,9 @@ pub trait CompositorLayer { fn scroll_layer_and_all_child_layers(&self, new_offset: TypedPoint2D<LayerPixel, f32>) -> bool; + + /// Return a flag describing how this layer deals with scroll events. + fn wants_scroll_events(&self) -> WantsScrollEventsFlag; } #[deriving(PartialEq, Clone)] @@ -260,8 +263,8 @@ impl CompositorLayer for Layer<CompositorData> { -> ScrollEventResult { // If this layer doesn't want scroll events, neither it nor its children can handle scroll // events. - if self.extra_data.borrow().wants_scroll_events != WantsScrollEvents { - return ScrollEventUnhandled; + if self.wants_scroll_events() != WantsScrollEventsFlag::WantsScrollEvents { + return ScrollEventResult::ScrollEventUnhandled; } //// Allow children to scroll. @@ -271,7 +274,7 @@ impl CompositorLayer for Layer<CompositorData> { let child_bounds = child.bounds.borrow(); if child_bounds.contains(&new_cursor) { let result = child.handle_scroll_event(delta, new_cursor - child_bounds.origin); - if result != ScrollEventUnhandled { + if result != ScrollEventResult::ScrollEventUnhandled { return result; } } @@ -292,7 +295,7 @@ impl CompositorLayer for Layer<CompositorData> { Length(new_offset.y.get().clamp(&min_y, &0.0))); if self.extra_data.borrow().scroll_offset == new_offset { - return ScrollPositionUnchanged; + return ScrollEventResult::ScrollPositionUnchanged; } // The scroll offset is just a record of the scroll position of this scrolling root, @@ -305,9 +308,9 @@ impl CompositorLayer for Layer<CompositorData> { } if result { - return ScrollPositionChanged; + return ScrollEventResult::ScrollPositionChanged; } else { - return ScrollPositionUnchanged; + return ScrollEventResult::ScrollPositionUnchanged; } } @@ -316,9 +319,12 @@ impl CompositorLayer for Layer<CompositorData> { cursor: TypedPoint2D<LayerPixel, f32>) { let event_point = cursor.to_untyped(); let message = match event { - MouseWindowClickEvent(button, _) => ClickEvent(button, event_point), - MouseWindowMouseDownEvent(button, _) => MouseDownEvent(button, event_point), - MouseWindowMouseUpEvent(button, _) => MouseUpEvent(button, event_point), + MouseWindowEvent::MouseWindowClickEvent(button, _) => + ClickEvent(button, event_point), + MouseWindowEvent::MouseWindowMouseDownEvent(button, _) => + MouseDownEvent(button, event_point), + MouseWindowEvent::MouseWindowMouseUpEvent(button, _) => + MouseUpEvent(button, event_point), }; let pipeline = &self.extra_data.borrow().pipeline; let ScriptControlChan(ref chan) = pipeline.script_chan; @@ -356,4 +362,8 @@ impl CompositorLayer for Layer<CompositorData> { return result; } + fn wants_scroll_events(&self) -> WantsScrollEventsFlag { + self.extra_data.borrow().wants_scroll_events + } + } diff --git a/components/compositing/compositor_task.rs b/components/compositing/compositor_task.rs index 733637b1b95..0fc99cc1884 100644 --- a/components/compositing/compositor_task.rs +++ b/components/compositing/compositor_task.rs @@ -62,7 +62,7 @@ impl CompositorReceiver for Receiver<Msg> { /// Implementation of the abstract `ScriptListener` interface. impl ScriptListener for Box<CompositorProxy+'static+Send> { fn set_ready_state(&mut self, pipeline_id: PipelineId, ready_state: ReadyState) { - let msg = ChangeReadyState(pipeline_id, ready_state); + let msg = Msg::ChangeReadyState(pipeline_id, ready_state); self.send(msg); } @@ -70,12 +70,12 @@ impl ScriptListener for Box<CompositorProxy+'static+Send> { pipeline_id: PipelineId, layer_id: LayerId, point: Point2D<f32>) { - self.send(ScrollFragmentPoint(pipeline_id, layer_id, point)); + self.send(Msg::ScrollFragmentPoint(pipeline_id, layer_id, point)); } fn close(&mut self) { let (chan, port) = channel(); - self.send(Exit(chan)); + self.send(Msg::Exit(chan)); port.recv(); } @@ -84,12 +84,12 @@ impl ScriptListener for Box<CompositorProxy+'static+Send> { } fn set_title(&mut self, pipeline_id: PipelineId, title: Option<String>) { - self.send(ChangePageTitle(pipeline_id, title)) + self.send(Msg::ChangePageTitle(pipeline_id, title)) } fn send_key_event(&mut self, key: Key, state: KeyState, modifiers: KeyModifiers) { if state == Pressed { - self.send(KeyEvent(key, modifiers)); + self.send(Msg::KeyEvent(key, modifiers)); } } } @@ -124,7 +124,7 @@ impl LayerProperties { impl PaintListener for Box<CompositorProxy+'static+Send> { fn get_graphics_metadata(&mut self) -> Option<NativeGraphicsMetadata> { let (chan, port) = channel(); - self.send(GetGraphicsMetadata(chan)); + self.send(Msg::GetGraphicsMetadata(chan)); port.recv() } @@ -132,7 +132,7 @@ impl PaintListener for Box<CompositorProxy+'static+Send> { pipeline_id: PipelineId, epoch: Epoch, replies: Vec<(LayerId, Box<LayerBufferSet>)>) { - self.send(Paint(pipeline_id, epoch, replies)); + self.send(Msg::Paint(pipeline_id, epoch, replies)); } fn initialize_layers_for_pipeline(&mut self, @@ -146,20 +146,20 @@ impl PaintListener for Box<CompositorProxy+'static+Send> { for metadata in metadata.iter() { let layer_properties = LayerProperties::new(pipeline_id, epoch, metadata); if first { - self.send(CreateOrUpdateRootLayer(layer_properties)); + self.send(Msg::CreateOrUpdateRootLayer(layer_properties)); first = false } else { - self.send(CreateOrUpdateDescendantLayer(layer_properties)); + self.send(Msg::CreateOrUpdateDescendantLayer(layer_properties)); } } } fn paint_msg_discarded(&mut self) { - self.send(PaintMsgDiscarded); + self.send(Msg::PaintMsgDiscarded); } fn set_paint_state(&mut self, pipeline_id: PipelineId, paint_state: PaintState) { - self.send(ChangePaintState(pipeline_id, paint_state)) + self.send(Msg::ChangePaintState(pipeline_id, paint_state)) } } @@ -205,7 +205,7 @@ pub enum Msg { /// Sets the channel to the current layout and paint tasks, along with their ID. SetIds(SendableFrameTree, Sender<()>, ConstellationChan), /// Sends an updated version of the frame tree. - FrameTreeUpdateMsg(FrameTreeDiff, Sender<()>), + FrameTreeUpdate(FrameTreeDiff, Sender<()>), /// The load of a page has completed. LoadComplete, /// Indicates that the scrolling timeout with the given starting timestamp has happened and a @@ -218,24 +218,24 @@ pub enum Msg { impl Show for Msg { fn fmt(&self, f: &mut Formatter) -> Result<(),FormatError> { match *self { - Exit(..) => write!(f, "Exit"), - ShutdownComplete(..) => write!(f, "ShutdownComplete"), - GetGraphicsMetadata(..) => write!(f, "GetGraphicsMetadata"), - CreateOrUpdateRootLayer(..) => write!(f, "CreateOrUpdateRootLayer"), - CreateOrUpdateDescendantLayer(..) => write!(f, "CreateOrUpdateDescendantLayer"), - SetLayerOrigin(..) => write!(f, "SetLayerOrigin"), - ScrollFragmentPoint(..) => write!(f, "ScrollFragmentPoint"), - Paint(..) => write!(f, "Paint"), - ChangeReadyState(..) => write!(f, "ChangeReadyState"), - ChangePaintState(..) => write!(f, "ChangePaintState"), - ChangePageTitle(..) => write!(f, "ChangePageTitle"), - ChangePageLoadData(..) => write!(f, "ChangePageLoadData"), - PaintMsgDiscarded(..) => write!(f, "PaintMsgDiscarded"), - SetIds(..) => write!(f, "SetIds"), - FrameTreeUpdateMsg(..) => write!(f, "FrameTreeUpdateMsg"), - LoadComplete => write!(f, "LoadComplete"), - ScrollTimeout(..) => write!(f, "ScrollTimeout"), - KeyEvent(..) => write!(f, "KeyEvent"), + Msg::Exit(..) => write!(f, "Exit"), + Msg::ShutdownComplete(..) => write!(f, "ShutdownComplete"), + Msg::GetGraphicsMetadata(..) => write!(f, "GetGraphicsMetadata"), + Msg::CreateOrUpdateRootLayer(..) => write!(f, "CreateOrUpdateRootLayer"), + Msg::CreateOrUpdateDescendantLayer(..) => write!(f, "CreateOrUpdateDescendantLayer"), + Msg::SetLayerOrigin(..) => write!(f, "SetLayerOrigin"), + Msg::ScrollFragmentPoint(..) => write!(f, "ScrollFragmentPoint"), + Msg::Paint(..) => write!(f, "Paint"), + Msg::ChangeReadyState(..) => write!(f, "ChangeReadyState"), + Msg::ChangePaintState(..) => write!(f, "ChangePaintState"), + Msg::ChangePageTitle(..) => write!(f, "ChangePageTitle"), + Msg::ChangePageLoadData(..) => write!(f, "ChangePageLoadData"), + Msg::PaintMsgDiscarded(..) => write!(f, "PaintMsgDiscarded"), + Msg::SetIds(..) => write!(f, "SetIds"), + Msg::FrameTreeUpdate(..) => write!(f, "FrameTreeUpdateMsg"), + Msg::LoadComplete => write!(f, "LoadComplete"), + Msg::ScrollTimeout(..) => write!(f, "ScrollTimeout"), + Msg::KeyEvent(..) => write!(f, "KeyEvent"), } } } diff --git a/components/compositing/constellation.rs b/components/compositing/constellation.rs index 44f26e97565..fe756a5c7b9 100644 --- a/components/compositing/constellation.rs +++ b/components/compositing/constellation.rs @@ -4,8 +4,8 @@ use pipeline::{Pipeline, CompositionPipeline}; -use compositor_task::{ChangePageLoadData, ChangePageTitle, CompositorProxy, FrameTreeUpdateMsg}; -use compositor_task::{LoadComplete, SetLayerOrigin, SetIds, ShutdownComplete}; +use compositor_task::CompositorProxy; +use compositor_task::Msg as CompositorMsg; use devtools_traits; use devtools_traits::DevtoolsControlChan; use geom::rect::{Rect, TypedRect}; @@ -22,9 +22,10 @@ use servo_msg::constellation_msg::{ConstellationChan, ExitMsg, FailureMsg, Failu use servo_msg::constellation_msg::{GetPipelineTitleMsg}; use servo_msg::constellation_msg::{IFrameSandboxState, IFrameUnsandboxed, InitLoadUrlMsg}; use servo_msg::constellation_msg::{KeyEvent, Key, KeyState, KeyModifiers, LoadCompleteMsg}; -use servo_msg::constellation_msg::{LoadData, LoadUrlMsg, Msg, NavigateMsg, NavigationType}; +use servo_msg::constellation_msg::{LoadData, LoadUrlMsg, NavigateMsg, NavigationType}; use servo_msg::constellation_msg::{PainterReadyMsg, PipelineId, ResizedWindowMsg}; use servo_msg::constellation_msg::{ScriptLoadedURLInIFrameMsg, SubpageId, WindowSizeData}; +use servo_msg::constellation_msg::Msg as ConstellationMsg; use servo_msg::constellation_msg; use servo_net::image_cache_task::{ImageCacheTask, ImageCacheTaskClient}; use servo_net::resource_task::ResourceTask; @@ -48,7 +49,7 @@ pub struct Constellation<LTF, STF> { pub chan: ConstellationChan, /// Receives messages. - pub request_port: Receiver<Msg>, + pub request_port: Receiver<ConstellationMsg>, /// A channel (the implementation of which is port-specific) through which messages can be sent /// to the compositor. @@ -203,12 +204,12 @@ impl FrameTreeTraversal for Rc<FrameTree> { match child { Some(child) => { *new_child.parent.borrow_mut() = child.frame_tree.parent.borrow().clone(); - return ReplacedNode(replace(&mut child.frame_tree, new_child)); + return ReplaceResult::ReplacedNode(replace(&mut child.frame_tree, new_child)); } None => (), } } - OriginalNode(new_child) + ReplaceResult::OriginalNode(new_child) } fn iter(&self) -> FrameTreeIterator { @@ -333,8 +334,9 @@ impl NavigationContext { /// compositor of the new URLs. fn set_current(&mut self, new_frame: Rc<FrameTree>, compositor_proxy: &mut CompositorProxy) { self.current = Some(new_frame.clone()); - compositor_proxy.send(ChangePageLoadData(new_frame.id, - new_frame.pipeline.load_data.clone())); + compositor_proxy.send(CompositorMsg::ChangePageLoadData( + new_frame.id, + new_frame.pipeline.load_data.clone())); } } @@ -442,7 +444,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { } /// Handles loading pages, navigation, and granting access to the compositor - fn handle_request(&mut self, request: Msg) -> bool { + fn handle_request(&mut self, request: ConstellationMsg) -> bool { match request { ExitMsg => { debug!("constellation exiting"); @@ -481,7 +483,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { // script, and reflow messages have been sent. LoadCompleteMsg => { debug!("constellation got load complete message"); - self.compositor_proxy.send(LoadComplete); + self.compositor_proxy.send(CompositorMsg::LoadComplete); } // Handle a forward or back request NavigateMsg(direction) => { @@ -520,7 +522,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { }); self.storage_task.send(storage_task::Exit); self.font_cache_task.exit(); - self.compositor_proxy.send(ShutdownComplete); + self.compositor_proxy.send(CompositorMsg::ShutdownComplete); } fn handle_failure_msg(&mut self, pipeline_id: PipelineId, subpage_id: Option<SubpageId>) { @@ -681,9 +683,10 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { initial_viewport: rect.size * ScaleFactor(1.0), device_pixel_ratio: device_pixel_ratio, })); - compositor_proxy.send(SetLayerOrigin(pipeline.id, - LayerId::null(), - rect.to_untyped().origin)); + compositor_proxy.send(CompositorMsg::SetLayerOrigin( + pipeline.id, + LayerId::null(), + rect.to_untyped().origin)); } else { already_sent.insert(pipeline.id); } @@ -843,7 +846,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { fn handle_get_pipeline_title_msg(&mut self, pipeline_id: PipelineId) { match self.pipelines.get(&pipeline_id) { - None => self.compositor_proxy.send(ChangePageTitle(pipeline_id, None)), + None => self.compositor_proxy.send(CompositorMsg::ChangePageTitle(pipeline_id, None)), Some(pipeline) => { let ScriptControlChan(ref script_channel) = pipeline.script_chan; script_channel.send(GetTitleMsg(pipeline_id)); @@ -1018,7 +1021,9 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { fn set_ids(&mut self, frame_tree: &Rc<FrameTree>) { let (chan, port) = channel(); debug!("Constellation sending SetIds"); - self.compositor_proxy.send(SetIds(frame_tree.to_sendable(), chan, self.chan.clone())); + self.compositor_proxy.send(CompositorMsg::SetIds(frame_tree.to_sendable(), + chan, + self.chan.clone())); match port.recv_opt() { Ok(()) => { let mut iter = frame_tree.iter(); @@ -1075,7 +1080,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { }; let (chan, port) = channel(); - self.compositor_proxy.send(FrameTreeUpdateMsg(sendable_frame_tree_diff, chan)); + self.compositor_proxy.send(CompositorMsg::FrameTreeUpdate(sendable_frame_tree_diff, chan)); match port.recv_opt() { Ok(()) => { child.frame_tree.has_compositor_layer.set(true); diff --git a/components/compositing/headless.rs b/components/compositing/headless.rs index c9cf6a25132..4a9ed6d5c56 100644 --- a/components/compositing/headless.rs +++ b/components/compositing/headless.rs @@ -2,11 +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 compositor_task::{GetGraphicsMetadata, CreateOrUpdateRootLayer, CreateOrUpdateDescendantLayer}; -use compositor_task::{Exit, ChangeReadyState, LoadComplete, Paint, ScrollFragmentPoint, SetIds}; -use compositor_task::{SetLayerOrigin, ShutdownComplete, ChangePaintState, PaintMsgDiscarded}; -use compositor_task::{CompositorEventListener, CompositorReceiver, ScrollTimeout, ChangePageTitle}; -use compositor_task::{ChangePageLoadData, FrameTreeUpdateMsg, KeyEvent}; +use compositor_task::{CompositorEventListener, CompositorReceiver, Msg}; use windowing::WindowEvent; use geom::scale_factor::ScaleFactor; @@ -73,27 +69,27 @@ impl NullCompositor { impl CompositorEventListener for NullCompositor { fn handle_event(&mut self, _: WindowEvent) -> bool { match self.port.recv_compositor_msg() { - Exit(chan) => { + Msg::Exit(chan) => { debug!("shutting down the constellation"); let ConstellationChan(ref con_chan) = self.constellation_chan; con_chan.send(ExitMsg); chan.send(()); } - ShutdownComplete => { + Msg::ShutdownComplete => { debug!("constellation completed shutdown"); return false } - GetGraphicsMetadata(chan) => { + Msg::GetGraphicsMetadata(chan) => { chan.send(None); } - SetIds(_, response_chan, _) => { + Msg::SetIds(_, response_chan, _) => { response_chan.send(()); } - FrameTreeUpdateMsg(_, response_channel) => { + Msg::FrameTreeUpdate(_, response_channel) => { response_channel.send(()); } @@ -101,12 +97,12 @@ impl CompositorEventListener for NullCompositor { // we'll notice and think about whether it needs a response, like // SetIds. - CreateOrUpdateRootLayer(..) | - CreateOrUpdateDescendantLayer(..) | - SetLayerOrigin(..) | Paint(..) | - ChangeReadyState(..) | ChangePaintState(..) | ScrollFragmentPoint(..) | - LoadComplete | PaintMsgDiscarded(..) | ScrollTimeout(..) | ChangePageTitle(..) | - ChangePageLoadData(..) | KeyEvent(..) => () + Msg::CreateOrUpdateRootLayer(..) | + Msg::CreateOrUpdateDescendantLayer(..) | + Msg::SetLayerOrigin(..) | Msg::Paint(..) | + Msg::ChangeReadyState(..) | Msg::ChangePaintState(..) | Msg::ScrollFragmentPoint(..) | + Msg::LoadComplete | Msg::PaintMsgDiscarded(..) | Msg::ScrollTimeout(..) | Msg::ChangePageTitle(..) | + Msg::ChangePageLoadData(..) | Msg::KeyEvent(..) => () } true } @@ -118,8 +114,8 @@ impl CompositorEventListener for NullCompositor { // another task from finishing (i.e. SetIds) while self.port.try_recv_compositor_msg().is_some() {} - self.time_profiler_chan.send(time::ExitMsg); - self.memory_profiler_chan.send(memory::ExitMsg); + self.time_profiler_chan.send(time::TimeProfilerMsg::Exit); + self.memory_profiler_chan.send(memory::MemoryProfilerMsg::Exit); } fn pinch_zoom_level(&self) -> f32 { diff --git a/components/compositing/scrolling.rs b/components/compositing/scrolling.rs index d3dfb6a8fdb..d36674b69e9 100644 --- a/components/compositing/scrolling.rs +++ b/components/compositing/scrolling.rs @@ -4,7 +4,7 @@ //! A timer thread that gives the painting task a little time to catch up when the user scrolls. -use compositor_task::{CompositorProxy, ScrollTimeout}; +use compositor_task::{CompositorProxy, Msg}; use native::task::NativeTaskBuilder; use std::io::timer; @@ -47,11 +47,11 @@ impl ScrollingTimerProxy { } pub fn scroll_event_processed(&mut self, timestamp: u64) { - self.sender.send(ScrollEventProcessedMsg(timestamp)) + self.sender.send(ToScrollingTimerMsg::ScrollEventProcessedMsg(timestamp)) } pub fn shutdown(&mut self) { - self.sender.send(ExitMsg); + self.sender.send(ToScrollingTimerMsg::ExitMsg); } } @@ -59,13 +59,13 @@ impl ScrollingTimer { pub fn run(&mut self) { loop { match self.receiver.recv_opt() { - Ok(ScrollEventProcessedMsg(timestamp)) => { + Ok(ToScrollingTimerMsg::ScrollEventProcessedMsg(timestamp)) => { let target = timestamp as i64 + TIMEOUT; let delta = target - (time::precise_time_ns() as i64); timer::sleep(Duration::nanoseconds(delta)); - self.compositor_proxy.send(ScrollTimeout(timestamp)); + self.compositor_proxy.send(Msg::ScrollTimeout(timestamp)); } - Ok(ExitMsg) | Err(_) => break, + Ok(ToScrollingTimerMsg::ExitMsg) | Err(_) => break, } } } diff --git a/components/compositing/windowing.rs b/components/compositing/windowing.rs index fdfc93c559e..e33a5f9fe75 100644 --- a/components/compositing/windowing.rs +++ b/components/compositing/windowing.rs @@ -36,32 +36,32 @@ pub enum WindowEvent { /// FIXME(pcwalton): This is kind of ugly and may not work well with multiprocess Servo. /// It's possible that this should be something like /// `CompositorMessageWindowEvent(compositor_task::Msg)` instead. - IdleWindowEvent, + Idle, /// Sent when part of the window is marked dirty and needs to be redrawn. Before sending this /// message, the window must make the same GL context as in `PrepareRenderingEvent` current. - RefreshWindowEvent, + Refresh, /// Sent to initialize the GL context. The windowing system must have a valid, current GL /// context when this message is sent. - InitializeCompositingWindowEvent, + InitializeCompositing, /// Sent when the window is resized. - ResizeWindowEvent(TypedSize2D<DevicePixel, uint>), + Resize(TypedSize2D<DevicePixel, uint>), /// Sent when a new URL is to be loaded. - LoadUrlWindowEvent(String), + LoadUrl(String), /// Sent when a mouse hit test is to be performed. MouseWindowEventClass(MouseWindowEvent), /// Sent when a mouse move. MouseWindowMoveEventClass(TypedPoint2D<DevicePixel, f32>), /// Sent when the user scrolls. The first point is the delta and the second point is the /// origin. - ScrollWindowEvent(TypedPoint2D<DevicePixel, f32>, TypedPoint2D<DevicePixel, i32>), + Scroll(TypedPoint2D<DevicePixel, f32>, TypedPoint2D<DevicePixel, i32>), /// Sent when the user zooms. - ZoomWindowEvent(f32), + Zoom(f32), /// Simulated "pinch zoom" gesture for non-touch platforms (e.g. ctrl-scrollwheel). - PinchZoomWindowEvent(f32), + PinchZoom(f32), /// Sent when the user uses chrome navigation (i.e. backspace or shift-backspace). - NavigationWindowEvent(WindowNavigateMsg), + Navigation(WindowNavigateMsg), /// Sent when the user quits the application - QuitWindowEvent, + Quit, /// Sent when a key input state changes KeyEvent(Key, KeyState, KeyModifiers), } @@ -69,19 +69,19 @@ pub enum WindowEvent { impl Show for WindowEvent { fn fmt(&self, f: &mut Formatter) -> Result<(),FormatError> { match *self { - IdleWindowEvent => write!(f, "Idle"), - RefreshWindowEvent => write!(f, "Refresh"), - InitializeCompositingWindowEvent => write!(f, "InitializeCompositing"), - ResizeWindowEvent(..) => write!(f, "Resize"), - KeyEvent(..) => write!(f, "Key"), - LoadUrlWindowEvent(..) => write!(f, "LoadUrl"), - MouseWindowEventClass(..) => write!(f, "Mouse"), - MouseWindowMoveEventClass(..) => write!(f, "MouseMove"), - ScrollWindowEvent(..) => write!(f, "Scroll"), - ZoomWindowEvent(..) => write!(f, "Zoom"), - PinchZoomWindowEvent(..) => write!(f, "PinchZoom"), - NavigationWindowEvent(..) => write!(f, "Navigation"), - QuitWindowEvent => write!(f, "Quit"), + WindowEvent::Idle => write!(f, "Idle"), + WindowEvent::Refresh => write!(f, "Refresh"), + WindowEvent::InitializeCompositing => write!(f, "InitializeCompositing"), + WindowEvent::Resize(..) => write!(f, "Resize"), + WindowEvent::KeyEvent(..) => write!(f, "Key"), + WindowEvent::LoadUrl(..) => write!(f, "LoadUrl"), + WindowEvent::MouseWindowEventClass(..) => write!(f, "Mouse"), + WindowEvent::MouseWindowMoveEventClass(..) => write!(f, "MouseMove"), + WindowEvent::Scroll(..) => write!(f, "Scroll"), + WindowEvent::Zoom(..) => write!(f, "Zoom"), + WindowEvent::PinchZoom(..) => write!(f, "PinchZoom"), + WindowEvent::Navigation(..) => write!(f, "Navigation"), + WindowEvent::Quit => write!(f, "Quit"), } } } diff --git a/components/devtools/actors/console.rs b/components/devtools/actors/console.rs index 545fbb34e78..3e0c934bddb 100644 --- a/components/devtools/actors/console.rs +++ b/components/devtools/actors/console.rs @@ -18,6 +18,7 @@ use core::cell::RefCell; use serialize::json; use serialize::json::ToJson; use std::io::TcpStream; +use std::num::Float; #[deriving(Encodable)] struct StartedListenersTraits { diff --git a/components/devtools/actors/inspector.rs b/components/devtools/actors/inspector.rs index 471e379e693..f35ae3d9f40 100644 --- a/components/devtools/actors/inspector.rs +++ b/components/devtools/actors/inspector.rs @@ -16,6 +16,7 @@ use serialize::json; use serialize::json::ToJson; use std::cell::RefCell; use std::io::TcpStream; +use std::num::Float; pub struct InspectorActor { pub name: String, diff --git a/components/gfx/Cargo.toml b/components/gfx/Cargo.toml index 0c0f84ec105..dbdd1246897 100644 --- a/components/gfx/Cargo.toml +++ b/components/gfx/Cargo.toml @@ -62,3 +62,5 @@ git = "https://github.com/servo/rust-core-text" [dependencies.script_traits] path = "../script_traits" +[dependencies.time] +git = "https://github.com/rust-lang/time" diff --git a/components/gfx/display_list/mod.rs b/components/gfx/display_list/mod.rs index df998d42da6..b0cb1e609a6 100644 --- a/components/gfx/display_list/mod.rs +++ b/components/gfx/display_list/mod.rs @@ -14,6 +14,9 @@ //! They are therefore not exactly analogous to constructs like Skia pictures, which consist of //! low-level drawing primitives. +use self::DisplayItem::*; +use self::DisplayItemIterator::*; + use color::Color; use display_list::optimizer::DisplayListOptimizer; use paint_context::{PaintContext, ToAzureRect}; diff --git a/components/gfx/font_cache_task.rs b/components/gfx/font_cache_task.rs index 3af5bd0d8d4..ec724c87f26 100644 --- a/components/gfx/font_cache_task.rs +++ b/components/gfx/font_cache_task.rs @@ -2,6 +2,9 @@ * 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 self::Command::*; +use self::Reply::*; + use platform::font_list::get_available_families; use platform::font_list::get_system_default_family; use platform::font_list::get_variations_for_family; @@ -16,7 +19,7 @@ use platform::font_template::FontTemplateData; use servo_net::resource_task::{ResourceTask, load_whole_resource}; use servo_util::task::spawn_named; use servo_util::str::LowercaseString; -use style::{Source, LocalSource, UrlSource_}; +use style::Source; /// A list of font templates that make up a given font family. struct FontFamily { @@ -128,7 +131,7 @@ impl FontCache { } match src { - UrlSource_(ref url_source) => { + Source::Url(ref url_source) => { let url = &url_source.url; let maybe_resource = load_whole_resource(&self.resource_task, url.clone()); match maybe_resource { @@ -141,7 +144,7 @@ impl FontCache { } } } - LocalSource(ref local_family_name) => { + Source::Local(ref local_family_name) => { let family = &mut self.web_families[family_name]; get_variations_for_family(local_family_name.as_slice(), |path| { family.add_template(path.as_slice(), None); diff --git a/components/gfx/paint_context.rs b/components/gfx/paint_context.rs index f34b62559f8..81cbd806fbc 100644 --- a/components/gfx/paint_context.rs +++ b/components/gfx/paint_context.rs @@ -13,8 +13,8 @@ use azure::azure_hl::{StrokeOptions}; use azure::scaled_font::ScaledFont; use azure::{AZ_CAP_BUTT, AzFloat, struct__AzDrawOptions, struct__AzGlyph}; use azure::{struct__AzGlyphBuffer, struct__AzPoint, AzDrawTargetFillGlyphs}; -use display_list::{BOX_SHADOW_INFLATION_FACTOR, BorderRadii, SidewaysLeft, SidewaysRight}; -use display_list::{TextDisplayItem, Upright}; +use display_list::{BOX_SHADOW_INFLATION_FACTOR, TextDisplayItem, BorderRadii}; +use display_list::TextOrientation::{SidewaysLeft, SidewaysRight, Upright}; use font_context::FontContext; use geom::matrix2d::Matrix2D; use geom::point::Point2D; @@ -86,10 +86,10 @@ impl<'a> PaintContext<'a> { self.draw_target.make_current(); - self.draw_border_segment(Top, bounds, border, &radius, color, style); - self.draw_border_segment(Right, bounds, border, &radius, color, style); - self.draw_border_segment(Bottom, bounds, border, &radius, color, style); - self.draw_border_segment(Left, bounds, border, &radius, color, style); + self.draw_border_segment(Direction::Top, bounds, border, &radius, color, style); + self.draw_border_segment(Direction::Right, bounds, border, &radius, color, style); + self.draw_border_segment(Direction::Bottom, bounds, border, &radius, color, style); + self.draw_border_segment(Direction::Left, bounds, border, &radius, color, style); } pub fn draw_line(&self, @@ -171,10 +171,10 @@ impl<'a> PaintContext<'a> { color: SideOffsets2D<Color>, style: SideOffsets2D<border_style::T>) { let (style_select, color_select) = match direction { - Top => (style.top, color.top), - Left => (style.left, color.left), - Right => (style.right, color.right), - Bottom => (style.bottom, color.bottom) + Direction::Top => (style.top, color.top), + Direction::Left => (style.left, color.left), + Direction::Right => (style.right, color.right), + Direction::Bottom => (style.bottom, color.bottom) }; match style_select{ @@ -184,10 +184,10 @@ impl<'a> PaintContext<'a> { } //FIXME(sammykim): This doesn't work with dash_pattern and cap_style well. I referred firefox code. border_style::dotted => { - self.draw_dashed_border_segment(direction, bounds, border, color_select, DottedBorder); + self.draw_dashed_border_segment(direction, bounds, border, color_select, DashSize::DottedBorder); } border_style::dashed => { - self.draw_dashed_border_segment(direction, bounds, border, color_select, DashedBorder); + self.draw_dashed_border_segment(direction, bounds, border, color_select, DashSize::DashedBorder); } border_style::solid => { self.draw_solid_border_segment(direction,bounds,border,radius,color_select); @@ -210,22 +210,22 @@ impl<'a> PaintContext<'a> { match style { border_style::none | border_style::hidden => {} border_style::dotted => { - self.draw_dashed_border_segment(Right, bounds, border, color, DottedBorder); + self.draw_dashed_border_segment(Direction::Right, bounds, border, color, DashSize::DottedBorder); } border_style::dashed => { - self.draw_dashed_border_segment(Right, bounds, border, color, DashedBorder); + self.draw_dashed_border_segment(Direction::Right, bounds, border, color, DashSize::DashedBorder); } border_style::solid => { - self.draw_solid_border_segment(Right, bounds, border, radius, color); + self.draw_solid_border_segment(Direction::Right, bounds, border, radius, color); } border_style::double => { - self.draw_double_border_segment(Right, bounds, border, radius, color); + self.draw_double_border_segment(Direction::Right, bounds, border, radius, color); } border_style::groove | border_style::ridge => { - self.draw_groove_ridge_border_segment(Right, bounds, border, radius, color, style); + self.draw_groove_ridge_border_segment(Direction::Right, bounds, border, radius, color, style); } border_style::inset | border_style::outset => { - self.draw_inset_outset_border_segment(Right, bounds, border, radius, color, style); + self.draw_inset_outset_border_segment(Direction::Right, bounds, border, radius, color, style); } } } @@ -354,7 +354,7 @@ impl<'a> PaintContext<'a> { } match direction { - Top => { + 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); @@ -387,7 +387,7 @@ impl<'a> PaintContext<'a> { path_builder.arc(origin, radius.top_left, rad_TL, rad_T, false); } } - Left => { + 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); @@ -418,7 +418,7 @@ impl<'a> PaintContext<'a> { path_builder.arc(origin, radius.bottom_left, rad_BL, rad_L, false); } } - Right => { + 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); @@ -449,7 +449,7 @@ impl<'a> PaintContext<'a> { path_builder.arc(origin, distance_to_elbow, rad_BR, rad_R, true); } } - Bottom => { + 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); @@ -500,10 +500,10 @@ impl<'a> PaintContext<'a> { stroke_opts.set_cap_style(AZ_CAP_BUTT as u8); let border_width = match direction { - Top => border.top, - Left => border.left, - Right => border.right, - Bottom => border.bottom + Direction::Top => border.top, + Direction::Left => border.left, + Direction::Right => border.right, + Direction::Bottom => border.bottom }; stroke_opts.line_width = border_width; @@ -513,25 +513,25 @@ impl<'a> PaintContext<'a> { stroke_opts.mDashLength = dash.len() as size_t; let (start, end) = match direction { - Top => { + Direction::Top => { let y = rect.origin.y + border.top * 0.5; let start = Point2D(rect.origin.x, y); let end = Point2D(rect.origin.x + rect.size.width, y); (start, end) } - Left => { + Direction::Left => { let x = rect.origin.x + border.left * 0.5; let start = Point2D(x, rect.origin.y + rect.size.height); let end = Point2D(x, rect.origin.y + border.top); (start, end) } - Right => { + Direction::Right => { let x = rect.origin.x + rect.size.width - border.right * 0.5; let start = Point2D(x, rect.origin.y); let end = Point2D(x, rect.origin.y + rect.size.height); (start, end) } - Bottom => { + Direction::Bottom => { let y = rect.origin.y + rect.size.height - border.bottom * 0.5; let start = Point2D(rect.origin.x + rect.size.width, y); let end = Point2D(rect.origin.x + border.left, y); @@ -617,8 +617,10 @@ impl<'a> PaintContext<'a> { } let (outer_color, inner_color) = match (direction, is_groove) { - (Top, true) | (Left, true) | (Right, false) | (Bottom, false) => (darker_color, lighter_color), - (Top, false) | (Left, false) | (Right, true) | (Bottom, true) => (lighter_color, darker_color) + (Direction::Top, true) | (Direction::Left, true) | + (Direction::Right, false) | (Direction::Bottom, false) => (darker_color, lighter_color), + (Direction::Top, false) | (Direction::Left, false) | + (Direction::Right, true) | (Direction::Bottom, true) => (lighter_color, darker_color) }; // outer portion of the border self.draw_border_path(&original_bounds, direction, scaled_border, radius, outer_color); @@ -642,8 +644,8 @@ impl<'a> PaintContext<'a> { let original_bounds = self.get_scaled_bounds(bounds, border, 0.0); // select and scale the color appropriately. let scaled_color = match direction { - Top | Left => self.scale_color(color, if is_inset { 2.0/3.0 } else { 1.0 }), - Right | Bottom => self.scale_color(color, if is_inset { 1.0 } else { 2.0/3.0 }) + Direction::Top | Direction::Left => self.scale_color(color, if is_inset { 2.0/3.0 } else { 1.0 }), + Direction::Right | Direction::Bottom => self.scale_color(color, if is_inset { 1.0 } else { 2.0/3.0 }) }; self.draw_border_path(&original_bounds, direction, border, radius, scaled_color); } diff --git a/components/gfx/paint_task.rs b/components/gfx/paint_task.rs index 2f1dad3b436..d6a6010701b 100644 --- a/components/gfx/paint_task.rs +++ b/components/gfx/paint_task.rs @@ -4,6 +4,10 @@ //! The task that handles all painting. +use self::Msg::*; +use self::MsgFromWorkerThread::*; +use self::MsgToWorkerThread::*; + use buffer_map::BufferMap; use display_list::{mod, StackingContext}; use font_cache_task::FontCacheTask; diff --git a/components/gfx/platform/freetype/font.rs b/components/gfx/platform/freetype/font.rs index 90179b377a3..5896a335585 100644 --- a/components/gfx/platform/freetype/font.rs +++ b/components/gfx/platform/freetype/font.rs @@ -26,6 +26,7 @@ use freetype::freetype::{ft_sfnt_os2}; use freetype::tt_os2::TT_OS2; use std::mem; +use std::num::Float; use std::ptr; use std::string; diff --git a/components/gfx/platform/macos/font.rs b/components/gfx/platform/macos/font.rs index 529bdcf615d..d73a22d7d41 100644 --- a/components/gfx/platform/macos/font.rs +++ b/components/gfx/platform/macos/font.rs @@ -27,6 +27,7 @@ use core_text::font::CTFont; use core_text::font_descriptor::{SymbolicTraitAccessors, TraitAccessors}; use core_text::font_descriptor::{kCTFontDefaultOrientation}; +use std::num::Float; use std::ptr; use sync::Arc; diff --git a/components/gfx/text/glyph.rs b/components/gfx/text/glyph.rs index c1d601b8120..4f9407f8bbf 100644 --- a/components/gfx/text/glyph.rs +++ b/components/gfx/text/glyph.rs @@ -2,6 +2,9 @@ * 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 self::BreakType::*; +use self::GlyphInfo::*; + use servo_util::vec::*; use servo_util::range; use servo_util::range::{Range, RangeIndex, IntRangeIndex, EachIndex}; diff --git a/components/gfx/text/util.rs b/components/gfx/text/util.rs index 05b257688fb..63d73c76dab 100644 --- a/components/gfx/text/util.rs +++ b/components/gfx/text/util.rs @@ -2,6 +2,8 @@ * 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 self::CompressionMode::*; + use text::glyph::CharIndex; #[deriving(PartialEq)] diff --git a/components/layout/block.rs b/components/layout/block.rs index 079a1961073..6ff01eaf684 100644 --- a/components/layout/block.rs +++ b/components/layout/block.rs @@ -31,9 +31,9 @@ use construct::FlowConstructor; use context::LayoutContext; use css::node_style::StyledNode; use display_list_builder::{BlockFlowDisplayListBuilding, FragmentDisplayListBuilding}; -use floats::{ClearBoth, ClearLeft, ClearRight, FloatKind, FloatLeft, Floats, PlacementInfo}; -use flow::{AbsolutePositionInfo, BaseFlow, BlockFlowClass, FloatIfNecessary, FlowClass, Flow}; -use flow::{ForceNonfloated, ImmutableFlowUtils, MutableFlowUtils, PreorderFlowTraversal}; +use floats::{ClearType, FloatKind, Floats, PlacementInfo}; +use flow::{AbsolutePositionInfo, BaseFlow, ForceNonfloatedFlag, FlowClass, Flow}; +use flow::{ImmutableFlowUtils, MutableFlowUtils, PreorderFlowTraversal}; use flow::{PostorderFlowTraversal, mut_base}; use flow::{HAS_LEFT_FLOATED_DESCENDANTS, HAS_RIGHT_FLOATED_DESCENDANTS}; use flow::{IMPACTED_BY_LEFT_FLOATS, IMPACTED_BY_RIGHT_FLOATS}; @@ -41,12 +41,11 @@ use flow::{LAYERS_NEEDED_FOR_DESCENDANTS, NEEDS_LAYER}; use flow::{IS_ABSOLUTELY_POSITIONED}; use flow::{CLEARS_LEFT, CLEARS_RIGHT}; use flow; -use fragment::{Fragment, ImageFragment, InlineBlockFragment, FragmentBoundsIterator}; -use fragment::ScannedTextFragment; +use fragment::{Fragment, FragmentBoundsIterator, SpecificFragmentInfo}; use incremental::{REFLOW, REFLOW_OUT_OF_FLOW}; use layout_debug; -use model::{Auto, IntrinsicISizes, MarginCollapseInfo, MarginsCollapse, MarginsCollapseThrough}; -use model::{MaybeAuto, NoCollapsibleMargins, Specified, specified, specified_or_none}; +use model::{IntrinsicISizes, MarginCollapseInfo}; +use model::{MaybeAuto, CollapsibleMargins, specified, specified_or_none}; use table::ColumnComputedInlineSize; use wrapper::ThreadSafeLayoutNode; @@ -60,8 +59,8 @@ use servo_util::opts; use std::cmp::{max, min}; use std::fmt; use style::ComputedValues; -use style::computed_values::{LPA_Auto, LPA_Length, LPA_Percentage, LPN_Length, LPN_None}; -use style::computed_values::{LPN_Percentage, LP_Length, LP_Percentage, box_sizing, display, float}; +use style::computed_values::{LengthOrPercentageOrAuto, LengthOrPercentageOrNone}; +use style::computed_values::{LengthOrPercentage, box_sizing, display, float}; use style::computed_values::{overflow, position}; use sync::Arc; @@ -138,7 +137,7 @@ impl BSizeConstraintSolution { let static_position_block_start = static_b_offset; let (block_start, block_end, block_size, margin_block_start, margin_block_end) = match (block_start, block_end, block_size) { - (Auto, Auto, Auto) => { + (MaybeAuto::Auto, MaybeAuto::Auto, MaybeAuto::Auto) => { let margin_block_start = block_start_margin.specified_or_zero(); let margin_block_end = block_end_margin.specified_or_zero(); let block_start = static_position_block_start; @@ -149,23 +148,23 @@ impl BSizeConstraintSolution { let sum = block_start + block_size + margin_block_start + margin_block_end; (block_start, available_block_size - sum, block_size, margin_block_start, margin_block_end) } - (Specified(block_start), Specified(block_end), Specified(block_size)) => { + (MaybeAuto::Specified(block_start), MaybeAuto::Specified(block_end), MaybeAuto::Specified(block_size)) => { match (block_start_margin, block_end_margin) { - (Auto, Auto) => { + (MaybeAuto::Auto, MaybeAuto::Auto) => { let total_margin_val = available_block_size - block_start - block_end - block_size; (block_start, block_end, block_size, total_margin_val.scale_by(0.5), total_margin_val.scale_by(0.5)) } - (Specified(margin_block_start), Auto) => { + (MaybeAuto::Specified(margin_block_start), MaybeAuto::Auto) => { let sum = block_start + block_end + block_size + margin_block_start; (block_start, block_end, block_size, margin_block_start, available_block_size - sum) } - (Auto, Specified(margin_block_end)) => { + (MaybeAuto::Auto, MaybeAuto::Specified(margin_block_end)) => { let sum = block_start + block_end + block_size + margin_block_end; (block_start, block_end, block_size, available_block_size - sum, margin_block_end) } - (Specified(margin_block_start), Specified(margin_block_end)) => { + (MaybeAuto::Specified(margin_block_start), MaybeAuto::Specified(margin_block_end)) => { // Values are over-constrained. Ignore value for 'block-end'. let sum = block_start + block_size + margin_block_start + margin_block_end; (block_start, available_block_size - sum, block_size, margin_block_start, margin_block_end) @@ -176,19 +175,19 @@ impl BSizeConstraintSolution { // For the rest of the cases, auto values for margin are set to 0 // If only one is Auto, solve for it - (Auto, Specified(block_end), Specified(block_size)) => { + (MaybeAuto::Auto, MaybeAuto::Specified(block_end), MaybeAuto::Specified(block_size)) => { let margin_block_start = block_start_margin.specified_or_zero(); let margin_block_end = block_end_margin.specified_or_zero(); let sum = block_end + block_size + margin_block_start + margin_block_end; (available_block_size - sum, block_end, block_size, margin_block_start, margin_block_end) } - (Specified(block_start), Auto, Specified(block_size)) => { + (MaybeAuto::Specified(block_start), MaybeAuto::Auto, MaybeAuto::Specified(block_size)) => { let margin_block_start = block_start_margin.specified_or_zero(); let margin_block_end = block_end_margin.specified_or_zero(); let sum = block_start + block_size + margin_block_start + margin_block_end; (block_start, available_block_size - sum, block_size, margin_block_start, margin_block_end) } - (Specified(block_start), Specified(block_end), Auto) => { + (MaybeAuto::Specified(block_start), MaybeAuto::Specified(block_end), MaybeAuto::Auto) => { let margin_block_start = block_start_margin.specified_or_zero(); let margin_block_end = block_end_margin.specified_or_zero(); let sum = block_start + block_end + margin_block_start + margin_block_end; @@ -197,14 +196,14 @@ impl BSizeConstraintSolution { // If block-size is auto, then block-size is content block-size. Solve for the // non-auto value. - (Specified(block_start), Auto, Auto) => { + (MaybeAuto::Specified(block_start), MaybeAuto::Auto, MaybeAuto::Auto) => { let margin_block_start = block_start_margin.specified_or_zero(); let margin_block_end = block_end_margin.specified_or_zero(); let block_size = content_block_size; let sum = block_start + block_size + margin_block_start + margin_block_end; (block_start, available_block_size - sum, block_size, margin_block_start, margin_block_end) } - (Auto, Specified(block_end), Auto) => { + (MaybeAuto::Auto, MaybeAuto::Specified(block_end), MaybeAuto::Auto) => { let margin_block_start = block_start_margin.specified_or_zero(); let margin_block_end = block_end_margin.specified_or_zero(); let block_size = content_block_size; @@ -212,7 +211,7 @@ impl BSizeConstraintSolution { (available_block_size - sum, block_end, block_size, margin_block_start, margin_block_end) } - (Auto, Auto, Specified(block_size)) => { + (MaybeAuto::Auto, MaybeAuto::Auto, MaybeAuto::Specified(block_size)) => { let margin_block_start = block_start_margin.specified_or_zero(); let margin_block_end = block_end_margin.specified_or_zero(); let block_start = static_position_block_start; @@ -249,30 +248,30 @@ impl BSizeConstraintSolution { let static_position_block_start = static_b_offset; let (block_start, block_end, block_size, margin_block_start, margin_block_end) = match (block_start, block_end) { - (Auto, Auto) => { + (MaybeAuto::Auto, MaybeAuto::Auto) => { let margin_block_start = block_start_margin.specified_or_zero(); let margin_block_end = block_end_margin.specified_or_zero(); let block_start = static_position_block_start; let sum = block_start + block_size + margin_block_start + margin_block_end; (block_start, available_block_size - sum, block_size, margin_block_start, margin_block_end) } - (Specified(block_start), Specified(block_end)) => { + (MaybeAuto::Specified(block_start), MaybeAuto::Specified(block_end)) => { match (block_start_margin, block_end_margin) { - (Auto, Auto) => { + (MaybeAuto::Auto, MaybeAuto::Auto) => { let total_margin_val = available_block_size - block_start - block_end - block_size; (block_start, block_end, block_size, total_margin_val.scale_by(0.5), total_margin_val.scale_by(0.5)) } - (Specified(margin_block_start), Auto) => { + (MaybeAuto::Specified(margin_block_start), MaybeAuto::Auto) => { let sum = block_start + block_end + block_size + margin_block_start; (block_start, block_end, block_size, margin_block_start, available_block_size - sum) } - (Auto, Specified(margin_block_end)) => { + (MaybeAuto::Auto, MaybeAuto::Specified(margin_block_end)) => { let sum = block_start + block_end + block_size + margin_block_end; (block_start, block_end, block_size, available_block_size - sum, margin_block_end) } - (Specified(margin_block_start), Specified(margin_block_end)) => { + (MaybeAuto::Specified(margin_block_start), MaybeAuto::Specified(margin_block_end)) => { // Values are over-constrained. Ignore value for 'block-end'. let sum = block_start + block_size + margin_block_start + margin_block_end; (block_start, available_block_size - sum, block_size, margin_block_start, margin_block_end) @@ -281,13 +280,13 @@ impl BSizeConstraintSolution { } // If only one is Auto, solve for it - (Auto, Specified(block_end)) => { + (MaybeAuto::Auto, MaybeAuto::Specified(block_end)) => { let margin_block_start = block_start_margin.specified_or_zero(); let margin_block_end = block_end_margin.specified_or_zero(); let sum = block_end + block_size + margin_block_start + margin_block_end; (available_block_size - sum, block_end, block_size, margin_block_start, margin_block_end) } - (Specified(block_start), Auto) => { + (MaybeAuto::Specified(block_start), MaybeAuto::Auto) => { let margin_block_start = block_start_margin.specified_or_zero(); let margin_block_end = block_end_margin.specified_or_zero(); let sum = block_start + block_size + margin_block_start + margin_block_end; @@ -325,25 +324,26 @@ impl CandidateBSizeIterator { // `min-height` and `max-height`, percentage values are ignored. let block_size = match (fragment.style.content_block_size(), block_container_block_size) { - (LPA_Percentage(percent), Some(block_container_block_size)) => { - Specified(block_container_block_size.scale_by(percent)) + (LengthOrPercentageOrAuto::Percentage(percent), Some(block_container_block_size)) => { + MaybeAuto::Specified(block_container_block_size.scale_by(percent)) } - (LPA_Percentage(_), None) | (LPA_Auto, _) => Auto, - (LPA_Length(length), _) => Specified(length), + (LengthOrPercentageOrAuto::Percentage(_), None) | (LengthOrPercentageOrAuto::Auto, _) => MaybeAuto::Auto, + (LengthOrPercentageOrAuto::Length(length), _) => MaybeAuto::Specified(length), }; let max_block_size = match (fragment.style.max_block_size(), block_container_block_size) { - (LPN_Percentage(percent), Some(block_container_block_size)) => { + (LengthOrPercentageOrNone::Percentage(percent), Some(block_container_block_size)) => { Some(block_container_block_size.scale_by(percent)) } - (LPN_Percentage(_), None) | (LPN_None, _) => None, - (LPN_Length(length), _) => Some(length), + (LengthOrPercentageOrNone::Percentage(_), None) | + (LengthOrPercentageOrNone::None, _) => None, + (LengthOrPercentageOrNone::Length(length), _) => Some(length), }; let min_block_size = match (fragment.style.min_block_size(), block_container_block_size) { - (LP_Percentage(percent), Some(block_container_block_size)) => { + (LengthOrPercentage::Percentage(percent), Some(block_container_block_size)) => { block_container_block_size.scale_by(percent) } - (LP_Percentage(_), None) => Au(0), - (LP_Length(length), _) => length, + (LengthOrPercentage::Percentage(_), None) => Au(0), + (LengthOrPercentage::Length(length), _) => length, }; // If the style includes `box-sizing: border-box`, subtract the border and padding. @@ -357,7 +357,7 @@ impl CandidateBSizeIterator { max_block_size: max_block_size.map(|size| adjust(size, adjustment_for_box_sizing)), min_block_size: adjust(min_block_size, adjustment_for_box_sizing), candidate_value: Au(0), - status: InitialCandidateBSizeStatus, + status: CandidateBSizeIteratorStatus::Initial, }; fn adjust(size: Au, delta: Au) -> Au { @@ -369,48 +369,48 @@ impl CandidateBSizeIterator { impl Iterator<MaybeAuto> for CandidateBSizeIterator { fn next(&mut self) -> Option<MaybeAuto> { self.status = match self.status { - InitialCandidateBSizeStatus => TryingBSizeCandidateBSizeStatus, - TryingBSizeCandidateBSizeStatus => { + CandidateBSizeIteratorStatus::Initial => CandidateBSizeIteratorStatus::Trying, + CandidateBSizeIteratorStatus::Trying => { match self.max_block_size { Some(max_block_size) if self.candidate_value > max_block_size => { - TryingMaxCandidateBSizeStatus + CandidateBSizeIteratorStatus::TryingMax } - _ if self.candidate_value < self.min_block_size => TryingMinCandidateBSizeStatus, - _ => FoundCandidateBSizeStatus, + _ if self.candidate_value < self.min_block_size => CandidateBSizeIteratorStatus::TryingMin, + _ => CandidateBSizeIteratorStatus::Found, } } - TryingMaxCandidateBSizeStatus => { + CandidateBSizeIteratorStatus::TryingMax => { if self.candidate_value < self.min_block_size { - TryingMinCandidateBSizeStatus + CandidateBSizeIteratorStatus::TryingMin } else { - FoundCandidateBSizeStatus + CandidateBSizeIteratorStatus::Found } } - TryingMinCandidateBSizeStatus | FoundCandidateBSizeStatus => { - FoundCandidateBSizeStatus + CandidateBSizeIteratorStatus::TryingMin | CandidateBSizeIteratorStatus::Found => { + CandidateBSizeIteratorStatus::Found } }; match self.status { - TryingBSizeCandidateBSizeStatus => Some(self.block_size), - TryingMaxCandidateBSizeStatus => { - Some(Specified(self.max_block_size.unwrap())) + CandidateBSizeIteratorStatus::Trying => Some(self.block_size), + CandidateBSizeIteratorStatus::TryingMax => { + Some(MaybeAuto::Specified(self.max_block_size.unwrap())) } - TryingMinCandidateBSizeStatus => { - Some(Specified(self.min_block_size)) + CandidateBSizeIteratorStatus::TryingMin => { + Some(MaybeAuto::Specified(self.min_block_size)) } - FoundCandidateBSizeStatus => None, - InitialCandidateBSizeStatus => panic!(), + CandidateBSizeIteratorStatus::Found => None, + CandidateBSizeIteratorStatus::Initial => panic!(), } } } enum CandidateBSizeIteratorStatus { - InitialCandidateBSizeStatus, - TryingBSizeCandidateBSizeStatus, - TryingMaxCandidateBSizeStatus, - TryingMinCandidateBSizeStatus, - FoundCandidateBSizeStatus, + Initial, + Trying, + TryingMax, + TryingMin, + Found, } // A helper function used in block-size calculation. @@ -479,12 +479,12 @@ impl<'a> PostorderFlowTraversal for AbsoluteStoreOverflowTraversal<'a> { } pub enum BlockType { - BlockReplacedType, - BlockNonReplacedType, - AbsoluteReplacedType, - AbsoluteNonReplacedType, - FloatReplacedType, - FloatNonReplacedType, + Replaced, + NonReplaced, + AbsoluteReplaced, + AbsoluteNonReplaced, + FloatReplaced, + FloatNonReplaced, } #[deriving(Clone, PartialEq)] @@ -495,9 +495,9 @@ pub enum MarginsMayCollapseFlag { #[deriving(PartialEq)] enum FormattingContextType { - NonformattingContext, - BlockFormattingContext, - OtherFormattingContext, + None, + Block, + Other, } // Propagates the `layers_needed_for_descendants` flag appropriately from a child. This is called @@ -571,7 +571,7 @@ impl BlockFlow { pub fn from_node(constructor: &mut FlowConstructor, node: &ThreadSafeLayoutNode) -> BlockFlow { let writing_mode = node.style().writing_mode; BlockFlow { - base: BaseFlow::new(Some((*node).clone()), writing_mode, ForceNonfloated), + base: BaseFlow::new(Some((*node).clone()), writing_mode, ForceNonfloatedFlag::ForceNonfloated), fragment: Fragment::new(constructor, node), static_b_offset: Au::new(0), inline_size_of_preceding_left_floats: Au(0), @@ -585,7 +585,7 @@ impl BlockFlow { pub fn from_node_and_fragment(node: &ThreadSafeLayoutNode, fragment: Fragment) -> BlockFlow { let writing_mode = node.style().writing_mode; BlockFlow { - base: BaseFlow::new(Some((*node).clone()), writing_mode, ForceNonfloated), + base: BaseFlow::new(Some((*node).clone()), writing_mode, ForceNonfloatedFlag::ForceNonfloated), fragment: fragment, static_b_offset: Au::new(0), inline_size_of_preceding_left_floats: Au(0), @@ -602,7 +602,7 @@ impl BlockFlow { -> BlockFlow { let writing_mode = node.style().writing_mode; BlockFlow { - base: BaseFlow::new(Some((*node).clone()), writing_mode, FloatIfNecessary), + base: BaseFlow::new(Some((*node).clone()), writing_mode, ForceNonfloatedFlag::FloatIfNecessary), fragment: Fragment::new(constructor, node), static_b_offset: Au::new(0), inline_size_of_preceding_left_floats: Au(0), @@ -619,7 +619,7 @@ impl BlockFlow { -> BlockFlow { let writing_mode = node.style().writing_mode; BlockFlow { - base: BaseFlow::new(Some((*node).clone()), writing_mode, FloatIfNecessary), + base: BaseFlow::new(Some((*node).clone()), writing_mode, ForceNonfloatedFlag::FloatIfNecessary), fragment: fragment, static_b_offset: Au::new(0), inline_size_of_preceding_left_floats: Au(0), @@ -637,21 +637,21 @@ impl BlockFlow { pub fn block_type(&self) -> BlockType { if self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) { if self.is_replaced_content() { - AbsoluteReplacedType + BlockType::AbsoluteReplaced } else { - AbsoluteNonReplacedType + BlockType::AbsoluteNonReplaced } } else if self.base.flags.is_float() { if self.is_replaced_content() { - FloatReplacedType + BlockType::FloatReplaced } else { - FloatNonReplacedType + BlockType::FloatNonReplaced } } else { if self.is_replaced_content() { - BlockReplacedType + BlockType::Replaced } else { - BlockNonReplacedType + BlockType::NonReplaced } } } @@ -662,27 +662,27 @@ impl BlockFlow { containing_block_inline_size: Au) { let block_type = self.block_type(); match block_type { - AbsoluteReplacedType => { + BlockType::AbsoluteReplaced => { let inline_size_computer = AbsoluteReplaced; inline_size_computer.compute_used_inline_size(self, ctx, containing_block_inline_size); } - AbsoluteNonReplacedType => { + BlockType::AbsoluteNonReplaced => { let inline_size_computer = AbsoluteNonReplaced; inline_size_computer.compute_used_inline_size(self, ctx, containing_block_inline_size); } - FloatReplacedType => { + BlockType::FloatReplaced => { let inline_size_computer = FloatReplaced; inline_size_computer.compute_used_inline_size(self, ctx, containing_block_inline_size); } - FloatNonReplacedType => { + BlockType::FloatNonReplaced => { let inline_size_computer = FloatNonReplaced; inline_size_computer.compute_used_inline_size(self, ctx, containing_block_inline_size); } - BlockReplacedType => { + BlockType::Replaced => { let inline_size_computer = BlockReplaced; inline_size_computer.compute_used_inline_size(self, ctx, containing_block_inline_size); } - BlockNonReplacedType => { + BlockType::NonReplaced => { let inline_size_computer = BlockNonReplaced; inline_size_computer.compute_used_inline_size(self, ctx, containing_block_inline_size); } @@ -767,7 +767,7 @@ impl BlockFlow { /// and image fragments. fn is_replaced_content(&self) -> bool { match self.fragment.specific { - ScannedTextFragment(_) | ImageFragment(_) | InlineBlockFragment(_) => true, + SpecificFragmentInfo::ScannedText(_) | SpecificFragmentInfo::Image(_) | SpecificFragmentInfo::InlineBlock(_) => true, _ => false, } } @@ -793,11 +793,11 @@ impl BlockFlow { } let (block_start_margin_value, block_end_margin_value) = match self.base.collapsible_margins { - MarginsCollapseThrough(_) => panic!("Margins unexpectedly collapsed through root flow."), - MarginsCollapse(block_start_margin, block_end_margin) => { + CollapsibleMargins::CollapseThrough(_) => panic!("Margins unexpectedly collapsed through root flow."), + CollapsibleMargins::Collapse(block_start_margin, block_end_margin) => { (block_start_margin.collapse(), block_end_margin.collapse()) } - NoCollapsibleMargins(block_start, block_end) => (block_start, block_end), + CollapsibleMargins::None(block_start, block_end) => (block_start, block_end), }; // Shift all kids down (or up, if margins are negative) if necessary. @@ -840,7 +840,7 @@ impl BlockFlow { // Absolute positioning establishes a block formatting context. Don't propagate floats // in or out. (But do propagate them between kids.) if self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) || - margins_may_collapse != MarginsMayCollapse { + margins_may_collapse != MarginsMayCollapseFlag::MarginsMayCollapse { self.base.floats = Floats::new(self.fragment.style.writing_mode); } @@ -853,7 +853,7 @@ impl BlockFlow { translate_including_floats(&mut cur_b, block_start_offset, &mut self.base.floats); let can_collapse_block_start_margin_with_kids = - margins_may_collapse == MarginsMayCollapse && + margins_may_collapse == MarginsMayCollapseFlag::MarginsMayCollapse && !self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) && self.fragment.border_padding.block_start == Au(0); margin_collapse_info.initialize_block_start_margin( @@ -924,9 +924,9 @@ impl BlockFlow { let clearance = match (flow::base(kid).flags.contains(CLEARS_LEFT), flow::base(kid).flags.contains(CLEARS_RIGHT)) { (false, false) => Au(0), - (true, false) => floats.clearance(ClearLeft), - (false, true) => floats.clearance(ClearRight), - (true, true) => floats.clearance(ClearBoth), + (true, false) => floats.clearance(ClearType::Left), + (false, true) => floats.clearance(ClearType::Right), + (true, true) => floats.clearance(ClearType::Both), }; translate_including_floats(&mut cur_b, clearance, &mut floats); @@ -961,7 +961,7 @@ impl BlockFlow { // Add in our block-end margin and compute our collapsible margins. let can_collapse_block_end_margin_with_kids = - margins_may_collapse == MarginsMayCollapse && + margins_may_collapse == MarginsMayCollapseFlag::MarginsMayCollapse && !self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) && self.fragment.border_padding.block_end == Au(0); let (collapsible_margins, delta) = @@ -983,11 +983,11 @@ impl BlockFlow { block_size = Au::max(screen_size.block, block_size) } - if is_root || self.formatting_context_type() != NonformattingContext || + if is_root || self.formatting_context_type() != FormattingContextType::None || self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) { // The content block-size includes all the floats per CSS 2.1 § 10.6.7. The easiest // way to handle this is to just treat it as clearance. - block_size = block_size + floats.clearance(ClearBoth); + block_size = block_size + floats.clearance(ClearType::Both); } if self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) { @@ -1014,8 +1014,8 @@ impl BlockFlow { Some(candidate_block_size) => { candidate_block_size_iterator.candidate_value = match candidate_block_size { - Auto => block_size, - Specified(value) => value + MaybeAuto::Auto => block_size, + MaybeAuto::Specified(value) => value } } None => break, @@ -1069,7 +1069,7 @@ impl BlockFlow { // Also don't remove the dirty bits if we're a block formatting context since our inline // size has not yet been computed. (See `assign_inline_position_for_formatting_context()`.) if (self.base.flags.is_float() || - self.formatting_context_type() == NonformattingContext) && + self.formatting_context_type() == FormattingContextType::None) && !self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) { self.base.restyle_damage.remove(REFLOW_OUT_OF_FLOW | REFLOW); } @@ -1147,12 +1147,12 @@ impl BlockFlow { // calculated during assign-inline-size. let margin = self.fragment.style().logical_margin(); let margin_block_start = match margin.block_start { - LPA_Auto => Auto, - _ => Specified(self.fragment.margin.block_start) + LengthOrPercentageOrAuto::Auto => MaybeAuto::Auto, + _ => MaybeAuto::Specified(self.fragment.margin.block_start) }; let margin_block_end = match margin.block_end { - LPA_Auto => Auto, - _ => Specified(self.fragment.margin.block_end) + LengthOrPercentageOrAuto::Auto => MaybeAuto::Auto, + _ => MaybeAuto::Specified(self.fragment.margin.block_end) }; let block_start; @@ -1292,7 +1292,7 @@ impl BlockFlow { // direction.) let mut inline_size_of_preceding_left_floats = Au(0); let mut inline_size_of_preceding_right_floats = Au(0); - if self.formatting_context_type() == NonformattingContext { + if self.formatting_context_type() == FormattingContextType::None { inline_size_of_preceding_left_floats = self.inline_size_of_preceding_left_floats; inline_size_of_preceding_right_floats = self.inline_size_of_preceding_right_floats; } @@ -1301,11 +1301,11 @@ impl BlockFlow { let content_block_size = self.fragment.style().content_block_size(); let explicit_content_size = match (content_block_size, self.base.block_container_explicit_block_size) { - (LPA_Percentage(percent), Some(container_size)) => { + (LengthOrPercentageOrAuto::Percentage(percent), Some(container_size)) => { Some(container_size.scale_by(percent)) } - (LPA_Percentage(_), None) | (LPA_Auto, _) => None, - (LPA_Length(length), _) => Some(length), + (LengthOrPercentageOrAuto::Percentage(_), None) | (LengthOrPercentageOrAuto::Auto, _) => None, + (LengthOrPercentageOrAuto::Length(length), _) => Some(length), }; // Calculate containing block inline size. @@ -1410,14 +1410,14 @@ impl BlockFlow { fn formatting_context_type(&self) -> FormattingContextType { let style = self.fragment.style(); if style.get_box().float != float::none { - return OtherFormattingContext + return FormattingContextType::Other } match style.get_box().display { display::table_cell | display::table_caption | display::inline_block => { - OtherFormattingContext + FormattingContextType::Other } - _ if style.get_box().overflow != overflow::visible => BlockFormattingContext, - _ => NonformattingContext, + _ if style.get_box().overflow != overflow::visible => FormattingContextType::Block, + _ => FormattingContextType::None, } } @@ -1435,7 +1435,7 @@ impl BlockFlow { /// /// FIXME(pcwalton): This code is not incremental-reflow-safe (i.e. not idempotent). fn assign_inline_position_for_formatting_context(&mut self) { - debug_assert!(self.formatting_context_type() != NonformattingContext); + debug_assert!(self.formatting_context_type() != FormattingContextType::None); if !self.base.restyle_damage.intersects(REFLOW_OUT_OF_FLOW | REFLOW) { return @@ -1449,7 +1449,7 @@ impl BlockFlow { self.fragment.border_box.size.block), ceiling: self.base.position.start.b, max_inline_size: MAX_AU, - kind: FloatLeft, + kind: FloatKind::Left, }; // Offset our position by whatever displacement is needed to not impact the floats. @@ -1482,7 +1482,7 @@ impl BlockFlow { impl Flow for BlockFlow { fn class(&self) -> FlowClass { - BlockFlowClass + FlowClass::Block } fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow { @@ -1510,7 +1510,7 @@ impl Flow for BlockFlow { // and preferred width, rather than bubbling up children inline // width. let fixed_width = match self.fragment.style().get_box().width { - LPA_Length(_) => true, + LengthOrPercentageOrAuto::Length(_) => true, _ => false, }; @@ -1602,8 +1602,8 @@ impl Flow for BlockFlow { // Formatting contexts are never impacted by floats. match self.formatting_context_type() { - NonformattingContext => {} - BlockFormattingContext => { + FormattingContextType::None => {} + FormattingContextType::Block => { self.base.flags.remove(IMPACTED_BY_LEFT_FLOATS); self.base.flags.remove(IMPACTED_BY_RIGHT_FLOATS); @@ -1615,7 +1615,7 @@ impl Flow for BlockFlow { self.inline_size_of_preceding_left_floats - self.inline_size_of_preceding_right_floats; } - OtherFormattingContext => { + FormattingContextType::Other => { self.base.flags.remove(IMPACTED_BY_LEFT_FLOATS); self.base.flags.remove(IMPACTED_BY_RIGHT_FLOATS); } @@ -1646,7 +1646,7 @@ impl Flow for BlockFlow { return false } - let is_formatting_context = self.formatting_context_type() != NonformattingContext; + let is_formatting_context = self.formatting_context_type() != FormattingContextType::None; if !self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) && is_formatting_context { self.assign_inline_position_for_formatting_context(); } @@ -1687,10 +1687,10 @@ impl Flow for BlockFlow { } else if self.is_root() || self.base.flags.is_float() || self.is_inline_block() { // Root element margins should never be collapsed according to CSS § 8.3.1. debug!("assign_block_size: assigning block_size for root flow"); - self.assign_block_size_block_base(ctx, MarginsMayNotCollapse); + self.assign_block_size_block_base(ctx, MarginsMayCollapseFlag::MarginsMayNotCollapse); } else { debug!("assign_block_size: assigning block_size for block"); - self.assign_block_size_block_base(ctx, MarginsMayCollapse); + self.assign_block_size_block_base(ctx, MarginsMayCollapseFlag::MarginsMayCollapse); } } @@ -1839,16 +1839,16 @@ impl Flow for BlockFlow { fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) { if self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) && - self.fragment.style().logical_position().inline_start == LPA_Auto && - self.fragment.style().logical_position().inline_end == LPA_Auto { + self.fragment.style().logical_position().inline_start == LengthOrPercentageOrAuto::Auto && + self.fragment.style().logical_position().inline_end == LengthOrPercentageOrAuto::Auto { self.base.position.start.i = inline_position } } fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) { if self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) && - self.fragment.style().logical_position().block_start == LPA_Auto && - self.fragment.style().logical_position().block_end == LPA_Auto { + self.fragment.style().logical_position().block_start == LengthOrPercentageOrAuto::Auto && + self.fragment.style().logical_position().block_end == LengthOrPercentageOrAuto::Auto { self.base.position.start.b = block_position } } @@ -1976,11 +1976,11 @@ pub trait ISizeAndMarginsComputer { let style = block.fragment.style(); match (computed_inline_size, style.get_box().box_sizing) { - (Specified(size), box_sizing::border_box) => { + (MaybeAuto::Specified(size), box_sizing::border_box) => { computed_inline_size = - Specified(size - block.fragment.border_padding.inline_start_end()) + MaybeAuto::Specified(size - block.fragment.border_padding.inline_start_end()) } - (Auto, box_sizing::border_box) | (_, box_sizing::content_box) => {} + (MaybeAuto::Auto, box_sizing::border_box) | (_, box_sizing::content_box) => {} } // The text alignment of a block flow is the text alignment of its box's style. @@ -2090,7 +2090,7 @@ pub trait ISizeAndMarginsComputer { match specified_or_none(block.fragment().style().max_inline_size(), containing_block_inline_size) { Some(max_inline_size) if max_inline_size < solution.inline_size => { - input.computed_inline_size = Specified(max_inline_size); + input.computed_inline_size = MaybeAuto::Specified(max_inline_size); solution = self.solve_inline_size_constraints(block, &input); } _ => {} @@ -2102,7 +2102,7 @@ pub trait ISizeAndMarginsComputer { let computed_min_inline_size = specified(block.fragment().style().min_inline_size(), containing_block_inline_size); if computed_min_inline_size > solution.inline_size { - input.computed_inline_size = Specified(computed_min_inline_size); + input.computed_inline_size = MaybeAuto::Specified(computed_min_inline_size); solution = self.solve_inline_size_constraints(block, &input); } @@ -2131,13 +2131,13 @@ pub trait ISizeAndMarginsComputer { // If inline-size is not 'auto', and inline-size + margins > available_inline-size, all // 'auto' margins are treated as 0. let (inline_start_margin, inline_end_margin) = match computed_inline_size { - Auto => (inline_start_margin, inline_end_margin), - Specified(inline_size) => { + MaybeAuto::Auto => (inline_start_margin, inline_end_margin), + MaybeAuto::Specified(inline_size) => { let inline_start = inline_start_margin.specified_or_zero(); let inline_end = inline_end_margin.specified_or_zero(); if (inline_start + inline_end + inline_size) > available_inline_size { - (Specified(inline_start), Specified(inline_end)) + (MaybeAuto::Specified(inline_start), MaybeAuto::Specified(inline_end)) } else { (inline_start_margin, inline_end_margin) } @@ -2150,31 +2150,31 @@ pub trait ISizeAndMarginsComputer { match (inline_start_margin, computed_inline_size, inline_end_margin) { // If all have a computed value other than 'auto', the system is // over-constrained so we discard the end margin. - (Specified(margin_start), Specified(inline_size), Specified(_margin_end)) => + (MaybeAuto::Specified(margin_start), MaybeAuto::Specified(inline_size), MaybeAuto::Specified(_margin_end)) => (margin_start, inline_size, available_inline_size - (margin_start + inline_size)), // If exactly one value is 'auto', solve for it - (Auto, Specified(inline_size), Specified(margin_end)) => + (MaybeAuto::Auto, MaybeAuto::Specified(inline_size), MaybeAuto::Specified(margin_end)) => (available_inline_size - (inline_size + margin_end), inline_size, margin_end), - (Specified(margin_start), Auto, Specified(margin_end)) => + (MaybeAuto::Specified(margin_start), MaybeAuto::Auto, MaybeAuto::Specified(margin_end)) => (margin_start, available_inline_size - (margin_start + margin_end), margin_end), - (Specified(margin_start), Specified(inline_size), Auto) => + (MaybeAuto::Specified(margin_start), MaybeAuto::Specified(inline_size), MaybeAuto::Auto) => (margin_start, inline_size, available_inline_size - (margin_start + inline_size)), // If inline-size is set to 'auto', any other 'auto' value becomes '0', // and inline-size is solved for - (Auto, Auto, Specified(margin_end)) => + (MaybeAuto::Auto, MaybeAuto::Auto, MaybeAuto::Specified(margin_end)) => (Au::new(0), available_inline_size - margin_end, margin_end), - (Specified(margin_start), Auto, Auto) => + (MaybeAuto::Specified(margin_start), MaybeAuto::Auto, MaybeAuto::Auto) => (margin_start, available_inline_size - margin_start, Au::new(0)), - (Auto, Auto, Auto) => + (MaybeAuto::Auto, MaybeAuto::Auto, MaybeAuto::Auto) => (Au::new(0), available_inline_size, Au::new(0)), // If inline-start and inline-end margins are auto, they become equal - (Auto, Specified(inline_size), Auto) => { + (MaybeAuto::Auto, MaybeAuto::Specified(inline_size), MaybeAuto::Auto) => { let margin = (available_inline_size - inline_size).scale_by(0.5); (margin, inline_size, margin) } @@ -2229,7 +2229,7 @@ impl ISizeAndMarginsComputer for AbsoluteNonReplaced { let static_position_inline_start = static_i_offset; let (inline_start, inline_end, inline_size, margin_inline_start, margin_inline_end) = match (inline_start, inline_end, computed_inline_size) { - (Auto, Auto, Auto) => { + (MaybeAuto::Auto, MaybeAuto::Auto, MaybeAuto::Auto) => { let margin_start = inline_start_margin.specified_or_zero(); let margin_end = inline_end_margin.specified_or_zero(); let inline_start = static_position_inline_start; @@ -2242,9 +2242,9 @@ impl ISizeAndMarginsComputer for AbsoluteNonReplaced { let sum = inline_start + inline_size + margin_start + margin_end; (inline_start, available_inline_size - sum, inline_size, margin_start, margin_end) } - (Specified(inline_start), Specified(inline_end), Specified(inline_size)) => { + (MaybeAuto::Specified(inline_start), MaybeAuto::Specified(inline_end), MaybeAuto::Specified(inline_size)) => { match (inline_start_margin, inline_end_margin) { - (Auto, Auto) => { + (MaybeAuto::Auto, MaybeAuto::Auto) => { let total_margin_val = available_inline_size - inline_start - inline_end - inline_size; if total_margin_val < Au(0) { // margin-inline-start becomes 0 because direction is 'ltr'. @@ -2257,15 +2257,15 @@ impl ISizeAndMarginsComputer for AbsoluteNonReplaced { total_margin_val.scale_by(0.5)) } } - (Specified(margin_start), Auto) => { + (MaybeAuto::Specified(margin_start), MaybeAuto::Auto) => { let sum = inline_start + inline_end + inline_size + margin_start; (inline_start, inline_end, inline_size, margin_start, available_inline_size - sum) } - (Auto, Specified(margin_end)) => { + (MaybeAuto::Auto, MaybeAuto::Specified(margin_end)) => { let sum = inline_start + inline_end + inline_size + margin_end; (inline_start, inline_end, inline_size, available_inline_size - sum, margin_end) } - (Specified(margin_start), Specified(margin_end)) => { + (MaybeAuto::Specified(margin_start), MaybeAuto::Specified(margin_end)) => { // Values are over-constrained. // Ignore value for 'inline-end' cos direction is 'ltr'. // TODO: Handle 'rtl' when it is implemented. @@ -2277,19 +2277,19 @@ impl ISizeAndMarginsComputer for AbsoluteNonReplaced { // For the rest of the cases, auto values for margin are set to 0 // If only one is Auto, solve for it - (Auto, Specified(inline_end), Specified(inline_size)) => { + (MaybeAuto::Auto, MaybeAuto::Specified(inline_end), MaybeAuto::Specified(inline_size)) => { let margin_start = inline_start_margin.specified_or_zero(); let margin_end = inline_end_margin.specified_or_zero(); let sum = inline_end + inline_size + margin_start + margin_end; (available_inline_size - sum, inline_end, inline_size, margin_start, margin_end) } - (Specified(inline_start), Auto, Specified(inline_size)) => { + (MaybeAuto::Specified(inline_start), MaybeAuto::Auto, MaybeAuto::Specified(inline_size)) => { let margin_start = inline_start_margin.specified_or_zero(); let margin_end = inline_end_margin.specified_or_zero(); let sum = inline_start + inline_size + margin_start + margin_end; (inline_start, available_inline_size - sum, inline_size, margin_start, margin_end) } - (Specified(inline_start), Specified(inline_end), Auto) => { + (MaybeAuto::Specified(inline_start), MaybeAuto::Specified(inline_end), MaybeAuto::Auto) => { let margin_start = inline_start_margin.specified_or_zero(); let margin_end = inline_end_margin.specified_or_zero(); let sum = inline_start + inline_end + margin_start + margin_end; @@ -2298,7 +2298,7 @@ impl ISizeAndMarginsComputer for AbsoluteNonReplaced { // If inline-size is auto, then inline-size is shrink-to-fit. Solve for the // non-auto value. - (Specified(inline_start), Auto, Auto) => { + (MaybeAuto::Specified(inline_start), MaybeAuto::Auto, MaybeAuto::Auto) => { let margin_start = inline_start_margin.specified_or_zero(); let margin_end = inline_end_margin.specified_or_zero(); // Set inline-end to zero to calculate inline-size @@ -2307,7 +2307,7 @@ impl ISizeAndMarginsComputer for AbsoluteNonReplaced { let sum = inline_start + inline_size + margin_start + margin_end; (inline_start, available_inline_size - sum, inline_size, margin_start, margin_end) } - (Auto, Specified(inline_end), Auto) => { + (MaybeAuto::Auto, MaybeAuto::Specified(inline_end), MaybeAuto::Auto) => { let margin_start = inline_start_margin.specified_or_zero(); let margin_end = inline_end_margin.specified_or_zero(); // Set inline-start to zero to calculate inline-size @@ -2317,7 +2317,7 @@ impl ISizeAndMarginsComputer for AbsoluteNonReplaced { (available_inline_size - sum, inline_end, inline_size, margin_start, margin_end) } - (Auto, Auto, Specified(inline_size)) => { + (MaybeAuto::Auto, MaybeAuto::Auto, MaybeAuto::Specified(inline_size)) => { let margin_start = inline_start_margin.specified_or_zero(); let margin_end = inline_end_margin.specified_or_zero(); // Setting 'inline-start' to static position because direction is 'ltr'. @@ -2374,7 +2374,7 @@ impl ISizeAndMarginsComputer for AbsoluteReplaced { // TODO: Handle all the cases for 'rtl' direction. let inline_size = match computed_inline_size { - Specified(w) => w, + MaybeAuto::Specified(w) => w, _ => panic!("{} {}", "The used value for inline_size for absolute replaced flow", "should have already been calculated by now.") @@ -2386,7 +2386,7 @@ impl ISizeAndMarginsComputer for AbsoluteReplaced { let static_position_inline_start = static_i_offset; let (inline_start, inline_end, inline_size, margin_inline_start, margin_inline_end) = match (inline_start, inline_end) { - (Auto, Auto) => { + (MaybeAuto::Auto, MaybeAuto::Auto) => { let inline_start = static_position_inline_start; let margin_start = inline_start_margin.specified_or_zero(); let margin_end = inline_end_margin.specified_or_zero(); @@ -2394,21 +2394,21 @@ impl ISizeAndMarginsComputer for AbsoluteReplaced { (inline_start, available_inline_size - sum, inline_size, margin_start, margin_end) } // If only one is Auto, solve for it - (Auto, Specified(inline_end)) => { + (MaybeAuto::Auto, MaybeAuto::Specified(inline_end)) => { let margin_start = inline_start_margin.specified_or_zero(); let margin_end = inline_end_margin.specified_or_zero(); let sum = inline_end + inline_size + margin_start + margin_end; (available_inline_size - sum, inline_end, inline_size, margin_start, margin_end) } - (Specified(inline_start), Auto) => { + (MaybeAuto::Specified(inline_start), MaybeAuto::Auto) => { let margin_start = inline_start_margin.specified_or_zero(); let margin_end = inline_end_margin.specified_or_zero(); let sum = inline_start + inline_size + margin_start + margin_end; (inline_start, available_inline_size - sum, inline_size, margin_start, margin_end) } - (Specified(inline_start), Specified(inline_end)) => { + (MaybeAuto::Specified(inline_start), MaybeAuto::Specified(inline_end)) => { match (inline_start_margin, inline_end_margin) { - (Auto, Auto) => { + (MaybeAuto::Auto, MaybeAuto::Auto) => { let total_margin_val = available_inline_size - inline_start - inline_end - inline_size; if total_margin_val < Au(0) { // margin-inline-start becomes 0 because direction is 'ltr'. @@ -2420,15 +2420,15 @@ impl ISizeAndMarginsComputer for AbsoluteReplaced { total_margin_val.scale_by(0.5)) } } - (Specified(margin_start), Auto) => { + (MaybeAuto::Specified(margin_start), MaybeAuto::Auto) => { let sum = inline_start + inline_end + inline_size + margin_start; (inline_start, inline_end, inline_size, margin_start, available_inline_size - sum) } - (Auto, Specified(margin_end)) => { + (MaybeAuto::Auto, MaybeAuto::Specified(margin_end)) => { let sum = inline_start + inline_end + inline_size + margin_end; (inline_start, inline_end, inline_size, available_inline_size - sum, margin_end) } - (Specified(margin_start), Specified(margin_end)) => { + (MaybeAuto::Specified(margin_start), MaybeAuto::Specified(margin_end)) => { // Values are over-constrained. // Ignore value for 'inline-end' cos direction is 'ltr'. let sum = inline_start + inline_size + margin_start + margin_end; @@ -2452,7 +2452,7 @@ impl ISizeAndMarginsComputer for AbsoluteReplaced { fragment.assign_replaced_inline_size_if_necessary(containing_block_inline_size); // For replaced absolute flow, the rest of the constraint solving will // take inline-size to be specified as the value computed here. - Specified(fragment.content_inline_size()) + MaybeAuto::Specified(fragment.content_inline_size()) } fn containing_block_inline_size(&self, block: &mut BlockFlow, _: Au, ctx: &LayoutContext) -> Au { @@ -2485,8 +2485,8 @@ impl ISizeAndMarginsComputer for BlockReplaced { input: &ISizeConstraintInput) -> ISizeConstraintSolution { match input.computed_inline_size { - Specified(_) => {}, - Auto => panic!("BlockReplaced: inline_size should have been computed by now") + MaybeAuto::Specified(_) => {}, + MaybeAuto::Auto => panic!("BlockReplaced: inline_size should have been computed by now") }; self.solve_block_inline_size_constraints(block, input) } @@ -2501,7 +2501,7 @@ impl ISizeAndMarginsComputer for BlockReplaced { fragment.assign_replaced_inline_size_if_necessary(parent_flow_inline_size); // For replaced block flow, the rest of the constraint solving will // take inline-size to be specified as the value computed here. - Specified(fragment.content_inline_size()) + MaybeAuto::Specified(fragment.content_inline_size()) } } @@ -2540,8 +2540,8 @@ impl ISizeAndMarginsComputer for FloatReplaced { let margin_inline_start = inline_start_margin.specified_or_zero(); let margin_inline_end = inline_end_margin.specified_or_zero(); let inline_size = match computed_inline_size { - Specified(w) => w, - Auto => panic!("FloatReplaced: inline_size should have been computed by now") + MaybeAuto::Specified(w) => w, + MaybeAuto::Auto => panic!("FloatReplaced: inline_size should have been computed by now") }; debug!("assign_inline_sizes_float -- inline_size: {}", inline_size); ISizeConstraintSolution::new(inline_size, margin_inline_start, margin_inline_end) @@ -2557,7 +2557,7 @@ impl ISizeAndMarginsComputer for FloatReplaced { fragment.assign_replaced_inline_size_if_necessary(parent_flow_inline_size); // For replaced block flow, the rest of the constraint solving will // take inline-size to be specified as the value computed here. - Specified(fragment.content_inline_size()) + MaybeAuto::Specified(fragment.content_inline_size()) } } diff --git a/components/layout/construct.rs b/components/layout/construct.rs index ec8533058cd..f59afba4696 100644 --- a/components/layout/construct.rs +++ b/components/layout/construct.rs @@ -22,12 +22,12 @@ use flow::{Descendants, AbsDescendants}; use flow::{IS_ABSOLUTELY_POSITIONED}; use flow; use flow_ref::FlowRef; -use fragment::{Fragment, GenericFragment, IframeFragment, IframeFragmentInfo, ImageFragment}; -use fragment::{ImageFragmentInfo, InlineAbsoluteHypotheticalFragment}; -use fragment::{InlineAbsoluteHypotheticalFragmentInfo, InlineBlockFragment}; -use fragment::{InlineBlockFragmentInfo, SpecificFragmentInfo, TableCellFragment}; -use fragment::{TableColumnFragment, TableColumnFragmentInfo, TableFragment, TableRowFragment}; -use fragment::{TableWrapperFragment, UnscannedTextFragment, UnscannedTextFragmentInfo}; +use fragment::{Fragment, IframeFragmentInfo}; +use fragment::ImageFragmentInfo; +use fragment::InlineAbsoluteHypotheticalFragmentInfo; +use fragment::{InlineBlockFragmentInfo, SpecificFragmentInfo}; +use fragment::TableColumnFragmentInfo; +use fragment::UnscannedTextFragmentInfo; use incremental::{RECONSTRUCT_FLOW, RestyleDamage}; use inline::InlineFlow; use list_item::{mod, ListItemFlow}; @@ -41,19 +41,11 @@ use table_row::TableRowFlow; use table_cell::TableCellFlow; use text::TextRunScanner; use util::{HAS_NEWLY_CONSTRUCTED_FLOW, LayoutDataAccess, OpaqueNodeMethods, LayoutDataWrapper}; -use wrapper::{PostorderNodeMutTraversal, TLayoutNode, ThreadSafeLayoutNode}; -use wrapper::{Before, After, Normal}; +use wrapper::{PostorderNodeMutTraversal, PseudoElementType, TLayoutNode, ThreadSafeLayoutNode}; use gfx::display_list::OpaqueNode; -use script::dom::element::{HTMLIFrameElementTypeId, HTMLImageElementTypeId}; -use script::dom::element::{HTMLObjectElementTypeId, HTMLInputElementTypeId}; -use script::dom::element::{HTMLTableColElementTypeId, HTMLTableDataCellElementTypeId}; -use script::dom::element::{HTMLTableElementTypeId, HTMLTableHeaderCellElementTypeId}; -use script::dom::element::{HTMLTableRowElementTypeId, HTMLTableSectionElementTypeId}; -use script::dom::element::HTMLTextAreaElementTypeId; -use script::dom::node::{CommentNodeTypeId, DoctypeNodeTypeId, DocumentFragmentNodeTypeId}; -use script::dom::node::{DocumentNodeTypeId, ElementNodeTypeId, ProcessingInstructionNodeTypeId}; -use script::dom::node::{TextNodeTypeId}; +use script::dom::element::ElementTypeId; +use script::dom::node::NodeTypeId; use script::dom::htmlobjectelement::is_image_data; use servo_util::opts; use std::collections::DList; @@ -69,22 +61,22 @@ use url::Url; pub enum ConstructionResult { /// This node contributes nothing at all (`display: none`). Alternately, this is what newly /// created nodes have their `ConstructionResult` set to. - NoConstructionResult, + None, /// This node contributed a flow at the proper position in the tree. /// Nothing more needs to be done for this node. It has bubbled up fixed /// and absolute descendant flows that have a containing block above it. - FlowConstructionResult(FlowRef, AbsDescendants), + Flow(FlowRef, AbsDescendants), /// This node contributed some object or objects that will be needed to construct a proper flow /// later up the tree, but these objects have not yet found their home. - ConstructionItemConstructionResult(ConstructionItem), + ConstructionItem(ConstructionItem), } impl ConstructionResult { pub fn swap_out(&mut self) -> ConstructionResult { if opts::get().nonincremental_layout { - return mem::replace(self, NoConstructionResult) + return mem::replace(self, ConstructionResult::None) } (*self).clone() @@ -92,9 +84,9 @@ impl ConstructionResult { pub fn debug_id(&self) -> uint { match self { - &NoConstructionResult => 0u, - &ConstructionItemConstructionResult(_) => 0u, - &FlowConstructionResult(ref flow_ref, _) => flow::base(flow_ref.deref()).debug_id(), + &ConstructionResult::None => 0u, + &ConstructionResult::ConstructionItem(_) => 0u, + &ConstructionResult::Flow(ref flow_ref, _) => flow::base(flow_ref.deref()).debug_id(), } } } @@ -105,11 +97,11 @@ impl ConstructionResult { #[deriving(Clone)] pub enum ConstructionItem { /// Inline fragments and associated {ib} splits that have not yet found flows. - InlineFragmentsConstructionItem(InlineFragmentsConstructionResult), + InlineFragments(InlineFragmentsConstructionResult), /// Potentially ignorable whitespace. - WhitespaceConstructionItem(OpaqueNode, Arc<ComputedValues>, RestyleDamage), + Whitespace(OpaqueNode, Arc<ComputedValues>, RestyleDamage), /// TableColumn Fragment - TableColumnFragmentConstructionItem(Fragment), + TableColumnFragment(Fragment), } /// Represents inline fragments and {ib} splits that are bubbling up from an inline. @@ -139,7 +131,7 @@ pub struct InlineFragmentsConstructionResult { /// The resulting `ConstructionItem` for the outer `span` will be: /// /// ```ignore -/// InlineFragmentsConstructionItem(Some(~[ +/// ConstructionItem::InlineFragments(Some(~[ /// InlineBlockSplit { /// predecessor_fragments: ~[ /// A @@ -213,9 +205,9 @@ impl InlineFragmentsAccumulator { } enum WhitespaceStrippingMode { - NoWhitespaceStripping, - StripWhitespaceFromStart, - StripWhitespaceFromEnd, + None, + FromStart, + FromEnd, } /// An object that knows how to create flows. @@ -237,11 +229,11 @@ impl<'a> FlowConstructor<'a> { fn build_fragment_info_for_image(&mut self, node: &ThreadSafeLayoutNode, url: Option<Url>) -> SpecificFragmentInfo { match url { - None => GenericFragment, + None => SpecificFragmentInfo::Generic, Some(url) => { // FIXME(pcwalton): The fact that image fragments store the cache within them makes // little sense to me. - ImageFragment(box ImageFragmentInfo::new(node, + SpecificFragmentInfo::Image(box ImageFragmentInfo::new(node, url, self.layout_context .shared @@ -260,28 +252,28 @@ impl<'a> FlowConstructor<'a> { pub fn build_specific_fragment_info_for_node(&mut self, node: &ThreadSafeLayoutNode) -> SpecificFragmentInfo { match node.type_id() { - Some(ElementNodeTypeId(HTMLIFrameElementTypeId)) => { - IframeFragment(box IframeFragmentInfo::new(node)) + Some(NodeTypeId::Element(ElementTypeId::HTMLIFrameElement)) => { + SpecificFragmentInfo::Iframe(box IframeFragmentInfo::new(node)) } - Some(ElementNodeTypeId(HTMLImageElementTypeId)) => { + Some(NodeTypeId::Element(ElementTypeId::HTMLImageElement)) => { self.build_fragment_info_for_image(node, node.image_url()) } - Some(ElementNodeTypeId(HTMLObjectElementTypeId)) => { + Some(NodeTypeId::Element(ElementTypeId::HTMLObjectElement)) => { let data = node.get_object_data(); self.build_fragment_info_for_image(node, data) } - Some(ElementNodeTypeId(HTMLTableElementTypeId)) => TableWrapperFragment, - Some(ElementNodeTypeId(HTMLTableColElementTypeId)) => { - TableColumnFragment(TableColumnFragmentInfo::new(node)) + Some(NodeTypeId::Element(ElementTypeId::HTMLTableElement)) => SpecificFragmentInfo::TableWrapper, + Some(NodeTypeId::Element(ElementTypeId::HTMLTableColElement)) => { + SpecificFragmentInfo::TableColumn(TableColumnFragmentInfo::new(node)) } - Some(ElementNodeTypeId(HTMLTableDataCellElementTypeId)) | - Some(ElementNodeTypeId(HTMLTableHeaderCellElementTypeId)) => TableCellFragment, - Some(ElementNodeTypeId(HTMLTableRowElementTypeId)) | - Some(ElementNodeTypeId(HTMLTableSectionElementTypeId)) => TableRowFragment, - Some(TextNodeTypeId) => UnscannedTextFragment(UnscannedTextFragmentInfo::new(node)), + Some(NodeTypeId::Element(ElementTypeId::HTMLTableDataCellElement)) | + Some(NodeTypeId::Element(ElementTypeId::HTMLTableHeaderCellElement)) => SpecificFragmentInfo::TableCell, + Some(NodeTypeId::Element(ElementTypeId::HTMLTableRowElement)) | + Some(NodeTypeId::Element(ElementTypeId::HTMLTableSectionElement)) => SpecificFragmentInfo::TableRow, + Some(NodeTypeId::Text) => SpecificFragmentInfo::UnscannedText(UnscannedTextFragmentInfo::new(node)), _ => { // This includes pseudo-elements. - GenericFragment + SpecificFragmentInfo::Generic } } } @@ -304,14 +296,14 @@ impl<'a> FlowConstructor<'a> { }; match whitespace_stripping { - NoWhitespaceStripping => {} - StripWhitespaceFromStart => { + WhitespaceStrippingMode::None => {} + WhitespaceStrippingMode::FromStart => { strip_ignorable_whitespace_from_start(&mut fragments); if fragments.is_empty() { return }; } - StripWhitespaceFromEnd => { + WhitespaceStrippingMode::FromEnd => { strip_ignorable_whitespace_from_end(&mut fragments); if fragments.is_empty() { return @@ -323,8 +315,8 @@ impl<'a> FlowConstructor<'a> { let mut inline_block_flows = vec!(); for f in fragments.iter() { match f.specific { - InlineBlockFragment(ref info) => inline_block_flows.push(info.flow_ref.clone()), - InlineAbsoluteHypotheticalFragment(ref info) => { + SpecificFragmentInfo::InlineBlock(ref info) => inline_block_flows.push(info.flow_ref.clone()), + SpecificFragmentInfo::InlineAbsoluteHypothetical(ref info) => { inline_block_flows.push(info.flow_ref.clone()) } _ => {} @@ -374,12 +366,12 @@ impl<'a> FlowConstructor<'a> { abs_descendants: &mut Descendants, first_fragment: &mut bool) { match kid.swap_out_construction_result() { - NoConstructionResult => {} - FlowConstructionResult(kid_flow, kid_abs_descendants) => { + ConstructionResult::None => {} + ConstructionResult::Flow(kid_flow, kid_abs_descendants) => { // If kid_flow is TableCaptionFlow, kid_flow should be added under // TableWrapperFlow. if flow.is_table() && kid_flow.deref().is_table_caption() { - kid.set_flow_construction_result(FlowConstructionResult(kid_flow, + kid.set_flow_construction_result(ConstructionResult::Flow(kid_flow, Descendants::new())) } else if flow.need_anonymous_flow(&*kid_flow) { consecutive_siblings.push(kid_flow) @@ -393,7 +385,7 @@ impl<'a> FlowConstructor<'a> { InlineFragmentsAccumulator::new()), flow, consecutive_siblings, - StripWhitespaceFromStart, + WhitespaceStrippingMode::FromStart, node); if !consecutive_siblings.is_empty() { let consecutive_siblings = mem::replace(consecutive_siblings, vec!()); @@ -403,7 +395,7 @@ impl<'a> FlowConstructor<'a> { } abs_descendants.push_descendants(kid_abs_descendants); } - ConstructionItemConstructionResult(InlineFragmentsConstructionItem( + ConstructionResult::ConstructionItem(ConstructionItem::InlineFragments( InlineFragmentsConstructionResult { splits, fragments: successor_fragments, @@ -423,9 +415,9 @@ impl<'a> FlowConstructor<'a> { // whitespace per CSS 2.1 § 9.2.1.1. let whitespace_stripping = if *first_fragment { *first_fragment = false; - StripWhitespaceFromStart + WhitespaceStrippingMode::FromStart } else { - NoWhitespaceStripping + WhitespaceStrippingMode::None }; // Flush any inline fragments that we were gathering up. @@ -452,20 +444,20 @@ impl<'a> FlowConstructor<'a> { inline_fragment_accumulator.push_all(successor_fragments); abs_descendants.push_descendants(kid_abs_descendants); } - ConstructionItemConstructionResult(WhitespaceConstructionItem(whitespace_node, + ConstructionResult::ConstructionItem(ConstructionItem::Whitespace(whitespace_node, whitespace_style, whitespace_damage)) => { // Add whitespace results. They will be stripped out later on when // between block elements, and retained when between inline elements. let fragment_info = - UnscannedTextFragment(UnscannedTextFragmentInfo::from_text(" ".to_string())); + SpecificFragmentInfo::UnscannedText(UnscannedTextFragmentInfo::from_text(" ".to_string())); let fragment = Fragment::from_opaque_node_and_style(whitespace_node, whitespace_style, whitespace_damage, fragment_info); inline_fragment_accumulator.fragments.push_back(fragment); } - ConstructionItemConstructionResult(TableColumnFragmentConstructionItem(_)) => { + ConstructionResult::ConstructionItem(ConstructionItem::TableColumnFragment(_)) => { // TODO: Implement anonymous table objects for missing parents // CSS 2.1 § 17.2.1, step 3-2 } @@ -495,7 +487,7 @@ impl<'a> FlowConstructor<'a> { // List of absolute descendants, in tree order. let mut abs_descendants = Descendants::new(); for kid in node.children() { - if kid.get_pseudo_element_type() != Normal { + if kid.get_pseudo_element_type() != PseudoElementType::Normal { self.process(&kid); } @@ -514,7 +506,7 @@ impl<'a> FlowConstructor<'a> { self.flush_inline_fragments_to_flow_or_list(inline_fragment_accumulator, &mut flow, &mut consecutive_siblings, - StripWhitespaceFromEnd, + WhitespaceStrippingMode::FromEnd, node); if !consecutive_siblings.is_empty() { self.generate_anonymous_missing_child(consecutive_siblings, &mut flow, node); @@ -537,7 +529,7 @@ impl<'a> FlowConstructor<'a> { abs_descendants.push(flow.clone()); } } - FlowConstructionResult(flow, abs_descendants) + ConstructionResult::Flow(flow, abs_descendants) } /// Constructs a flow for the given block node and its children. This method creates an @@ -553,19 +545,19 @@ impl<'a> FlowConstructor<'a> { /// `<textarea>`. fn build_flow_for_block(&mut self, flow: FlowRef, node: &ThreadSafeLayoutNode) -> ConstructionResult { - let initial_fragment = if node.get_pseudo_element_type() != Normal || - node.type_id() == Some(ElementNodeTypeId(HTMLInputElementTypeId)) || - node.type_id() == Some(ElementNodeTypeId(HTMLTextAreaElementTypeId)) { + let initial_fragment = if node.get_pseudo_element_type() != PseudoElementType::Normal || + node.type_id() == Some(NodeTypeId::Element(ElementTypeId::HTMLInputElement)) || + node.type_id() == Some(NodeTypeId::Element(ElementTypeId::HTMLTextAreaElement)) { // A TextArea's text contents are displayed through the input text // box, so don't construct them. - if node.type_id() == Some(ElementNodeTypeId(HTMLTextAreaElementTypeId)) { + if node.type_id() == Some(NodeTypeId::Element(ElementTypeId::HTMLTextAreaElement)) { for kid in node.children() { - kid.set_flow_construction_result(NoConstructionResult) + kid.set_flow_construction_result(ConstructionResult::None) } } Some(Fragment::new_from_specific_info( node, - UnscannedTextFragment(UnscannedTextFragmentInfo::new(node)))) + SpecificFragmentInfo::UnscannedText(UnscannedTextFragmentInfo::new(node)))) } else { None }; @@ -602,12 +594,12 @@ impl<'a> FlowConstructor<'a> { // Concatenate all the fragments of our kids, creating {ib} splits as necessary. for kid in node.children() { - if kid.get_pseudo_element_type() != Normal { + if kid.get_pseudo_element_type() != PseudoElementType::Normal { self.process(&kid); } match kid.swap_out_construction_result() { - NoConstructionResult => {} - FlowConstructionResult(flow, kid_abs_descendants) => { + ConstructionResult::None => {} + ConstructionResult::Flow(flow, kid_abs_descendants) => { // {ib} split. Flush the accumulator to our new split and make a new // accumulator to hold any subsequent fragments we come across. let split = InlineBlockSplit { @@ -620,7 +612,7 @@ impl<'a> FlowConstructor<'a> { opt_inline_block_splits.push_back(split); abs_descendants.push_descendants(kid_abs_descendants); } - ConstructionItemConstructionResult(InlineFragmentsConstructionItem( + ConstructionResult::ConstructionItem(ConstructionItem::InlineFragments( InlineFragmentsConstructionResult { splits, fragments: successors, @@ -649,12 +641,12 @@ impl<'a> FlowConstructor<'a> { fragment_accumulator.push_all(successors); abs_descendants.push_descendants(kid_abs_descendants); } - ConstructionItemConstructionResult(WhitespaceConstructionItem( + ConstructionResult::ConstructionItem(ConstructionItem::Whitespace( whitespace_node, whitespace_style, whitespace_damage)) => { // Instantiate the whitespace fragment. - let fragment_info = UnscannedTextFragment(UnscannedTextFragmentInfo::from_text( + let fragment_info = SpecificFragmentInfo::UnscannedText(UnscannedTextFragmentInfo::from_text( " ".to_string())); let fragment = Fragment::from_opaque_node_and_style(whitespace_node, whitespace_style, @@ -662,7 +654,7 @@ impl<'a> FlowConstructor<'a> { fragment_info); fragment_accumulator.fragments.push_back(fragment) } - ConstructionItemConstructionResult(TableColumnFragmentConstructionItem(_)) => { + ConstructionResult::ConstructionItem(ConstructionItem::TableColumnFragment(_)) => { // TODO: Implement anonymous table objects for missing parents // CSS 2.1 § 17.2.1, step 3-2 } @@ -672,15 +664,15 @@ impl<'a> FlowConstructor<'a> { // Finally, make a new construction result. if opt_inline_block_splits.len() > 0 || fragment_accumulator.fragments.len() > 0 || abs_descendants.len() > 0 { - let construction_item = InlineFragmentsConstructionItem( + let construction_item = ConstructionItem::InlineFragments( InlineFragmentsConstructionResult { splits: opt_inline_block_splits, fragments: fragment_accumulator.to_dlist(), abs_descendants: abs_descendants, }); - ConstructionItemConstructionResult(construction_item) + ConstructionResult::ConstructionItem(construction_item) } else { - NoConstructionResult + ConstructionResult::None } } @@ -690,7 +682,7 @@ impl<'a> FlowConstructor<'a> { fn build_fragments_for_replaced_inline_content(&mut self, node: &ThreadSafeLayoutNode) -> ConstructionResult { for kid in node.children() { - kid.set_flow_construction_result(NoConstructionResult) + kid.set_flow_construction_result(ConstructionResult::None) } // If this node is ignorable whitespace, bail out now. @@ -698,7 +690,7 @@ impl<'a> FlowConstructor<'a> { // FIXME(#2001, pcwalton): Don't do this if there's padding or borders. if node.is_ignorable_whitespace() { let opaque_node = OpaqueNodeMethods::from_thread_safe_layout_node(node); - return ConstructionItemConstructionResult(WhitespaceConstructionItem( + return ConstructionResult::ConstructionItem(ConstructionItem::Whitespace( opaque_node, node.style().clone(), node.restyle_damage())) @@ -707,8 +699,8 @@ impl<'a> FlowConstructor<'a> { // If this is generated content, then we need to initialize the accumulator with the // fragment corresponding to that content. Otherwise, just initialize with the ordinary // fragment that needs to be generated for this inline node. - let fragment = if node.get_pseudo_element_type() != Normal { - let fragment_info = UnscannedTextFragment(UnscannedTextFragmentInfo::new(node)); + let fragment = if node.get_pseudo_element_type() != PseudoElementType::Normal { + let fragment_info = SpecificFragmentInfo::UnscannedText(UnscannedTextFragmentInfo::new(node)); Fragment::new_from_specific_info(node, fragment_info) } else { Fragment::new(self, node) @@ -717,34 +709,34 @@ impl<'a> FlowConstructor<'a> { let mut fragments = DList::new(); fragments.push_back(fragment); - let construction_item = InlineFragmentsConstructionItem(InlineFragmentsConstructionResult { + let construction_item = ConstructionItem::InlineFragments(InlineFragmentsConstructionResult { splits: DList::new(), fragments: fragments, abs_descendants: Descendants::new(), }); - ConstructionItemConstructionResult(construction_item) + ConstructionResult::ConstructionItem(construction_item) } fn build_fragment_for_inline_block(&mut self, node: &ThreadSafeLayoutNode) -> ConstructionResult { let block_flow_result = self.build_flow_for_nonfloated_block(node); let (block_flow, abs_descendants) = match block_flow_result { - FlowConstructionResult(block_flow, abs_descendants) => (block_flow, abs_descendants), + ConstructionResult::Flow(block_flow, abs_descendants) => (block_flow, abs_descendants), _ => unreachable!() }; - let fragment_info = InlineBlockFragment(InlineBlockFragmentInfo::new(block_flow)); + let fragment_info = SpecificFragmentInfo::InlineBlock(InlineBlockFragmentInfo::new(block_flow)); let fragment = Fragment::new_from_specific_info(node, fragment_info); let mut fragment_accumulator = InlineFragmentsAccumulator::from_inline_node(node); fragment_accumulator.fragments.push_back(fragment); - let construction_item = InlineFragmentsConstructionItem(InlineFragmentsConstructionResult { + let construction_item = ConstructionItem::InlineFragments(InlineFragmentsConstructionResult { splits: DList::new(), fragments: fragment_accumulator.to_dlist(), abs_descendants: abs_descendants, }); - ConstructionItemConstructionResult(construction_item) + ConstructionResult::ConstructionItem(construction_item) } /// This is an annoying case, because the computed `display` value is `block`, but the @@ -753,23 +745,23 @@ impl<'a> FlowConstructor<'a> { -> ConstructionResult { let block_flow_result = self.build_flow_for_nonfloated_block(node); let (block_flow, abs_descendants) = match block_flow_result { - FlowConstructionResult(block_flow, abs_descendants) => (block_flow, abs_descendants), + ConstructionResult::Flow(block_flow, abs_descendants) => (block_flow, abs_descendants), _ => unreachable!() }; - let fragment_info = InlineAbsoluteHypotheticalFragment( + let fragment_info = SpecificFragmentInfo::InlineAbsoluteHypothetical( InlineAbsoluteHypotheticalFragmentInfo::new(block_flow)); let fragment = Fragment::new_from_specific_info(node, fragment_info); let mut fragment_accumulator = InlineFragmentsAccumulator::from_inline_node(node); fragment_accumulator.fragments.push_back(fragment); - let construction_item = InlineFragmentsConstructionItem(InlineFragmentsConstructionResult { + let construction_item = ConstructionItem::InlineFragments(InlineFragmentsConstructionResult { splits: DList::new(), fragments: fragment_accumulator.to_dlist(), abs_descendants: abs_descendants, }); - ConstructionItemConstructionResult(construction_item) + ConstructionResult::ConstructionItem(construction_item) } /// Builds one or more fragments for a node with `display: inline`. This yields an @@ -792,8 +784,8 @@ impl<'a> FlowConstructor<'a> { node: &ThreadSafeLayoutNode) { for kid in node.children() { match kid.swap_out_construction_result() { - NoConstructionResult | ConstructionItemConstructionResult(_) => {} - FlowConstructionResult(kid_flow, _) => { + ConstructionResult::None | ConstructionResult::ConstructionItem(_) => {} + ConstructionResult::Flow(kid_flow, _) => { // Only kid flows with table-caption are matched here. if kid_flow.deref().is_table_caption() { table_wrapper_flow.add_new_child(kid_flow); @@ -836,7 +828,7 @@ impl<'a> FlowConstructor<'a> { /// possibly other `TableCaptionFlow`s or `TableFlow`s underneath it. fn build_flow_for_table_wrapper(&mut self, node: &ThreadSafeLayoutNode, float_value: float::T) -> ConstructionResult { - let fragment = Fragment::new_from_specific_info(node, TableWrapperFragment); + let fragment = Fragment::new_from_specific_info(node, SpecificFragmentInfo::TableWrapper); let wrapper_flow = match float_value { float::none => box TableWrapperFlow::from_node_and_fragment(node, fragment), _ => { @@ -846,7 +838,7 @@ impl<'a> FlowConstructor<'a> { }; let mut wrapper_flow = FlowRef::new(wrapper_flow as Box<Flow>); - let table_fragment = Fragment::new_from_specific_info(node, TableFragment); + let table_fragment = Fragment::new_from_specific_info(node, SpecificFragmentInfo::Table); let table_flow = box TableFlow::from_node_and_fragment(node, table_fragment); let table_flow = FlowRef::new(table_flow as Box<Flow>); @@ -862,7 +854,7 @@ impl<'a> FlowConstructor<'a> { // NOTE: The order of captions and table are not the same order as in the DOM tree. // All caption blocks are placed before the table flow match construction_result { - FlowConstructionResult(table_flow, table_abs_descendants) => { + ConstructionResult::Flow(table_flow, table_abs_descendants) => { wrapper_flow.add_new_child(table_flow); abs_descendants.push_descendants(table_abs_descendants); } @@ -890,7 +882,7 @@ impl<'a> FlowConstructor<'a> { } } - FlowConstructionResult(wrapper_flow, abs_descendants) + ConstructionResult::Flow(wrapper_flow, abs_descendants) } /// Builds a flow for a node with `display: table-caption`. This yields a `TableCaptionFlow` @@ -904,7 +896,7 @@ impl<'a> FlowConstructor<'a> { /// with possibly other `TableRowFlow`s underneath it. fn build_flow_for_table_rowgroup(&mut self, node: &ThreadSafeLayoutNode) -> ConstructionResult { - let fragment = Fragment::new_from_specific_info(node, TableRowFragment); + let fragment = Fragment::new_from_specific_info(node, SpecificFragmentInfo::TableRow); let flow = box TableRowGroupFlow::from_node_and_fragment(node, fragment); let flow = flow as Box<Flow>; self.build_flow_for_block(FlowRef::new(flow), node) @@ -913,7 +905,7 @@ impl<'a> FlowConstructor<'a> { /// Builds a flow for a node with `display: table-row`. This yields a `TableRowFlow` with /// possibly other `TableCellFlow`s underneath it. fn build_flow_for_table_row(&mut self, node: &ThreadSafeLayoutNode) -> ConstructionResult { - let fragment = Fragment::new_from_specific_info(node, TableRowFragment); + let fragment = Fragment::new_from_specific_info(node, SpecificFragmentInfo::TableRow); let flow = box TableRowFlow::from_node_and_fragment(node, fragment) as Box<Flow>; self.build_flow_for_block(FlowRef::new(flow), node) } @@ -921,7 +913,7 @@ impl<'a> FlowConstructor<'a> { /// Builds a flow for a node with `display: table-cell`. This yields a `TableCellFlow` with /// possibly other `BlockFlow`s or `InlineFlow`s underneath it. fn build_flow_for_table_cell(&mut self, node: &ThreadSafeLayoutNode) -> ConstructionResult { - let fragment = Fragment::new_from_specific_info(node, TableCellFragment); + let fragment = Fragment::new_from_specific_info(node, SpecificFragmentInfo::TableCell); let flow = box TableCellFlow::from_node_and_fragment(node, fragment) as Box<Flow>; self.build_flow_for_block(FlowRef::new(flow), node) } @@ -945,7 +937,7 @@ impl<'a> FlowConstructor<'a> { let mut unscanned_marker_fragments = DList::new(); unscanned_marker_fragments.push_back(Fragment::new_from_specific_info( node, - UnscannedTextFragment(UnscannedTextFragmentInfo::from_text(text)))); + SpecificFragmentInfo::UnscannedText(UnscannedTextFragmentInfo::from_text(text)))); let marker_fragments = TextRunScanner::new().scan_for_runs( self.layout_context.font_context(), unscanned_marker_fragments); @@ -984,14 +976,14 @@ impl<'a> FlowConstructor<'a> { -> ConstructionResult { // CSS 2.1 § 17.2.1. Treat all child fragments of a `table-column` as `display: none`. for kid in node.children() { - kid.set_flow_construction_result(NoConstructionResult) + kid.set_flow_construction_result(ConstructionResult::None) } - let specific = TableColumnFragment(TableColumnFragmentInfo::new(node)); - let construction_item = TableColumnFragmentConstructionItem( + let specific = SpecificFragmentInfo::TableColumn(TableColumnFragmentInfo::new(node)); + let construction_item = ConstructionItem::TableColumnFragment( Fragment::new_from_specific_info(node, specific) ); - ConstructionItemConstructionResult(construction_item) + ConstructionResult::ConstructionItem(construction_item) } /// Builds a flow for a node with `display: table-column-group`. @@ -1000,13 +992,13 @@ impl<'a> FlowConstructor<'a> { -> ConstructionResult { let fragment = Fragment::new_from_specific_info( node, - TableColumnFragment(TableColumnFragmentInfo::new(node))); + SpecificFragmentInfo::TableColumn(TableColumnFragmentInfo::new(node))); let mut col_fragments = vec!(); for kid in node.children() { // CSS 2.1 § 17.2.1. Treat all non-column child fragments of `table-column-group` // as `display: none`. match kid.swap_out_construction_result() { - ConstructionItemConstructionResult(TableColumnFragmentConstructionItem( + ConstructionResult::ConstructionItem(ConstructionItem::TableColumnFragment( fragment)) => { col_fragments.push(fragment); } @@ -1014,15 +1006,15 @@ impl<'a> FlowConstructor<'a> { } } if col_fragments.is_empty() { - debug!("add TableColumnFragment for empty colgroup"); - let specific = TableColumnFragment(TableColumnFragmentInfo::new(node)); + debug!("add SpecificFragmentInfo::TableColumn for empty colgroup"); + let specific = SpecificFragmentInfo::TableColumn(TableColumnFragmentInfo::new(node)); col_fragments.push(Fragment::new_from_specific_info(node, specific)); } let flow = box TableColGroupFlow::from_node_and_fragments(node, fragment, col_fragments); let mut flow = FlowRef::new(flow as Box<Flow>); flow.finish(); - FlowConstructionResult(flow, Descendants::new()) + ConstructionResult::Flow(flow, Descendants::new()) } /// Attempts to perform incremental repair to account for recent changes to this node. This @@ -1049,15 +1041,15 @@ impl<'a> FlowConstructor<'a> { } match node.swap_out_construction_result() { - NoConstructionResult => true, - FlowConstructionResult(mut flow, _) => { + ConstructionResult::None => true, + ConstructionResult::Flow(mut flow, _) => { // The node's flow is of the same type and has the same set of children and can // therefore be repaired by simply propagating damage and style to the flow. flow::mut_base(&mut *flow).restyle_damage.insert(node.restyle_damage()); flow.repair_style(node.style()); true } - ConstructionItemConstructionResult(_) => { + ConstructionResult::ConstructionItem(_) => { false } } @@ -1078,13 +1070,13 @@ impl<'a> PostorderNodeMutTraversal for FlowConstructor<'a> { // Pseudo-element. let style = node.style(); let display = match node.get_pseudo_element_type() { - Normal => display::inline, - Before(display) => display, - After(display) => display, + PseudoElementType::Normal => display::inline, + PseudoElementType::Before(display) => display, + PseudoElementType::After(display) => display, }; (display, style.get_box().float, style.get_box().position) } - Some(ElementNodeTypeId(_)) => { + Some(NodeTypeId::Element(_)) => { let style = node.style(); let munged_display = if style.get_box()._servo_display_for_hypothetical_box == display::inline { @@ -1094,12 +1086,12 @@ impl<'a> PostorderNodeMutTraversal for FlowConstructor<'a> { }; (munged_display, style.get_box().float, style.get_box().position) } - Some(TextNodeTypeId) => (display::inline, float::none, position::static_), - Some(CommentNodeTypeId) | - Some(DoctypeNodeTypeId) | - Some(DocumentFragmentNodeTypeId) | - Some(DocumentNodeTypeId) | - Some(ProcessingInstructionNodeTypeId) => { + Some(NodeTypeId::Text) => (display::inline, float::none, position::static_), + Some(NodeTypeId::Comment) | + Some(NodeTypeId::DocumentType) | + Some(NodeTypeId::DocumentFragment) | + Some(NodeTypeId::Document) | + Some(NodeTypeId::ProcessingInstruction) => { (display::none, float::none, position::static_) } }; @@ -1228,7 +1220,7 @@ trait NodeUtils { /// Sets the construction result of a flow. fn set_flow_construction_result(self, result: ConstructionResult); - /// Replaces the flow construction result in a node with `NoConstructionResult` and returns the + /// Replaces the flow construction result in a node with `ConstructionResult::None` and returns the /// old value. fn swap_out_construction_result(self) -> ConstructionResult; } @@ -1236,24 +1228,24 @@ trait NodeUtils { impl<'ln> NodeUtils for ThreadSafeLayoutNode<'ln> { fn is_replaced_content(&self) -> bool { match self.type_id() { - Some(TextNodeTypeId) | - Some(ProcessingInstructionNodeTypeId) | - Some(CommentNodeTypeId) | - Some(DoctypeNodeTypeId) | - Some(DocumentFragmentNodeTypeId) | - Some(DocumentNodeTypeId) | + Some(NodeTypeId::Text) | + Some(NodeTypeId::ProcessingInstruction) | + Some(NodeTypeId::Comment) | + Some(NodeTypeId::DocumentType) | + Some(NodeTypeId::DocumentFragment) | + Some(NodeTypeId::Document) | None | - Some(ElementNodeTypeId(HTMLImageElementTypeId)) => true, - Some(ElementNodeTypeId(HTMLObjectElementTypeId)) => self.has_object_data(), - Some(ElementNodeTypeId(_)) => false, + Some(NodeTypeId::Element(ElementTypeId::HTMLImageElement)) => true, + Some(NodeTypeId::Element(ElementTypeId::HTMLObjectElement)) => self.has_object_data(), + Some(NodeTypeId::Element(_)) => false, } } fn get_construction_result<'a>(self, layout_data: &'a mut LayoutDataWrapper) -> &'a mut ConstructionResult { match self.get_pseudo_element_type() { - Before(_) => &mut layout_data.data.before_flow_construction_result, - After (_) => &mut layout_data.data.after_flow_construction_result, - Normal => &mut layout_data.data.flow_construction_result, + PseudoElementType::Before(_) => &mut layout_data.data.before_flow_construction_result, + PseudoElementType::After (_) => &mut layout_data.data.after_flow_construction_result, + PseudoElementType::Normal => &mut layout_data.data.flow_construction_result, } } diff --git a/components/layout/css/matching.rs b/components/layout/css/matching.rs index 86968a6d9c2..f8d4a3f72c2 100644 --- a/components/layout/css/matching.rs +++ b/components/layout/css/matching.rs @@ -9,7 +9,7 @@ use incremental::{mod, RestyleDamage}; use util::{LayoutDataAccess, LayoutDataWrapper}; use wrapper::{LayoutElement, LayoutNode, TLayoutNode}; -use script::dom::node::{TextNodeTypeId}; +use script::dom::node::NodeTypeId; use servo_util::bloom::BloomFilter; use servo_util::cache::{Cache, LRUCache, SimpleHashCache}; use servo_util::smallvec::{SmallVec, SmallVec16}; @@ -18,8 +18,8 @@ use std::mem; use std::hash::{Hash, sip}; use std::slice::Items; use string_cache::{Atom, Namespace}; -use style::{mod, After, Before, ComputedValues, DeclarationBlock, Stylist, TElement, TNode}; -use style::{AttrIsEqualMode, AttrIsPresentMode, CommonStyleAffectingAttributes, cascade}; +use style::{mod, PseudoElement, ComputedValues, DeclarationBlock, Stylist, TElement, TNode}; +use style::{CommonStyleAffectingAttributeMode, CommonStyleAffectingAttributes, cascade}; use sync::Arc; pub struct ApplicableDeclarations { @@ -153,12 +153,12 @@ fn create_common_style_affecting_attributes_from_element(element: &LayoutElement let mut flags = CommonStyleAffectingAttributes::empty(); for attribute_info in style::common_style_affecting_attributes().iter() { match attribute_info.mode { - AttrIsPresentMode(flag) => { + CommonStyleAffectingAttributeMode::IsPresent(flag) => { if element.get_attr(&ns!(""), &attribute_info.atom).is_some() { flags.insert(flag) } } - AttrIsEqualMode(target_value, flag) => { + CommonStyleAffectingAttributeMode::IsEqual(target_value, flag) => { match element.get_attr(&ns!(""), &attribute_info.atom) { Some(element_value) if element_value == target_value => { flags.insert(flag) @@ -273,13 +273,13 @@ impl StyleSharingCandidate { for attribute_info in style::common_style_affecting_attributes().iter() { match attribute_info.mode { - AttrIsPresentMode(flag) => { + CommonStyleAffectingAttributeMode::IsPresent(flag) => { if self.common_style_affecting_attributes.contains(flag) != element.get_attr(&ns!(""), &attribute_info.atom).is_some() { return false } } - AttrIsEqualMode(target_value, flag) => { + CommonStyleAffectingAttributeMode::IsEqual(target_value, flag) => { match element.get_attr(&ns!(""), &attribute_info.atom) { Some(ref element_value) if self.common_style_affecting_attributes .contains(flag) && @@ -501,12 +501,12 @@ impl<'ln> MatchMethods for LayoutNode<'ln> { stylist.push_applicable_declarations(self, parent_bf, None, - Some(Before), + Some(PseudoElement::Before), &mut applicable_declarations.before); stylist.push_applicable_declarations(self, parent_bf, None, - Some(After), + Some(PseudoElement::After), &mut applicable_declarations.after); *shareable = applicable_declarations.normal_shareable && @@ -520,7 +520,7 @@ impl<'ln> MatchMethods for LayoutNode<'ln> { parent: Option<LayoutNode>) -> StyleSharingResult { if !self.is_element() { - return CannotShare(false) + return StyleSharingResult::CannotShare(false) } let ok = { let element = self.as_element(); @@ -528,7 +528,7 @@ impl<'ln> MatchMethods for LayoutNode<'ln> { element.get_attr(&ns!(""), &atom!("id")).is_none() }; if !ok { - return CannotShare(false) + return StyleSharingResult::CannotShare(false) } for (i, &(ref candidate, ())) in style_sharing_candidate_cache.iter().enumerate() { @@ -540,13 +540,13 @@ impl<'ln> MatchMethods for LayoutNode<'ln> { let style = &mut shared_data.style; let damage = incremental::compute_damage(style, &*shared_style); *style = Some(shared_style); - return StyleWasShared(i, damage) + return StyleSharingResult::StyleWasShared(i, damage) } None => {} } } - CannotShare(true) + StyleSharingResult::CannotShare(true) } // The below two functions are copy+paste because I can't figure out how to @@ -614,7 +614,7 @@ impl<'ln> MatchMethods for LayoutNode<'ln> { &None => panic!("no layout data"), &Some(ref mut layout_data) => { match self.type_id() { - Some(TextNodeTypeId) => { + Some(NodeTypeId::Text) => { // Text nodes get a copy of the parent style. This ensures // that during fragment construction any non-inherited // CSS properties (such as vertical-align) are correctly diff --git a/components/layout/css/node_style.rs b/components/layout/css/node_style.rs index c3eaa04ddd2..8b4e1aa08a4 100644 --- a/components/layout/css/node_style.rs +++ b/components/layout/css/node_style.rs @@ -4,7 +4,7 @@ //! Style retrieval from DOM elements. -use wrapper::{After, Before, Normal, ThreadSafeLayoutNode}; +use wrapper::{PseudoElementType, ThreadSafeLayoutNode}; use std::mem; use style::ComputedValues; @@ -27,7 +27,7 @@ impl<'ln> StyledNode for ThreadSafeLayoutNode<'ln> { unsafe { let layout_data_ref = self.borrow_layout_data(); match self.get_pseudo_element_type() { - Before(_) => { + PseudoElementType::Before(_) => { mem::transmute(layout_data_ref.as_ref() .unwrap() .data @@ -35,7 +35,7 @@ impl<'ln> StyledNode for ThreadSafeLayoutNode<'ln> { .as_ref() .unwrap()) } - After(_) => { + PseudoElementType::After(_) => { mem::transmute(layout_data_ref.as_ref() .unwrap() .data @@ -43,7 +43,7 @@ impl<'ln> StyledNode for ThreadSafeLayoutNode<'ln> { .as_ref() .unwrap()) } - Normal => { + PseudoElementType::Normal => { mem::transmute(layout_data_ref.as_ref() .unwrap() .shared_data @@ -66,9 +66,9 @@ impl<'ln> StyledNode for ThreadSafeLayoutNode<'ln> { let style = match self.get_pseudo_element_type() { - Before(_) => &mut layout_data.data.before_style, - After (_) => &mut layout_data.data.after_style, - Normal => &mut layout_data.shared_data.style, + PseudoElementType::Before(_) => &mut layout_data.data.before_style, + PseudoElementType::After (_) => &mut layout_data.data.after_style, + PseudoElementType::Normal => &mut layout_data.shared_data.style, }; *style = None; diff --git a/components/layout/display_list_builder.rs b/components/layout/display_list_builder.rs index c8db1d4f992..33f40f8b188 100644 --- a/components/layout/display_list_builder.rs +++ b/components/layout/display_list_builder.rs @@ -13,11 +13,8 @@ use block::BlockFlow; use context::LayoutContext; use flow::{mod, Flow, IS_ABSOLUTELY_POSITIONED, NEEDS_LAYER}; -use fragment::{Fragment, GenericFragment, IframeFragment, IframeFragmentInfo, ImageFragment}; -use fragment::{ImageFragmentInfo, InlineAbsoluteHypotheticalFragment, InlineBlockFragment}; -use fragment::{ScannedTextFragment, ScannedTextFragmentInfo, TableFragment}; -use fragment::{TableCellFragment, TableColumnFragment, TableRowFragment, TableWrapperFragment}; -use fragment::{UnscannedTextFragment}; +use fragment::{Fragment, SpecificFragmentInfo, IframeFragmentInfo, ImageFragmentInfo}; +use fragment::ScannedTextFragmentInfo; use list_item::ListItemFlow; use model; use util::{OpaqueNodeMethods, ToGfxColor}; @@ -41,20 +38,21 @@ use servo_util::geometry::{mod, Au, ZERO_POINT, ZERO_RECT}; use servo_util::logical_geometry::{LogicalRect, WritingMode}; use servo_util::opts; use std::default::Default; -use style::computed::{AngleAoc, CornerAoc, LP_Length, LP_Percentage, LengthOrPercentage}; -use style::computed::{LinearGradient, LinearGradientImage, UrlImage}; +use std::num::FloatMath; +use style::computed::{AngleOrCorner, LengthOrPercentage, HorizontalDirection, VerticalDirection}; +use style::computed::{Image, LinearGradient}; use style::computed_values::{background_attachment, background_repeat, border_style, overflow}; use style::computed_values::{visibility}; -use style::{ComputedValues, Bottom, Left, RGBA, Right, Top}; +use style::{ComputedValues, RGBA}; use style::style_structs::Border; use sync::Arc; use url::Url; /// The results of display list building for a single flow. pub enum DisplayListBuildingResult { - NoDisplayListBuildingResult, - StackingContextResult(Arc<StackingContext>), - DisplayListResult(Box<DisplayList>), + None, + StackingContext(Arc<StackingContext>), + Normal(Box<DisplayList>), } impl DisplayListBuildingResult { @@ -63,11 +61,11 @@ impl DisplayListBuildingResult { /// consist of an entire stacking context, it will be emptied. pub fn add_to(&mut self, display_list: &mut DisplayList) { match *self { - NoDisplayListBuildingResult => return, - StackingContextResult(ref mut stacking_context) => { + DisplayListBuildingResult::None => return, + DisplayListBuildingResult::StackingContext(ref mut stacking_context) => { display_list.children.push_back((*stacking_context).clone()) } - DisplayListResult(ref mut source_display_list) => { + DisplayListBuildingResult::Normal(ref mut source_display_list) => { display_list.append_from(&mut **source_display_list) } } @@ -210,7 +208,7 @@ impl FragmentDisplayListBuilding for Fragment { let background = style.get_background(); match background.background_image { None => {} - Some(LinearGradientImage(ref gradient)) => { + Some(Image::LinearGradient(ref gradient)) => { self.build_display_list_for_background_linear_gradient(display_list, level, absolute_bounds, @@ -218,7 +216,7 @@ impl FragmentDisplayListBuilding for Fragment { gradient, style) } - Some(UrlImage(ref image_url)) => { + Some(Image::Url(ref image_url)) => { self.build_display_list_for_background_image(style, display_list, layout_context, @@ -330,20 +328,20 @@ impl FragmentDisplayListBuilding for Fragment { // This is the distance between the center and the ending point; i.e. half of the distance // between the starting point and the ending point. let delta = match gradient.angle_or_corner { - AngleAoc(angle) => { + AngleOrCorner::Angle(angle) => { Point2D(Au((angle.radians().sin() * absolute_bounds.size.width.to_f64().unwrap() / 2.0) as i32), Au((-angle.radians().cos() * absolute_bounds.size.height.to_f64().unwrap() / 2.0) as i32)) } - CornerAoc(horizontal, vertical) => { + AngleOrCorner::Corner(horizontal, vertical) => { let x_factor = match horizontal { - Left => -1, - Right => 1, + HorizontalDirection::Left => -1, + HorizontalDirection::Right => 1, }; let y_factor = match vertical { - Top => -1, - Bottom => 1, + VerticalDirection::Top => -1, + VerticalDirection::Bottom => 1, }; Point2D(Au(x_factor * absolute_bounds.size.width.to_i32().unwrap() / 2), Au(y_factor * absolute_bounds.size.height.to_i32().unwrap() / 2)) @@ -647,7 +645,7 @@ impl FragmentDisplayListBuilding for Fragment { None => {} } match self.specific { - ScannedTextFragment(_) => {}, + SpecificFragmentInfo::ScannedText(_) => {}, _ => { self.build_display_list_for_box_shadow_if_applicable( &*self.style, @@ -675,7 +673,7 @@ impl FragmentDisplayListBuilding for Fragment { None => {} } match self.specific { - ScannedTextFragment(_) => {}, + SpecificFragmentInfo::ScannedText(_) => {}, _ => { self.build_display_list_for_background_if_applicable( &*self.style, @@ -707,7 +705,7 @@ impl FragmentDisplayListBuilding for Fragment { None => {} } match self.specific { - ScannedTextFragment(_) => {}, + SpecificFragmentInfo::ScannedText(_) => {}, _ => { self.build_display_list_for_borders_if_applicable( &*self.style, @@ -729,9 +727,9 @@ impl FragmentDisplayListBuilding for Fragment { // Create special per-fragment-type display items. match self.specific { - UnscannedTextFragment(_) => panic!("Shouldn't see unscanned fragments here."), - TableColumnFragment(_) => panic!("Shouldn't see table column fragments here."), - ScannedTextFragment(ref text_fragment) => { + SpecificFragmentInfo::UnscannedText(_) => panic!("Shouldn't see unscanned fragments here."), + SpecificFragmentInfo::TableColumn(_) => panic!("Shouldn't see table column fragments here."), + SpecificFragmentInfo::ScannedText(ref text_fragment) => { // Create the text display item. let orientation = if self.style.writing_mode.is_vertical() { if self.style.writing_mode.is_sideways_left() { @@ -806,16 +804,16 @@ impl FragmentDisplayListBuilding for Fragment { clip_rect); } } - GenericFragment | IframeFragment(..) | TableFragment | TableCellFragment | - TableRowFragment | TableWrapperFragment | InlineBlockFragment(_) | - InlineAbsoluteHypotheticalFragment(_) => { + SpecificFragmentInfo::Generic | SpecificFragmentInfo::Iframe(..) | SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | + SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableWrapper | SpecificFragmentInfo::InlineBlock(_) | + SpecificFragmentInfo::InlineAbsoluteHypothetical(_) => { if opts::get().show_debug_fragment_borders { self.build_debug_borders_around_fragment(display_list, flow_origin, clip_rect); } } - ImageFragment(ref mut image_fragment) => { + SpecificFragmentInfo::Image(ref mut image_fragment) => { let image_ref = &mut image_fragment.image; match image_ref.get_image(self.node.to_untrusted_node_address()) { Some(image) => { @@ -857,7 +855,7 @@ impl FragmentDisplayListBuilding for Fragment { // because layout for the iframe only needs to know size, and origin is only relevant if // the iframe is actually going to be displayed. match self.specific { - IframeFragment(ref iframe_fragment) => { + SpecificFragmentInfo::Iframe(ref iframe_fragment) => { self.finalize_position_and_size_of_iframe(&**iframe_fragment, absolute_fragment_bounds.origin, layout_context) @@ -891,7 +889,7 @@ impl FragmentDisplayListBuilding for Fragment { -> Rect<Au> { // Don't clip if we're text. match self.specific { - ScannedTextFragment(_) => return current_clip_rect, + SpecificFragmentInfo::ScannedText(_) => return current_clip_rect, _ => {} } @@ -962,9 +960,9 @@ impl BlockFlowDisplayListBuilding for BlockFlow { background_border_level); self.base.display_list_building_result = if self.fragment.establishes_stacking_context() { - StackingContextResult(self.create_stacking_context(display_list, None)) + DisplayListBuildingResult::StackingContext(self.create_stacking_context(display_list, None)) } else { - DisplayListResult(display_list) + DisplayListBuildingResult::Normal(display_list) } } @@ -973,13 +971,13 @@ impl BlockFlowDisplayListBuilding for BlockFlow { layout_context: &LayoutContext) { self.build_display_list_for_block_base(&mut *display_list, layout_context, - RootOfStackingContextLevel); + BackgroundAndBorderLevel::RootOfStackingContext); if !self.base.absolute_position_info.layers_needed_for_positioned_flows && !self.base.flags.contains(NEEDS_LAYER) { // We didn't need a layer. self.base.display_list_building_result = - StackingContextResult(self.create_stacking_context(display_list, None)); + DisplayListBuildingResult::StackingContext(self.create_stacking_context(display_list, None)); return } @@ -996,7 +994,7 @@ impl BlockFlowDisplayListBuilding for BlockFlow { Some(Arc::new(PaintLayer::new(self.layer_id(0), transparent, scroll_policy)))); - self.base.display_list_building_result = StackingContextResult(stacking_context) + self.base.display_list_building_result = DisplayListBuildingResult::StackingContext(stacking_context) } fn build_display_list_for_floating_block(&mut self, @@ -1004,13 +1002,13 @@ impl BlockFlowDisplayListBuilding for BlockFlow { layout_context: &LayoutContext) { self.build_display_list_for_block_base(&mut *display_list, layout_context, - RootOfStackingContextLevel); + BackgroundAndBorderLevel::RootOfStackingContext); display_list.form_float_pseudo_stacking_context(); self.base.display_list_building_result = if self.fragment.establishes_stacking_context() { - StackingContextResult(self.create_stacking_context(display_list, None)) + DisplayListBuildingResult::StackingContext(self.create_stacking_context(display_list, None)) } else { - DisplayListResult(display_list) + DisplayListBuildingResult::Normal(display_list) } } @@ -1024,7 +1022,7 @@ impl BlockFlowDisplayListBuilding for BlockFlow { } else if self.base.flags.contains(IS_ABSOLUTELY_POSITIONED) { self.build_display_list_for_absolutely_positioned_block(display_list, layout_context) } else { - self.build_display_list_for_static_block(display_list, layout_context, BlockLevel) + self.build_display_list_for_static_block(display_list, layout_context, BackgroundAndBorderLevel::Block) } } @@ -1059,7 +1057,7 @@ impl ListItemFlowDisplayListBuilding for ListItemFlow { marker.build_display_list(&mut *display_list, layout_context, stacking_relative_fragment_origin, - ContentLevel, + BackgroundAndBorderLevel::Content, &self.block_flow.base.clip_rect); } } @@ -1087,8 +1085,8 @@ fn fmin(a: f32, b: f32) -> f32 { fn position_to_offset(position: LengthOrPercentage, Au(total_length): Au) -> f32 { match position { - LP_Length(Au(length)) => fmin(1.0, (length as f32) / (total_length as f32)), - LP_Percentage(percentage) => percentage as f32, + LengthOrPercentage::Length(Au(length)) => fmin(1.0, (length as f32) / (total_length as f32)), + LengthOrPercentage::Percentage(percentage) => percentage as f32, } } @@ -1096,29 +1094,29 @@ fn position_to_offset(position: LengthOrPercentage, Au(total_length): Au) -> f32 #[deriving(Clone, PartialEq, Show)] pub enum StackingLevel { /// The border and backgrounds for the root of this stacking context: steps 1 and 2. - BackgroundAndBordersStackingLevel, + BackgroundAndBorders, /// Borders and backgrounds for block-level descendants: step 4. - BlockBackgroundsAndBordersStackingLevel, + BlockBackgroundsAndBorders, /// All other content. - ContentStackingLevel, + Content, } impl StackingLevel { #[inline] pub fn from_background_and_border_level(level: BackgroundAndBorderLevel) -> StackingLevel { match level { - RootOfStackingContextLevel => BackgroundAndBordersStackingLevel, - BlockLevel => BlockBackgroundsAndBordersStackingLevel, - ContentLevel => ContentStackingLevel, + BackgroundAndBorderLevel::RootOfStackingContext => StackingLevel::BackgroundAndBorders, + BackgroundAndBorderLevel::Block => StackingLevel::BlockBackgroundsAndBorders, + BackgroundAndBorderLevel::Content => StackingLevel::Content, } } } /// Which level to place backgrounds and borders in. pub enum BackgroundAndBorderLevel { - RootOfStackingContextLevel, - BlockLevel, - ContentLevel, + RootOfStackingContext, + Block, + Content, } trait StackingContextConstruction { @@ -1129,13 +1127,13 @@ trait StackingContextConstruction { impl StackingContextConstruction for DisplayList { fn push(&mut self, display_item: DisplayItem, level: StackingLevel) { match level { - BackgroundAndBordersStackingLevel => { + StackingLevel::BackgroundAndBorders => { self.background_and_borders.push_back(display_item) } - BlockBackgroundsAndBordersStackingLevel => { + StackingLevel::BlockBackgroundsAndBorders => { self.block_backgrounds_and_borders.push_back(display_item) } - ContentStackingLevel => self.content.push_back(display_item), + StackingLevel::Content => self.content.push_back(display_item), } } } diff --git a/components/layout/floats.rs b/components/layout/floats.rs index 887ff67446d..ca840bc5374 100644 --- a/components/layout/floats.rs +++ b/components/layout/floats.rs @@ -14,25 +14,25 @@ use style::computed_values::float; /// The kind of float: left or right. #[deriving(Clone, Encodable, Show)] pub enum FloatKind { - FloatLeft, - FloatRight + Left, + Right } impl FloatKind { pub fn from_property(property: float::T) -> FloatKind { match property { float::none => panic!("can't create a float type from an unfloated property"), - float::left => FloatLeft, - float::right => FloatRight, + float::left => FloatKind::Left, + float::right => FloatKind::Right, } } } /// The kind of clearance: left, right, or both. pub enum ClearType { - ClearLeft, - ClearRight, - ClearBoth, + Left, + Right, + Both, } /// Information about a single float. @@ -184,7 +184,7 @@ impl Floats { debug!("float_pos: {}, float_size: {}", float_pos, float_size); match float.kind { - FloatLeft if float_pos.i + float_size.inline > max_inline_start && + FloatKind::Left if float_pos.i + float_size.inline > max_inline_start && float_pos.b + float_size.block > block_start && float_pos.b < block_start + block_size => { max_inline_start = float_pos.i + float_size.inline; @@ -196,7 +196,7 @@ impl Floats { max_inline_start is {}", max_inline_start); } - FloatRight if float_pos.i < min_inline_end && + FloatKind::Right if float_pos.i < min_inline_end && float_pos.b + float_size.block > block_start && float_pos.b < block_start + block_size => { min_inline_end = float_pos.i; @@ -207,7 +207,7 @@ impl Floats { is {}", min_inline_end); } - FloatLeft | FloatRight => {} + FloatKind::Left | FloatKind::Right => {} } } @@ -307,7 +307,7 @@ impl Floats { // If no floats, use this fast path. if !self.list.is_present() { match info.kind { - FloatLeft => { + FloatKind::Left => { return LogicalRect::new( self.writing_mode, Au(0), @@ -315,7 +315,7 @@ impl Floats { info.max_inline_size, Au(i32::MAX)) } - FloatRight => { + FloatKind::Right => { return LogicalRect::new( self.writing_mode, info.max_inline_size - info.size.inline, @@ -338,7 +338,7 @@ impl Floats { // TODO(eatkinson): integrate with overflow None => { return match info.kind { - FloatLeft => { + FloatKind::Left => { LogicalRect::new( self.writing_mode, Au(0), @@ -346,7 +346,7 @@ impl Floats { info.max_inline_size, Au(i32::MAX)) } - FloatRight => { + FloatKind::Right => { LogicalRect::new( self.writing_mode, info.max_inline_size - info.size.inline, @@ -367,7 +367,7 @@ impl Floats { rect.size.inline); let block_size = block_size.unwrap_or(Au(i32::MAX)); return match info.kind { - FloatLeft => { + FloatKind::Left => { LogicalRect::new( self.writing_mode, rect.start.i, @@ -375,7 +375,7 @@ impl Floats { rect.size.inline, block_size) } - FloatRight => { + FloatKind::Right => { LogicalRect::new( self.writing_mode, rect.start.i + rect.size.inline - info.size.inline, @@ -399,9 +399,9 @@ impl Floats { let mut clearance = Au(0); for float in list.floats.iter() { match (clear, float.kind) { - (ClearLeft, FloatLeft) | - (ClearRight, FloatRight) | - (ClearBoth, _) => { + (ClearType::Left, FloatKind::Left) | + (ClearType::Right, FloatKind::Right) | + (ClearType::Both, _) => { let b = self.offset.block + float.bounds.start.b + float.bounds.size.block; clearance = max(clearance, b); } diff --git a/components/layout/flow.rs b/components/layout/flow.rs index c7ce0275ef6..11ec16e86e5 100644 --- a/components/layout/flow.rs +++ b/components/layout/flow.rs @@ -28,12 +28,11 @@ use css::node_style::StyledNode; use block::BlockFlow; use context::LayoutContext; -use display_list_builder::{DisplayListBuildingResult, DisplayListResult}; -use display_list_builder::{NoDisplayListBuildingResult, StackingContextResult}; +use display_list_builder::DisplayListBuildingResult; use floats::Floats; use flow_list::{FlowList, FlowListIterator, MutFlowListIterator}; use flow_ref::FlowRef; -use fragment::{Fragment, FragmentBoundsIterator, TableRowFragment, TableCellFragment}; +use fragment::{Fragment, FragmentBoundsIterator, SpecificFragmentInfo}; use incremental::{RECONSTRUCT_FLOW, REFLOW, REFLOW_OUT_OF_FLOW, RestyleDamage}; use inline::InlineFlow; use model::{CollapsibleMargins, IntrinsicISizes, MarginCollapseInfo}; @@ -428,16 +427,16 @@ pub trait MutableOwnedFlowUtils { #[deriving(Encodable, PartialEq, Show)] pub enum FlowClass { - BlockFlowClass, - InlineFlowClass, - ListItemFlowClass, - TableWrapperFlowClass, - TableFlowClass, - TableColGroupFlowClass, - TableRowGroupFlowClass, - TableRowFlowClass, - TableCaptionFlowClass, - TableCellFlowClass, + Block, + Inline, + ListItem, + TableWrapper, + Table, + TableColGroup, + TableRowGroup, + TableRow, + TableCaption, + TableCell, } /// A top-down traversal. @@ -810,13 +809,13 @@ impl<E, S: Encoder<E>> Encodable<S, E> for BaseFlow { try!(e.emit_struct_field("class", 0, |e| c.class().encode(e))) e.emit_struct_field("data", 1, |e| { match c.class() { - BlockFlowClass => c.as_immutable_block().encode(e), - InlineFlowClass => c.as_immutable_inline().encode(e), - TableFlowClass => c.as_immutable_table().encode(e), - TableWrapperFlowClass => c.as_immutable_table_wrapper().encode(e), - TableRowGroupFlowClass => c.as_immutable_table_rowgroup().encode(e), - TableRowFlowClass => c.as_immutable_table_row().encode(e), - TableCellFlowClass => c.as_immutable_table_cell().encode(e), + FlowClass::Block => c.as_immutable_block().encode(e), + FlowClass::Inline => c.as_immutable_inline().encode(e), + FlowClass::Table => c.as_immutable_table().encode(e), + FlowClass::TableWrapper => c.as_immutable_table_wrapper().encode(e), + FlowClass::TableRowGroup => c.as_immutable_table_rowgroup().encode(e), + FlowClass::TableRow => c.as_immutable_table_row().encode(e), + FlowClass::TableCell => c.as_immutable_table_cell().encode(e), _ => { Ok(()) } // TODO: Support captions } }) @@ -869,7 +868,7 @@ impl BaseFlow { _ => {} } - if force_nonfloated == FloatIfNecessary { + if force_nonfloated == ForceNonfloatedFlag::FloatIfNecessary { match node_style.get_box().float { float::none => {} float::left => flags.insert(FLOATS_LEFT), @@ -910,7 +909,7 @@ impl BaseFlow { block_container_inline_size: Au(0), block_container_explicit_block_size: None, absolute_cb: ContainingBlockLink::new(), - display_list_building_result: NoDisplayListBuildingResult, + display_list_building_result: DisplayListBuildingResult::None, absolute_position_info: AbsolutePositionInfo::new(writing_mode), clip_rect: Rect(Zero::zero(), Size2D(Au(0), Au(0))), flags: flags, @@ -940,11 +939,11 @@ impl BaseFlow { position_with_overflow.size.block)); let all_items = match self.display_list_building_result { - NoDisplayListBuildingResult => Vec::new(), - StackingContextResult(ref stacking_context) => { + DisplayListBuildingResult::None => Vec::new(), + DisplayListBuildingResult::StackingContext(ref stacking_context) => { stacking_context.display_list.all_display_items() } - DisplayListResult(ref display_list) => display_list.all_display_items(), + DisplayListBuildingResult::Normal(ref display_list) => display_list.all_display_items(), }; for item in all_items.iter() { @@ -979,7 +978,7 @@ impl<'a> ImmutableFlowUtils for &'a Flow + 'a { /// Returns true if this flow is a block flow. fn is_block_like(self) -> bool { match self.class() { - BlockFlowClass => true, + FlowClass::Block => true, _ => false, } } @@ -989,8 +988,8 @@ impl<'a> ImmutableFlowUtils for &'a Flow + 'a { /// table-column-group flow, or table-caption flow. fn is_proper_table_child(self) -> bool { match self.class() { - TableRowFlowClass | TableRowGroupFlowClass | - TableColGroupFlowClass | TableCaptionFlowClass => true, + FlowClass::TableRow | FlowClass::TableRowGroup | + FlowClass::TableColGroup | FlowClass::TableCaption => true, _ => false, } } @@ -998,7 +997,7 @@ impl<'a> ImmutableFlowUtils for &'a Flow + 'a { /// Returns true if this flow is a table row flow. fn is_table_row(self) -> bool { match self.class() { - TableRowFlowClass => true, + FlowClass::TableRow => true, _ => false, } } @@ -1006,7 +1005,7 @@ impl<'a> ImmutableFlowUtils for &'a Flow + 'a { /// Returns true if this flow is a table cell flow. fn is_table_cell(self) -> bool { match self.class() { - TableCellFlowClass => true, + FlowClass::TableCell => true, _ => false, } } @@ -1014,7 +1013,7 @@ impl<'a> ImmutableFlowUtils for &'a Flow + 'a { /// Returns true if this flow is a table colgroup flow. fn is_table_colgroup(self) -> bool { match self.class() { - TableColGroupFlowClass => true, + FlowClass::TableColGroup => true, _ => false, } } @@ -1022,7 +1021,7 @@ impl<'a> ImmutableFlowUtils for &'a Flow + 'a { /// Returns true if this flow is a table flow. fn is_table(self) -> bool { match self.class() { - TableFlowClass => true, + FlowClass::Table => true, _ => false, } } @@ -1030,7 +1029,7 @@ impl<'a> ImmutableFlowUtils for &'a Flow + 'a { /// Returns true if this flow is a table caption flow. fn is_table_caption(self) -> bool { match self.class() { - TableCaptionFlowClass => true, + FlowClass::TableCaption => true, _ => false, } } @@ -1038,7 +1037,7 @@ impl<'a> ImmutableFlowUtils for &'a Flow + 'a { /// Returns true if this flow is a table rowgroup flow. fn is_table_rowgroup(self) -> bool { match self.class() { - TableRowGroupFlowClass => true, + FlowClass::TableRowGroup => true, _ => false, } } @@ -1046,9 +1045,9 @@ impl<'a> ImmutableFlowUtils for &'a Flow + 'a { /// Returns true if this flow is one of table-related flows. fn is_table_kind(self) -> bool { match self.class() { - TableWrapperFlowClass | TableFlowClass | - TableColGroupFlowClass | TableRowGroupFlowClass | - TableRowFlowClass | TableCaptionFlowClass | TableCellFlowClass => true, + FlowClass::TableWrapper | FlowClass::Table | + FlowClass::TableColGroup | FlowClass::TableRowGroup | + FlowClass::TableRow | FlowClass::TableCaption | FlowClass::TableCell => true, _ => false, } } @@ -1057,9 +1056,9 @@ impl<'a> ImmutableFlowUtils for &'a Flow + 'a { /// Spec: http://www.w3.org/TR/CSS21/tables.html#anonymous-boxes fn need_anonymous_flow(self, child: &Flow) -> bool { match self.class() { - TableFlowClass => !child.is_proper_table_child(), - TableRowGroupFlowClass => !child.is_table_row(), - TableRowFlowClass => !child.is_table_cell(), + FlowClass::Table => !child.is_proper_table_child(), + FlowClass::TableRowGroup => !child.is_table_row(), + FlowClass::TableRow => !child.is_table_cell(), _ => false } } @@ -1067,12 +1066,12 @@ impl<'a> ImmutableFlowUtils for &'a Flow + 'a { /// Generates missing child flow of this flow. fn generate_missing_child_flow(self, node: &ThreadSafeLayoutNode) -> FlowRef { let flow = match self.class() { - TableFlowClass | TableRowGroupFlowClass => { - let fragment = Fragment::new_anonymous_table_fragment(node, TableRowFragment); + FlowClass::Table | FlowClass::TableRowGroup => { + let fragment = Fragment::new_anonymous_table_fragment(node, SpecificFragmentInfo::TableRow); box TableRowFlow::from_node_and_fragment(node, fragment) as Box<Flow> }, - TableRowFlowClass => { - let fragment = Fragment::new_anonymous_table_fragment(node, TableCellFragment); + FlowClass::TableRow => { + let fragment = Fragment::new_anonymous_table_fragment(node, SpecificFragmentInfo::TableCell); box TableCellFlow::from_node_and_fragment(node, fragment) as Box<Flow> }, _ => { @@ -1101,7 +1100,7 @@ impl<'a> ImmutableFlowUtils for &'a Flow + 'a { fn is_block_container(self) -> bool { match self.class() { // TODO: Change this when inline-blocks are supported. - BlockFlowClass | TableCaptionFlowClass | TableCellFlowClass => { + FlowClass::Block | FlowClass::TableCaption | FlowClass::TableCell => { // FIXME: Actually check the type of the node self.child_count() != 0 } @@ -1112,7 +1111,7 @@ impl<'a> ImmutableFlowUtils for &'a Flow + 'a { /// Returns true if this flow is a block flow. fn is_block_flow(self) -> bool { match self.class() { - BlockFlowClass => true, + FlowClass::Block => true, _ => false, } } @@ -1120,7 +1119,7 @@ impl<'a> ImmutableFlowUtils for &'a Flow + 'a { /// Returns true if this flow is an inline flow. fn is_inline_flow(self) -> bool { match self.class() { - InlineFlowClass => true, + FlowClass::Inline => true, _ => false, } } diff --git a/components/layout/fragment.rs b/components/layout/fragment.rs index 0c4bf98a75e..bfc4286ae0e 100644 --- a/components/layout/fragment.rs +++ b/components/layout/fragment.rs @@ -9,14 +9,14 @@ use css::node_style::StyledNode; use construct::FlowConstructor; use context::LayoutContext; -use floats::{ClearBoth, ClearLeft, ClearRight, ClearType}; +use floats::ClearType; use flow; use flow::Flow; use flow_ref::FlowRef; use incremental::RestyleDamage; use inline::{InlineFragmentContext, InlineMetrics}; use layout_debug; -use model::{Auto, IntrinsicISizes, IntrinsicISizesContribution, MaybeAuto, Specified, specified}; +use model::{IntrinsicISizes, IntrinsicISizesContribution, MaybeAuto, specified}; use model; use text; use util::OpaqueNodeMethods; @@ -39,12 +39,12 @@ use servo_util::smallvec::SmallVec; use servo_util::str::is_whitespace; use std::cmp::{max, min}; use std::fmt; -use std::from_str::FromStr; +use std::str::FromStr; use string_cache::Atom; use style::{ComputedValues, TElement, TNode, cascade_anonymous}; use style::computed_values::{LengthOrPercentage, LengthOrPercentageOrAuto}; use style::computed_values::{LengthOrPercentageOrNone}; -use style::computed_values::{LPA_Auto, clear, overflow_wrap, position, text_align}; +use style::computed_values::{clear, overflow_wrap, position, text_align}; use style::computed_values::{text_decoration, vertical_align, white_space}; use sync::{Arc, Mutex}; use url::Url; @@ -62,7 +62,7 @@ use url::Url; /// positioned as if it were a block fragment, but its children are positioned according to /// inline flow. /// -/// A `GenericFragment` is an empty fragment that contributes only borders, margins, padding, and +/// A `SpecificFragmentInfo::Generic` is an empty fragment that contributes only borders, margins, padding, and /// backgrounds. It is analogous to a CSS nonreplaced content box. /// /// A fragment's type influences how its styles are interpreted during layout. For example, @@ -124,40 +124,40 @@ impl<E, S: Encoder<E>> Encodable<S, E> for Fragment { /// Keep this enum small. As in, no more than one word. Or pcwalton will yell at you. #[deriving(Clone)] pub enum SpecificFragmentInfo { - GenericFragment, - IframeFragment(Box<IframeFragmentInfo>), - ImageFragment(Box<ImageFragmentInfo>), + Generic, + Iframe(Box<IframeFragmentInfo>), + Image(Box<ImageFragmentInfo>), /// A hypothetical box (see CSS 2.1 § 10.3.7) for an absolutely-positioned block that was /// declared with `display: inline;`. - InlineAbsoluteHypotheticalFragment(InlineAbsoluteHypotheticalFragmentInfo), - - InlineBlockFragment(InlineBlockFragmentInfo), - ScannedTextFragment(Box<ScannedTextFragmentInfo>), - TableFragment, - TableCellFragment, - TableColumnFragment(TableColumnFragmentInfo), - TableRowFragment, - TableWrapperFragment, - UnscannedTextFragment(UnscannedTextFragmentInfo), + InlineAbsoluteHypothetical(InlineAbsoluteHypotheticalFragmentInfo), + + InlineBlock(InlineBlockFragmentInfo), + ScannedText(Box<ScannedTextFragmentInfo>), + Table, + TableCell, + TableColumn(TableColumnFragmentInfo), + TableRow, + TableWrapper, + UnscannedText(UnscannedTextFragmentInfo), } impl SpecificFragmentInfo { fn restyle_damage(&self) -> RestyleDamage { let flow = match *self { - IframeFragment(_) - | ImageFragment(_) - | ScannedTextFragment(_) - | TableFragment - | TableCellFragment - | TableColumnFragment(_) - | TableRowFragment - | TableWrapperFragment - | UnscannedTextFragment(_) - | GenericFragment => return RestyleDamage::empty(), - InlineAbsoluteHypotheticalFragment(ref info) => &info.flow_ref, - InlineBlockFragment(ref info) => &info.flow_ref, + SpecificFragmentInfo::Iframe(_) + | SpecificFragmentInfo::Image(_) + | SpecificFragmentInfo::ScannedText(_) + | SpecificFragmentInfo::Table + | SpecificFragmentInfo::TableCell + | SpecificFragmentInfo::TableColumn(_) + | SpecificFragmentInfo::TableRow + | SpecificFragmentInfo::TableWrapper + | SpecificFragmentInfo::UnscannedText(_) + | SpecificFragmentInfo::Generic => return RestyleDamage::empty(), + SpecificFragmentInfo::InlineAbsoluteHypothetical(ref info) => &info.flow_ref, + SpecificFragmentInfo::InlineBlock(ref info) => &info.flow_ref, }; flow::base(flow.deref()).restyle_damage @@ -165,18 +165,18 @@ impl SpecificFragmentInfo { pub fn get_type(&self) -> &'static str { match *self { - GenericFragment => "GenericFragment", - IframeFragment(_) => "IframeFragment", - ImageFragment(_) => "ImageFragment", - InlineAbsoluteHypotheticalFragment(_) => "InlineAbsoluteHypotheticalFragment", - InlineBlockFragment(_) => "InlineBlockFragment", - ScannedTextFragment(_) => "ScannedTextFragment", - TableFragment => "TableFragment", - TableCellFragment => "TableCellFragment", - TableColumnFragment(_) => "TableColumnFragment", - TableRowFragment => "TableRowFragment", - TableWrapperFragment => "TableWrapperFragment", - UnscannedTextFragment(_) => "UnscannedTextFragment", + SpecificFragmentInfo::Generic => "SpecificFragmentInfo::Generic", + SpecificFragmentInfo::Iframe(_) => "SpecificFragmentInfo::Iframe", + SpecificFragmentInfo::Image(_) => "SpecificFragmentInfo::Image", + SpecificFragmentInfo::InlineAbsoluteHypothetical(_) => "SpecificFragmentInfo::InlineAbsoluteHypothetical", + SpecificFragmentInfo::InlineBlock(_) => "SpecificFragmentInfo::InlineBlock", + SpecificFragmentInfo::ScannedText(_) => "SpecificFragmentInfo::ScannedText", + SpecificFragmentInfo::Table => "SpecificFragmentInfo::Table", + SpecificFragmentInfo::TableCell => "SpecificFragmentInfo::TableCell", + SpecificFragmentInfo::TableColumn(_) => "SpecificFragmentInfo::TableColumn", + SpecificFragmentInfo::TableRow => "SpecificFragmentInfo::TableRow", + SpecificFragmentInfo::TableWrapper => "SpecificFragmentInfo::TableWrapper", + SpecificFragmentInfo::UnscannedText(_) => "SpecificFragmentInfo::UnscannedText", } } } @@ -294,14 +294,14 @@ impl ImageFragmentInfo { dom_length: Option<Au>, container_inline_size: Au) -> MaybeAuto { match (MaybeAuto::from_style(style_length,container_inline_size),dom_length) { - (Specified(length),_) => { - Specified(length) + (MaybeAuto::Specified(length),_) => { + MaybeAuto::Specified(length) }, - (Auto,Some(length)) => { - Specified(length) + (MaybeAuto::Auto,Some(length)) => { + MaybeAuto::Specified(length) }, - (Auto,None) => { - Auto + (MaybeAuto::Auto,None) => { + MaybeAuto::Auto } } } @@ -531,7 +531,7 @@ impl Fragment { // Foo // </div> // - // Anonymous table fragments, TableRowFragment and TableCellFragment, are generated around + // Anonymous table fragments, SpecificFragmentInfo::TableRow and SpecificFragmentInfo::TableCell, are generated around // `Foo`, but they shouldn't inherit the border. let node_style = cascade_anonymous(&**node.style()); @@ -574,11 +574,11 @@ impl Fragment { self.margin = LogicalMargin::zero(self.style.writing_mode); } - /// Saves the new_line_pos vector into a `ScannedTextFragment`. This will fail + /// Saves the new_line_pos vector into a `SpecificFragmentInfo::ScannedText`. This will fail /// if called on any other type of fragment. pub fn save_new_line_pos(&mut self) { match &mut self.specific { - &ScannedTextFragment(ref mut info) => { + &SpecificFragmentInfo::ScannedText(ref mut info) => { if !info.new_line_pos.is_empty() { info.original_new_line_pos = Some(info.new_line_pos.clone()); } @@ -589,7 +589,7 @@ impl Fragment { pub fn restore_new_line_pos(&mut self) { match &mut self.specific { - &ScannedTextFragment(ref mut info) => { + &SpecificFragmentInfo::ScannedText(ref mut info) => { match info.original_new_line_pos.take() { None => {} Some(new_line_pos) => info.new_line_pos = new_line_pos, @@ -623,7 +623,7 @@ impl Fragment { border_box: new_border_box, border_padding: self.border_padding, margin: self.margin, - specific: ScannedTextFragment(info), + specific: SpecificFragmentInfo::ScannedText(info), inline_context: self.inline_context.clone(), debug_id: self.debug_id, } @@ -647,25 +647,25 @@ impl Fragment { fn quantities_included_in_intrinsic_inline_size(&self) -> QuantitiesIncludedInIntrinsicInlineSizes { match self.specific { - GenericFragment | IframeFragment(_) | ImageFragment(_) | InlineBlockFragment(_) => { + SpecificFragmentInfo::Generic | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Image(_) | SpecificFragmentInfo::InlineBlock(_) => { QuantitiesIncludedInIntrinsicInlineSizes::all() } - TableFragment | TableCellFragment => { + SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell => { INTRINSIC_INLINE_SIZE_INCLUDES_PADDING | INTRINSIC_INLINE_SIZE_INCLUDES_BORDER | INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED } - TableWrapperFragment => { + SpecificFragmentInfo::TableWrapper => { INTRINSIC_INLINE_SIZE_INCLUDES_MARGINS | INTRINSIC_INLINE_SIZE_INCLUDES_BORDER | INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED } - TableRowFragment => { + SpecificFragmentInfo::TableRow => { INTRINSIC_INLINE_SIZE_INCLUDES_BORDER | INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED } - ScannedTextFragment(_) | TableColumnFragment(_) | UnscannedTextFragment(_) | - InlineAbsoluteHypotheticalFragment(_) => { + SpecificFragmentInfo::ScannedText(_) | SpecificFragmentInfo::TableColumn(_) | SpecificFragmentInfo::UnscannedText(_) | + SpecificFragmentInfo::InlineAbsoluteHypothetical(_) => { QuantitiesIncludedInIntrinsicInlineSizes::empty() } } @@ -744,7 +744,7 @@ impl Fragment { #[inline] pub fn border_width(&self) -> LogicalMargin<Au> { let style_border_width = match self.specific { - ScannedTextFragment(_) => LogicalMargin::zero(self.style.writing_mode), + SpecificFragmentInfo::ScannedText(_) => LogicalMargin::zero(self.style.writing_mode), _ => self.style().logical_border_width(), }; @@ -764,7 +764,7 @@ impl Fragment { /// (for example, via constraint solving for blocks). pub fn compute_inline_direction_margins(&mut self, containing_block_inline_size: Au) { match self.specific { - TableFragment | TableCellFragment | TableRowFragment | TableColumnFragment(_) => { + SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableColumn(_) => { self.margin.inline_start = Au(0); self.margin.inline_end = Au(0) } @@ -787,7 +787,7 @@ impl Fragment { /// (for example, via constraint solving for absolutely-positioned flows). pub fn compute_block_direction_margins(&mut self, containing_block_inline_size: Au) { match self.specific { - TableFragment | TableCellFragment | TableRowFragment | TableColumnFragment(_) => { + SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableColumn(_) => { self.margin.block_start = Au(0); self.margin.block_end = Au(0) } @@ -814,11 +814,11 @@ impl Fragment { // Compute padding. let padding = match self.specific { - TableColumnFragment(_) | TableRowFragment | - TableWrapperFragment => LogicalMargin::zero(self.style.writing_mode), + SpecificFragmentInfo::TableColumn(_) | SpecificFragmentInfo::TableRow | + SpecificFragmentInfo::TableWrapper => LogicalMargin::zero(self.style.writing_mode), _ => { let style_padding = match self.specific { - ScannedTextFragment(_) => LogicalMargin::zero(self.style.writing_mode), + SpecificFragmentInfo::ScannedText(_) => LogicalMargin::zero(self.style.writing_mode), _ => model::padding_from_style(self.style(), containing_block_inline_size), }; @@ -842,12 +842,12 @@ impl Fragment { fn from_style(style: &ComputedValues, container_size: &LogicalSize<Au>) -> LogicalSize<Au> { let offsets = style.logical_position(); - let offset_i = if offsets.inline_start != LPA_Auto { + let offset_i = if offsets.inline_start != LengthOrPercentageOrAuto::Auto { MaybeAuto::from_style(offsets.inline_start, container_size.inline).specified_or_zero() } else { -MaybeAuto::from_style(offsets.inline_end, container_size.inline).specified_or_zero() }; - let offset_b = if offsets.block_start != LPA_Auto { + let offset_b = if offsets.block_start != LengthOrPercentageOrAuto::Auto { MaybeAuto::from_style(offsets.block_start, container_size.inline).specified_or_zero() } else { -MaybeAuto::from_style(offsets.block_end, container_size.inline).specified_or_zero() @@ -883,9 +883,9 @@ impl Fragment { let style = self.style(); match style.get_box().clear { clear::none => None, - clear::left => Some(ClearLeft), - clear::right => Some(ClearRight), - clear::both => Some(ClearBoth), + clear::left => Some(ClearType::Left), + clear::right => Some(ClearType::Right), + clear::both => Some(ClearType::Both), } } @@ -925,9 +925,9 @@ impl Fragment { /// inlines. pub fn inline_start_offset(&self) -> Au { match self.specific { - TableWrapperFragment => self.margin.inline_start, - TableFragment | TableCellFragment | TableRowFragment => self.border_padding.inline_start, - TableColumnFragment(_) => Au(0), + SpecificFragmentInfo::TableWrapper => self.margin.inline_start, + SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | SpecificFragmentInfo::TableRow => self.border_padding.inline_start, + SpecificFragmentInfo::TableColumn(_) => Au(0), _ => self.margin.inline_start + self.border_padding.inline_start, } } @@ -940,7 +940,7 @@ impl Fragment { /// Returns the newline positions of this fragment, if it's a scanned text fragment. pub fn newline_positions(&self) -> Option<&Vec<CharIndex>> { match self.specific { - ScannedTextFragment(ref info) => Some(&info.new_line_pos), + SpecificFragmentInfo::ScannedText(ref info) => Some(&info.new_line_pos), _ => None, } } @@ -948,7 +948,7 @@ impl Fragment { /// Returns the newline positions of this fragment, if it's a scanned text fragment. pub fn newline_positions_mut(&mut self) -> Option<&mut Vec<CharIndex>> { match self.specific { - ScannedTextFragment(ref mut info) => Some(&mut info.new_line_pos), + SpecificFragmentInfo::ScannedText(ref mut info) => Some(&mut info.new_line_pos), _ => None, } } @@ -956,7 +956,7 @@ impl Fragment { /// Returns true if and only if this is a scanned text fragment. fn is_scanned_text_fragment(&self) -> bool { match self.specific { - ScannedTextFragment(..) => true, + SpecificFragmentInfo::ScannedText(..) => true, _ => false, } } @@ -965,21 +965,21 @@ impl Fragment { pub fn compute_intrinsic_inline_sizes(&mut self) -> IntrinsicISizesContribution { let mut result = self.style_specified_intrinsic_inline_size(); match self.specific { - GenericFragment | IframeFragment(_) | TableFragment | TableCellFragment | - TableColumnFragment(_) | TableRowFragment | TableWrapperFragment | - InlineAbsoluteHypotheticalFragment(_) => {} - InlineBlockFragment(ref mut info) => { + SpecificFragmentInfo::Generic | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | + SpecificFragmentInfo::TableColumn(_) | SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableWrapper | + SpecificFragmentInfo::InlineAbsoluteHypothetical(_) => {} + SpecificFragmentInfo::InlineBlock(ref mut info) => { let block_flow = info.flow_ref.as_block(); result.union_block(&block_flow.base.intrinsic_inline_sizes) } - ImageFragment(ref mut image_fragment_info) => { + SpecificFragmentInfo::Image(ref mut image_fragment_info) => { let image_inline_size = image_fragment_info.image_inline_size(); result.union_block(&IntrinsicISizes { minimum_inline_size: image_inline_size, preferred_inline_size: image_inline_size, }) } - ScannedTextFragment(ref text_fragment_info) => { + SpecificFragmentInfo::ScannedText(ref text_fragment_info) => { let range = &text_fragment_info.range; let min_line_inline_size = text_fragment_info.run.min_width_for_range(range); @@ -994,7 +994,7 @@ impl Fragment { preferred_inline_size: max_line_inline_size, }) } - UnscannedTextFragment(..) => { + SpecificFragmentInfo::UnscannedText(..) => { panic!("Unscanned text fragments should have been scanned by now!") } }; @@ -1019,40 +1019,40 @@ impl Fragment { } - /// TODO: What exactly does this function return? Why is it Au(0) for GenericFragment? + /// TODO: What exactly does this function return? Why is it Au(0) for SpecificFragmentInfo::Generic? pub fn content_inline_size(&self) -> Au { match self.specific { - GenericFragment | IframeFragment(_) | TableFragment | TableCellFragment | - TableRowFragment | TableWrapperFragment | InlineBlockFragment(_) | - InlineAbsoluteHypotheticalFragment(_) => Au(0), - ImageFragment(ref image_fragment_info) => { + SpecificFragmentInfo::Generic | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | + SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableWrapper | SpecificFragmentInfo::InlineBlock(_) | + SpecificFragmentInfo::InlineAbsoluteHypothetical(_) => Au(0), + SpecificFragmentInfo::Image(ref image_fragment_info) => { image_fragment_info.computed_inline_size() } - ScannedTextFragment(ref text_fragment_info) => { + SpecificFragmentInfo::ScannedText(ref text_fragment_info) => { let (range, run) = (&text_fragment_info.range, &text_fragment_info.run); let text_bounds = run.metrics_for_range(range).bounding_box; text_bounds.size.width } - TableColumnFragment(_) => panic!("Table column fragments do not have inline_size"), - UnscannedTextFragment(_) => panic!("Unscanned text fragments should have been scanned by now!"), + SpecificFragmentInfo::TableColumn(_) => panic!("Table column fragments do not have inline_size"), + SpecificFragmentInfo::UnscannedText(_) => panic!("Unscanned text fragments should have been scanned by now!"), } } /// Returns, and computes, the block-size of this fragment. pub fn content_block_size(&self, layout_context: &LayoutContext) -> Au { match self.specific { - GenericFragment | IframeFragment(_) | TableFragment | TableCellFragment | - TableRowFragment | TableWrapperFragment | InlineBlockFragment(_) | - InlineAbsoluteHypotheticalFragment(_) => Au(0), - ImageFragment(ref image_fragment_info) => { + SpecificFragmentInfo::Generic | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | + SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableWrapper | SpecificFragmentInfo::InlineBlock(_) | + SpecificFragmentInfo::InlineAbsoluteHypothetical(_) => Au(0), + SpecificFragmentInfo::Image(ref image_fragment_info) => { image_fragment_info.computed_block_size() } - ScannedTextFragment(_) => { + SpecificFragmentInfo::ScannedText(_) => { // Compute the block-size based on the line-block-size and font size. self.calculate_line_height(layout_context) } - TableColumnFragment(_) => panic!("Table column fragments do not have block_size"), - UnscannedTextFragment(_) => panic!("Unscanned text fragments should have been scanned by now!"), + SpecificFragmentInfo::TableColumn(_) => panic!("Table column fragments do not have block_size"), + SpecificFragmentInfo::UnscannedText(_) => panic!("Unscanned text fragments should have been scanned by now!"), } } @@ -1076,14 +1076,14 @@ impl Fragment { pub fn find_split_info_by_new_line(&self) -> Option<(SplitInfo, Option<SplitInfo>, Arc<Box<TextRun>> /* TODO(bjz): remove */)> { match self.specific { - GenericFragment | IframeFragment(_) | ImageFragment(_) | TableFragment | TableCellFragment | - TableRowFragment | TableWrapperFragment => None, - TableColumnFragment(_) => panic!("Table column fragments do not need to split"), - UnscannedTextFragment(_) => panic!("Unscanned text fragments should have been scanned by now!"), - InlineBlockFragment(_) | InlineAbsoluteHypotheticalFragment(_) => { + SpecificFragmentInfo::Generic | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Image(_) | SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | + SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableWrapper => None, + SpecificFragmentInfo::TableColumn(_) => panic!("Table column fragments do not need to split"), + SpecificFragmentInfo::UnscannedText(_) => panic!("Unscanned text fragments should have been scanned by now!"), + SpecificFragmentInfo::InlineBlock(_) | SpecificFragmentInfo::InlineAbsoluteHypothetical(_) => { panic!("Inline blocks or inline absolute hypothetical fragments do not get split") } - ScannedTextFragment(ref text_fragment_info) => { + SpecificFragmentInfo::ScannedText(ref text_fragment_info) => { let mut new_line_pos = text_fragment_info.new_line_pos.clone(); let cur_new_line_pos = new_line_pos.remove(0).unwrap(); @@ -1118,14 +1118,14 @@ impl Fragment { pub fn calculate_split_position(&self, max_inline_size: Au, starts_line: bool) -> Option<SplitResult> { let text_fragment_info = match self.specific { - GenericFragment | IframeFragment(_) | ImageFragment(_) | TableFragment | - TableCellFragment | TableRowFragment | TableWrapperFragment | InlineBlockFragment(_) | - InlineAbsoluteHypotheticalFragment(_) => return None, - TableColumnFragment(_) => panic!("Table column fragments do not have inline_size"), - UnscannedTextFragment(_) => { + SpecificFragmentInfo::Generic | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Image(_) | SpecificFragmentInfo::Table | + SpecificFragmentInfo::TableCell | SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableWrapper | SpecificFragmentInfo::InlineBlock(_) | + SpecificFragmentInfo::InlineAbsoluteHypothetical(_) => return None, + SpecificFragmentInfo::TableColumn(_) => panic!("Table column fragments do not have inline_size"), + SpecificFragmentInfo::UnscannedText(_) => { panic!("Unscanned text fragments should have been scanned by now!") } - ScannedTextFragment(ref text_fragment_info) => text_fragment_info, + SpecificFragmentInfo::ScannedText(ref text_fragment_info) => text_fragment_info, }; let mut flags = SplitOptions::empty(); @@ -1152,14 +1152,14 @@ impl Fragment { -> Option<SplitResult> where I: Iterator<TextRunSlice<'a>> { let text_fragment_info = match self.specific { - GenericFragment | IframeFragment(_) | ImageFragment(_) | TableFragment | - TableCellFragment | TableRowFragment | TableWrapperFragment | InlineBlockFragment(_) | - InlineAbsoluteHypotheticalFragment(_) => return None, - TableColumnFragment(_) => panic!("Table column fragments do not have inline_size"), - UnscannedTextFragment(_) => { + SpecificFragmentInfo::Generic | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Image(_) | SpecificFragmentInfo::Table | + SpecificFragmentInfo::TableCell | SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableWrapper | SpecificFragmentInfo::InlineBlock(_) | + SpecificFragmentInfo::InlineAbsoluteHypothetical(_) => return None, + SpecificFragmentInfo::TableColumn(_) => panic!("Table column fragments do not have inline_size"), + SpecificFragmentInfo::UnscannedText(_) => { panic!("Unscanned text fragments should have been scanned by now!") } - ScannedTextFragment(ref text_fragment_info) => text_fragment_info, + SpecificFragmentInfo::ScannedText(ref text_fragment_info) => text_fragment_info, }; let mut pieces_processed_count: uint = 0; @@ -1262,7 +1262,7 @@ impl Fragment { white_space::normal | white_space::nowrap => {} } match self.specific { - UnscannedTextFragment(ref text_fragment_info) => { + SpecificFragmentInfo::UnscannedText(ref text_fragment_info) => { is_whitespace(text_fragment_info.text.as_slice()) } _ => false, @@ -1273,14 +1273,14 @@ impl Fragment { /// content per CSS 2.1 § 10.3.2. pub fn assign_replaced_inline_size_if_necessary(&mut self, container_inline_size: Au) { match self.specific { - GenericFragment | IframeFragment(_) | TableFragment | TableCellFragment | - TableRowFragment | TableWrapperFragment => return, - TableColumnFragment(_) => panic!("Table column fragments do not have inline_size"), - UnscannedTextFragment(_) => { + SpecificFragmentInfo::Generic | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | + SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableWrapper => return, + SpecificFragmentInfo::TableColumn(_) => panic!("Table column fragments do not have inline_size"), + SpecificFragmentInfo::UnscannedText(_) => { panic!("Unscanned text fragments should have been scanned by now!") } - ImageFragment(_) | ScannedTextFragment(_) | InlineBlockFragment(_) | - InlineAbsoluteHypotheticalFragment(_) => {} + SpecificFragmentInfo::Image(_) | SpecificFragmentInfo::ScannedText(_) | SpecificFragmentInfo::InlineBlock(_) | + SpecificFragmentInfo::InlineAbsoluteHypothetical(_) => {} }; let style_inline_size = self.style().content_inline_size(); @@ -1292,7 +1292,7 @@ impl Fragment { let noncontent_inline_size = self.border_padding.inline_start_end(); match self.specific { - InlineAbsoluteHypotheticalFragment(ref mut info) => { + SpecificFragmentInfo::InlineAbsoluteHypothetical(ref mut info) => { let block_flow = info.flow_ref.as_block(); block_flow.base.position.size.inline = block_flow.base.intrinsic_inline_sizes.preferred_inline_size; @@ -1300,18 +1300,18 @@ impl Fragment { // This is a hypothetical box, so it takes up no space. self.border_box.size.inline = Au(0); } - InlineBlockFragment(ref mut info) => { + SpecificFragmentInfo::InlineBlock(ref mut info) => { let block_flow = info.flow_ref.as_block(); self.border_box.size.inline = block_flow.base.intrinsic_inline_sizes.preferred_inline_size; block_flow.base.block_container_inline_size = self.border_box.size.inline; } - ScannedTextFragment(ref info) => { + SpecificFragmentInfo::ScannedText(ref info) => { // Scanned text fragments will have already had their content inline-sizes assigned // by this point. self.border_box.size.inline = info.content_size.inline + noncontent_inline_size } - ImageFragment(ref mut image_fragment_info) => { + SpecificFragmentInfo::Image(ref mut image_fragment_info) => { // TODO(ksh8281): compute border,margin let inline_size = ImageFragmentInfo::style_length( style_inline_size, @@ -1319,7 +1319,7 @@ impl Fragment { container_inline_size); let inline_size = match inline_size { - Auto => { + MaybeAuto::Auto => { let intrinsic_width = image_fragment_info.image_inline_size(); let intrinsic_height = image_fragment_info.image_block_size(); @@ -1334,8 +1334,8 @@ impl Fragment { image_fragment_info.dom_block_size, Au(0)); let specified_height = match specified_height { - Auto => intrinsic_height, - Specified(h) => h, + MaybeAuto::Auto => intrinsic_height, + MaybeAuto::Specified(h) => h, }; let specified_height = ImageFragmentInfo::clamp_size( specified_height, @@ -1345,7 +1345,7 @@ impl Fragment { Au((specified_height.to_f32().unwrap() * ratio) as i32) } }, - Specified(w) => w, + MaybeAuto::Specified(w) => w, }; let inline_size = ImageFragmentInfo::clamp_size(inline_size, @@ -1366,14 +1366,14 @@ impl Fragment { /// Ideally, this should follow CSS 2.1 § 10.6.2. pub fn assign_replaced_block_size_if_necessary(&mut self, containing_block_block_size: Au) { match self.specific { - GenericFragment | IframeFragment(_) | TableFragment | TableCellFragment | - TableRowFragment | TableWrapperFragment => return, - TableColumnFragment(_) => panic!("Table column fragments do not have block_size"), - UnscannedTextFragment(_) => { + SpecificFragmentInfo::Generic | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | + SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableWrapper => return, + SpecificFragmentInfo::TableColumn(_) => panic!("Table column fragments do not have block_size"), + SpecificFragmentInfo::UnscannedText(_) => { panic!("Unscanned text fragments should have been scanned by now!") } - ImageFragment(_) | ScannedTextFragment(_) | InlineBlockFragment(_) | - InlineAbsoluteHypotheticalFragment(_) => {} + SpecificFragmentInfo::Image(_) | SpecificFragmentInfo::ScannedText(_) | SpecificFragmentInfo::InlineBlock(_) | + SpecificFragmentInfo::InlineAbsoluteHypothetical(_) => {} } let style_block_size = self.style().content_block_size(); @@ -1382,7 +1382,7 @@ impl Fragment { let noncontent_block_size = self.border_padding.block_start_end(); match self.specific { - ImageFragment(ref mut image_fragment_info) => { + SpecificFragmentInfo::Image(ref mut image_fragment_info) => { // TODO(ksh8281): compute border,margin,padding let inline_size = image_fragment_info.computed_inline_size(); let block_size = ImageFragmentInfo::style_length( @@ -1391,13 +1391,13 @@ impl Fragment { containing_block_block_size); let block_size = match block_size { - Auto => { + MaybeAuto::Auto => { let scale = image_fragment_info.image_inline_size().to_f32().unwrap() / inline_size.to_f32().unwrap(); Au((image_fragment_info.image_block_size().to_f32().unwrap() / scale) as i32) }, - Specified(h) => { + MaybeAuto::Specified(h) => { h } }; @@ -1409,18 +1409,18 @@ impl Fragment { image_fragment_info.computed_block_size = Some(block_size); self.border_box.size.block = block_size + noncontent_block_size } - ScannedTextFragment(ref info) => { + SpecificFragmentInfo::ScannedText(ref info) => { // Scanned text fragments' content block-sizes are calculated by the text run // scanner during flow construction. self.border_box.size.block = info.content_size.block + noncontent_block_size } - InlineBlockFragment(ref mut info) => { + SpecificFragmentInfo::InlineBlock(ref mut info) => { // Not the primary fragment, so we do not take the noncontent size into account. let block_flow = info.flow_ref.as_block(); self.border_box.size.block = block_flow.base.position.size.block + block_flow.fragment.margin.block_start_end() } - InlineAbsoluteHypotheticalFragment(ref mut info) => { + SpecificFragmentInfo::InlineAbsoluteHypothetical(ref mut info) => { // Not the primary fragment, so we do not take the noncontent size into account. let block_flow = info.flow_ref.as_block(); self.border_box.size.block = block_flow.base.position.size.block; @@ -1433,7 +1433,7 @@ impl Fragment { /// used in an inline formatting context. See CSS 2.1 § 10.8.1. pub fn inline_metrics(&self, layout_context: &LayoutContext) -> InlineMetrics { match self.specific { - ImageFragment(ref image_fragment_info) => { + SpecificFragmentInfo::Image(ref image_fragment_info) => { let computed_block_size = image_fragment_info.computed_block_size(); InlineMetrics { block_size_above_baseline: computed_block_size + self.border_padding.block_start_end(), @@ -1441,12 +1441,12 @@ impl Fragment { ascent: computed_block_size + self.border_padding.block_end, } } - ScannedTextFragment(ref text_fragment) => { + SpecificFragmentInfo::ScannedText(ref text_fragment) => { // See CSS 2.1 § 10.8.1. let line_height = self.calculate_line_height(layout_context); InlineMetrics::from_font_metrics(&text_fragment.run.font_metrics, line_height) } - InlineBlockFragment(ref info) => { + SpecificFragmentInfo::InlineBlock(ref info) => { // See CSS 2.1 § 10.8.1. let block_flow = info.flow_ref.deref().as_immutable_block(); let font_style = self.style.get_font_arc(); @@ -1456,7 +1456,7 @@ impl Fragment { block_flow.base.position.size.block + block_flow.fragment.margin.block_start_end()) } - InlineAbsoluteHypotheticalFragment(_) => { + SpecificFragmentInfo::InlineAbsoluteHypothetical(_) => { // Hypothetical boxes take up no space. InlineMetrics { block_size_above_baseline: Au(0), @@ -1477,7 +1477,7 @@ impl Fragment { /// Returns true if this fragment is a hypothetical box. See CSS 2.1 § 10.3.7. pub fn is_hypothetical(&self) -> bool { match self.specific { - InlineAbsoluteHypotheticalFragment(_) => true, + SpecificFragmentInfo::InlineAbsoluteHypothetical(_) => true, _ => false, } } @@ -1485,7 +1485,7 @@ impl Fragment { /// Returns true if this fragment can merge with another adjacent fragment or false otherwise. pub fn can_merge_with_fragment(&self, other: &Fragment) -> bool { match (&self.specific, &other.specific) { - (&UnscannedTextFragment(_), &UnscannedTextFragment(_)) => { + (&SpecificFragmentInfo::UnscannedText(_), &SpecificFragmentInfo::UnscannedText(_)) => { // FIXME: Should probably use a whitelist of styles that can safely differ (#3165) self.style().get_font() == other.style().get_font() && self.text_decoration() == other.text_decoration() && @@ -1506,17 +1506,17 @@ impl Fragment { /// because the corresponding table flow is the primary fragment. pub fn is_primary_fragment(&self) -> bool { match self.specific { - InlineBlockFragment(_) | InlineAbsoluteHypotheticalFragment(_) | - TableWrapperFragment => false, - GenericFragment | IframeFragment(_) | ImageFragment(_) | ScannedTextFragment(_) | - TableFragment | TableCellFragment | TableColumnFragment(_) | TableRowFragment | - UnscannedTextFragment(_) => true, + SpecificFragmentInfo::InlineBlock(_) | SpecificFragmentInfo::InlineAbsoluteHypothetical(_) | + SpecificFragmentInfo::TableWrapper => false, + SpecificFragmentInfo::Generic | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Image(_) | SpecificFragmentInfo::ScannedText(_) | + SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | SpecificFragmentInfo::TableColumn(_) | SpecificFragmentInfo::TableRow | + SpecificFragmentInfo::UnscannedText(_) => true, } } pub fn update_late_computed_inline_position_if_necessary(&mut self) { match self.specific { - InlineAbsoluteHypotheticalFragment(ref mut info) => { + SpecificFragmentInfo::InlineAbsoluteHypothetical(ref mut info) => { let position = self.border_box.start.i; info.flow_ref.update_late_computed_inline_position_if_necessary(position) } @@ -1526,7 +1526,7 @@ impl Fragment { pub fn update_late_computed_block_position_if_necessary(&mut self) { match self.specific { - InlineAbsoluteHypotheticalFragment(ref mut info) => { + SpecificFragmentInfo::InlineAbsoluteHypothetical(ref mut info) => { let position = self.border_box.start.b; info.flow_ref.update_late_computed_block_position_if_necessary(position) } diff --git a/components/layout/inline.rs b/components/layout/inline.rs index 370d7e325d9..70b933dcacf 100644 --- a/components/layout/inline.rs +++ b/components/layout/inline.rs @@ -6,13 +6,13 @@ use css::node_style::StyledNode; use context::LayoutContext; -use display_list_builder::{ContentLevel, DisplayListResult, FragmentDisplayListBuilding}; -use floats::{FloatLeft, Floats, PlacementInfo}; -use flow::{BaseFlow, FlowClass, Flow, ForceNonfloated, InlineFlowClass, MutableFlowUtils}; +use display_list_builder::{BackgroundAndBorderLevel, DisplayListBuildingResult, FragmentDisplayListBuilding}; +use floats::{FloatKind, Floats, PlacementInfo}; +use flow::{BaseFlow, FlowClass, Flow, MutableFlowUtils, ForceNonfloatedFlag}; use flow::{IS_ABSOLUTELY_POSITIONED}; use flow; -use fragment::{Fragment, InlineAbsoluteHypotheticalFragment, InlineBlockFragment}; -use fragment::{FragmentBoundsIterator, ScannedTextFragment, ScannedTextFragmentInfo}; +use fragment::{Fragment, SpecificFragmentInfo}; +use fragment::{FragmentBoundsIterator, ScannedTextFragmentInfo}; use fragment::SplitInfo; use incremental::{REFLOW, REFLOW_OUT_OF_FLOW}; use layout_debug; @@ -345,8 +345,8 @@ impl LineBreaker { }; let need_to_merge = match (&mut result.specific, &candidate.specific) { - (&ScannedTextFragment(ref mut result_info), - &ScannedTextFragment(ref candidate_info)) + (&SpecificFragmentInfo::ScannedText(ref mut result_info), + &SpecificFragmentInfo::ScannedText(ref candidate_info)) if arc_ptr_eq(&result_info.run, &candidate_info.run) && result_info.range.end() + CharIndex(1) == candidate_info.range.begin() => { // We found a previously-broken fragment. Merge it up. @@ -412,7 +412,7 @@ impl LineBreaker { first_fragment.border_box.size.block), ceiling: ceiling, max_inline_size: flow.base.position.size.inline, - kind: FloatLeft, + kind: FloatKind::Left, }); // Simple case: if the fragment fits, then we can stop here. @@ -744,7 +744,7 @@ pub struct InlineFlow { impl InlineFlow { pub fn from_fragments(fragments: InlineFragments, writing_mode: WritingMode) -> InlineFlow { InlineFlow { - base: BaseFlow::new(None, writing_mode, ForceNonfloated), + base: BaseFlow::new(None, writing_mode, ForceNonfloatedFlag::ForceNonfloated), fragments: fragments, lines: Vec::new(), minimum_block_size_above_baseline: Au(0), @@ -946,7 +946,7 @@ impl InlineFlow { impl Flow for InlineFlow { fn class(&self) -> FlowClass { - InlineFlowClass + FlowClass::Inline } fn as_immutable_inline<'a>(&'a self) -> &'a InlineFlow { @@ -1188,7 +1188,7 @@ impl Flow for InlineFlow { fn compute_absolute_position(&mut self) { for fragment in self.fragments.fragments.iter_mut() { let stacking_relative_position = match fragment.specific { - InlineBlockFragment(ref mut info) => { + SpecificFragmentInfo::InlineBlock(ref mut info) => { let block_flow = info.flow_ref.as_block(); block_flow.base.absolute_position_info = self.base.absolute_position_info; @@ -1200,7 +1200,7 @@ impl Flow for InlineFlow { container_size); block_flow.base.stacking_relative_position } - InlineAbsoluteHypotheticalFragment(ref mut info) => { + SpecificFragmentInfo::InlineAbsoluteHypothetical(ref mut info) => { let block_flow = info.flow_ref.as_block(); block_flow.base.absolute_position_info = self.base.absolute_position_info; @@ -1220,10 +1220,10 @@ impl Flow for InlineFlow { stacking_relative_position); match fragment.specific { - InlineBlockFragment(ref mut info) => { + SpecificFragmentInfo::InlineBlock(ref mut info) => { flow::mut_base(info.flow_ref.deref_mut()).clip_rect = clip_rect } - InlineAbsoluteHypotheticalFragment(ref mut info) => { + SpecificFragmentInfo::InlineAbsoluteHypothetical(ref mut info) => { flow::mut_base(info.flow_ref.deref_mut()).clip_rect = clip_rect } _ => {} @@ -1246,15 +1246,15 @@ impl Flow for InlineFlow { fragment.build_display_list(&mut *display_list, layout_context, fragment_origin, - ContentLevel, + BackgroundAndBorderLevel::Content, &self.base.clip_rect); match fragment.specific { - InlineBlockFragment(ref mut block_flow) => { + SpecificFragmentInfo::InlineBlock(ref mut block_flow) => { let block_flow = block_flow.flow_ref.deref_mut(); flow::mut_base(block_flow).display_list_building_result .add_to(&mut *display_list) } - InlineAbsoluteHypotheticalFragment(ref mut block_flow) => { + SpecificFragmentInfo::InlineAbsoluteHypothetical(ref mut block_flow) => { let block_flow = block_flow.flow_ref.deref_mut(); flow::mut_base(block_flow).display_list_building_result .add_to(&mut *display_list) @@ -1263,7 +1263,7 @@ impl Flow for InlineFlow { } } - self.base.display_list_building_result = DisplayListResult(display_list); + self.base.display_list_building_result = DisplayListBuildingResult::Normal(display_list); if opts::get().validate_display_list_geometry { self.base.validate_display_list_geometry(); diff --git a/components/layout/layout_task.rs b/components/layout/layout_task.rs index 8203eb9b6a3..4d8885cf8ed 100644 --- a/components/layout/layout_task.rs +++ b/components/layout/layout_task.rs @@ -6,7 +6,7 @@ //! painted. use css::node_style::StyledNode; -use construct::FlowConstructionResult; +use construct::ConstructionResult; use context::SharedLayoutContext; use flow::{mod, Flow, ImmutableFlowUtils, MutableFlowUtils, MutableOwnedFlowUtils}; use flow_ref::FlowRef; @@ -33,8 +33,8 @@ use layout_traits; use layout_traits::{LayoutControlMsg, LayoutTaskFactory}; use log; use script::dom::bindings::js::JS; -use script::dom::node::{ElementNodeTypeId, LayoutDataRef, Node}; -use script::dom::element::{HTMLBodyElementTypeId, HTMLHtmlElementTypeId}; +use script::dom::node::{LayoutDataRef, Node, NodeTypeId}; +use script::dom::element::ElementTypeId; use script::layout_interface::{AddStylesheetMsg, ContentBoxResponse, ContentBoxesResponse}; use script::layout_interface::{ContentBoxesQuery, ContentBoxQuery, ExitNowMsg, GetRPCMsg}; use script::layout_interface::{HitTestResponse, LayoutChan, LayoutRPC, LoadStylesheetMsg}; @@ -54,15 +54,15 @@ use servo_util::opts; use servo_util::smallvec::{SmallVec, SmallVec1, VecLike}; use servo_util::task::spawn_named_with_send_on_failure; use servo_util::task_state; -use servo_util::time::{TimeProfilerChan, profile, TimeRootWindow, TimeIFrame, TimeIncremental, TimeFirstReflow}; +use servo_util::time::{TimeProfilerChan, profile, TimerMetadataFrameType, TimerMetadataReflowType}; use servo_util::time; use servo_util::workqueue::WorkQueue; use std::cell::Cell; use std::comm::{channel, Sender, Receiver, Select}; use std::mem; use std::ptr; -use style::{AuthorOrigin, Stylesheet, Stylist, TNode, iter_font_face_rules}; -use style::{Device, Screen}; +use style::{StylesheetOrigin, Stylesheet, Stylist, TNode, iter_font_face_rules}; +use style::{MediaType, Device}; use sync::{Arc, Mutex, MutexGuard}; use url::Url; @@ -217,8 +217,8 @@ enum RWGuard<'a> { impl<'a> Deref<LayoutTaskData> for RWGuard<'a> { fn deref(&self) -> &LayoutTaskData { match *self { - Held(ref x) => x.deref(), - Used(ref x) => x.deref(), + RWGuard::Held(ref x) => x.deref(), + RWGuard::Used(ref x) => x.deref(), } } } @@ -226,8 +226,8 @@ impl<'a> Deref<LayoutTaskData> for RWGuard<'a> { impl<'a> DerefMut<LayoutTaskData> for RWGuard<'a> { fn deref_mut(&mut self) -> &mut LayoutTaskData { match *self { - Held(ref mut x) => x.deref_mut(), - Used(ref mut x) => x.deref_mut(), + RWGuard::Held(ref mut x) => x.deref_mut(), + RWGuard::Used(ref mut x) => x.deref_mut(), } } } @@ -249,7 +249,7 @@ impl LayoutTask { let local_image_cache = Arc::new(Mutex::new(LocalImageCache::new(image_cache_task.clone()))); let screen_size = Size2D(Au(0), Au(0)); - let device = Device::new(Screen, opts::get().initial_window_size.as_f32() * ScaleFactor(1.0)); + let device = Device::new(MediaType::Screen, opts::get().initial_window_size.as_f32() * ScaleFactor(1.0)); let parallel_traversal = if opts::get().layout_threads != 1 { Some(WorkQueue::new("LayoutWorker", task_state::LAYOUT, opts::get().layout_threads, ptr::null())) @@ -332,23 +332,23 @@ impl LayoutTask { } let ret = sel.wait(); if ret == port1.id() { - Script + PortToRead::Script } else if ret == port2.id() { - Pipeline + PortToRead::Pipeline } else { panic!("invalid select result"); } }; match port_to_read { - Pipeline => { + PortToRead::Pipeline => { match self.pipeline_port.recv() { layout_traits::ExitNowMsg => { self.handle_script_request(ExitNowMsg, possibly_locked_rw_data) } } }, - Script => { + PortToRead::Script => { let msg = self.port.recv(); self.handle_script_request(msg, possibly_locked_rw_data) } @@ -365,8 +365,8 @@ impl LayoutTask { possibly_locked_rw_data: &mut Option<MutexGuard<'a, LayoutTaskData>>) -> RWGuard<'a> { match possibly_locked_rw_data.take() { - None => Used(self.rw_data.lock()), - Some(x) => Held(x), + None => RWGuard::Used(self.rw_data.lock()), + Some(x) => RWGuard::Held(x), } } @@ -376,8 +376,8 @@ impl LayoutTask { fn return_rw_data<'a>(possibly_locked_rw_data: &mut Option<MutexGuard<'a, LayoutTaskData>>, rw_data: RWGuard<'a>) { match rw_data { - Used(x) => drop(x), - Held(x) => *possibly_locked_rw_data = Some(x), + RWGuard::Used(x) => drop(x), + RWGuard::Held(x) => *possibly_locked_rw_data = Some(x), } } @@ -398,8 +398,8 @@ impl LayoutTask { ReflowMsg(data) => { profile(time::LayoutPerformCategory, Some((&data.url, - if data.iframe { TimeIFrame } else { TimeRootWindow }, - if self.first_reflow.get() { TimeFirstReflow } else { TimeIncremental })), + if data.iframe { TimerMetadataFrameType::IFrame } else { TimerMetadataFrameType::RootWindow }, + if self.first_reflow.get() { TimerMetadataReflowType::FirstReflow } else { TimerMetadataReflowType::Incremental })), self.time_profiler_chan.clone(), || self.handle_reflow(&*data, possibly_locked_rw_data)); }, @@ -483,7 +483,7 @@ impl LayoutTask { final_url, protocol_encoding_label, Some(environment_encoding), - AuthorOrigin); + StylesheetOrigin::Author); self.handle_add_stylesheet(sheet, possibly_locked_rw_data); } @@ -522,7 +522,7 @@ impl LayoutTask { let result = layout_data.data.flow_construction_result.swap_out(); let mut flow = match result { - FlowConstructionResult(mut flow, abs_descendants) => { + ConstructionResult::Flow(mut flow, abs_descendants) => { // Note: Assuming that the root has display 'static' (as per // CSS Section 9.3.1). Otherwise, if it were absolutely // positioned, it would return a reference to itself in @@ -574,8 +574,8 @@ impl LayoutTask { // operation out. parallel::traverse_flow_tree_preorder(layout_root, &data.url, - if data.iframe { TimeIFrame } else { TimeRootWindow }, - if self.first_reflow.get() { TimeFirstReflow } else { TimeIncremental }, + if data.iframe { TimerMetadataFrameType::IFrame } else { TimerMetadataFrameType::RootWindow }, + if self.first_reflow.get() { TimerMetadataReflowType::FirstReflow } else { TimerMetadataReflowType::Incremental }, self.time_profiler_chan.clone(), shared_layout_context, traversal); @@ -629,8 +629,8 @@ impl LayoutTask { let writing_mode = flow::base(&**layout_root).writing_mode; profile(time::LayoutDispListBuildCategory, Some((&data.url, - if data.iframe { TimeIFrame } else { TimeRootWindow }, - if self.first_reflow.get() { TimeFirstReflow } else { TimeIncremental })), + if data.iframe { TimerMetadataFrameType::IFrame } else { TimerMetadataFrameType::RootWindow }, + if self.first_reflow.get() { TimerMetadataReflowType::FirstReflow } else { TimerMetadataReflowType::Incremental })), self.time_profiler_chan.clone(), || { shared_layout_ctx.dirty = @@ -650,8 +650,8 @@ impl LayoutTask { Some(ref mut traversal) => { parallel::build_display_list_for_subtree(layout_root, &data.url, - if data.iframe { TimeIFrame } else { TimeRootWindow }, - if self.first_reflow.get() { TimeFirstReflow } else { TimeIncremental }, + if data.iframe { TimerMetadataFrameType::IFrame } else { TimerMetadataFrameType::RootWindow }, + if self.first_reflow.get() { TimerMetadataReflowType::FirstReflow } else { TimerMetadataReflowType::Incremental }, self.time_profiler_chan.clone(), shared_layout_ctx, traversal); @@ -664,8 +664,8 @@ impl LayoutTask { // it with extreme prejudice. let mut color = color::rgba(1.0, 1.0, 1.0, 1.0); for child in node.traverse_preorder() { - if child.type_id() == Some(ElementNodeTypeId(HTMLHtmlElementTypeId)) || - child.type_id() == Some(ElementNodeTypeId(HTMLBodyElementTypeId)) { + if child.type_id() == Some(NodeTypeId::Element(ElementTypeId::HTMLHtmlElement)) || + child.type_id() == Some(NodeTypeId::Element(ElementTypeId::HTMLBodyElement)) { let element_bg_color = { let thread_safe_child = ThreadSafeLayoutNode::new(&child); thread_safe_child.style() @@ -754,7 +754,7 @@ impl LayoutTask { let screen_size_changed = current_screen_size != old_screen_size; if screen_size_changed { - let device = Device::new(Screen, data.window_size.initial_viewport); + let device = Device::new(MediaType::Screen, data.window_size.initial_viewport); rw_data.stylist.set_device(device); } @@ -776,8 +776,8 @@ impl LayoutTask { let mut layout_root = profile(time::LayoutStyleRecalcCategory, Some((&data.url, - if data.iframe { TimeIFrame } else { TimeRootWindow }, - if self.first_reflow.get() { TimeFirstReflow } else { TimeIncremental })), + if data.iframe { TimerMetadataFrameType::IFrame } else { TimerMetadataFrameType::RootWindow }, + if self.first_reflow.get() { TimerMetadataReflowType::FirstReflow } else { TimerMetadataReflowType::Incremental })), self.time_profiler_chan.clone(), || { // Perform CSS selector matching and flow construction. @@ -796,8 +796,8 @@ impl LayoutTask { profile(time::LayoutRestyleDamagePropagation, Some((&data.url, - if data.iframe { TimeIFrame } else { TimeRootWindow }, - if self.first_reflow.get() { TimeFirstReflow } else { TimeIncremental })), + if data.iframe { TimerMetadataFrameType::IFrame } else { TimerMetadataFrameType::RootWindow }, + if self.first_reflow.get() { TimerMetadataReflowType::FirstReflow } else { TimerMetadataReflowType::Incremental })), self.time_profiler_chan.clone(), || { if opts::get().nonincremental_layout || @@ -819,8 +819,8 @@ impl LayoutTask { // the boxes. profile(time::LayoutMainCategory, Some((&data.url, - if data.iframe { TimeIFrame } else { TimeRootWindow }, - if self.first_reflow.get() { TimeFirstReflow } else { TimeIncremental })), + if data.iframe { TimerMetadataFrameType::IFrame } else { TimerMetadataFrameType::RootWindow }, + if self.first_reflow.get() { TimerMetadataReflowType::FirstReflow } else { TimerMetadataReflowType::Incremental })), self.time_profiler_chan.clone(), || { let rw_data = rw_data.deref_mut(); diff --git a/components/layout/list_item.rs b/components/layout/list_item.rs index fbf40c7747c..3b31d1fdc44 100644 --- a/components/layout/list_item.rs +++ b/components/layout/list_item.rs @@ -11,7 +11,7 @@ use block::BlockFlow; use construct::FlowConstructor; use context::LayoutContext; use display_list_builder::ListItemFlowDisplayListBuilding; -use flow::{Flow, FlowClass, ListItemFlowClass}; +use flow::{Flow, FlowClass}; use fragment::{Fragment, FragmentBoundsIterator}; use wrapper::ThreadSafeLayoutNode; @@ -46,7 +46,7 @@ impl ListItemFlow { impl Flow for ListItemFlow { fn class(&self) -> FlowClass { - ListItemFlowClass + FlowClass::ListItem } fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow { diff --git a/components/layout/model.rs b/components/layout/model.rs index 49506b43475..4e4e5cad399 100644 --- a/components/layout/model.rs +++ b/components/layout/model.rs @@ -10,7 +10,7 @@ use fragment::Fragment; use style::computed_values as computed; use geom::SideOffsets2D; -use style::computed_values::{LPA_Auto, LPA_Length, LPA_Percentage, LP_Length, LP_Percentage}; +use style::computed_values::{LengthOrPercentageOrAuto, LengthOrPercentage}; use style::ComputedValues; use servo_util::geometry::Au; use servo_util::logical_geometry::LogicalMargin; @@ -62,26 +62,26 @@ impl AdjoiningMargins { /// Represents the block-start and block-end margins of a flow with collapsible margins. See CSS 2.1 § 8.3.1. pub enum CollapsibleMargins { /// Margins may not collapse with this flow. - NoCollapsibleMargins(Au, Au), + None(Au, Au), /// Both the block-start and block-end margins (specified here in that order) may collapse, but the /// margins do not collapse through this flow. - MarginsCollapse(AdjoiningMargins, AdjoiningMargins), + Collapse(AdjoiningMargins, AdjoiningMargins), /// Margins collapse *through* this flow. This means, essentially, that the flow doesn’t /// have any border, padding, or out-of-flow (floating or positioned) content - MarginsCollapseThrough(AdjoiningMargins), + CollapseThrough(AdjoiningMargins), } impl CollapsibleMargins { pub fn new() -> CollapsibleMargins { - NoCollapsibleMargins(Au(0), Au(0)) + CollapsibleMargins::None(Au(0), Au(0)) } } enum FinalMarginState { - MarginsCollapseThroughFinalMarginState, - BottomMarginCollapsesFinalMarginState, + MarginsCollapseThrough, + BottomMarginCollapses, } pub struct MarginCollapseInfo { @@ -94,7 +94,7 @@ impl MarginCollapseInfo { /// TODO(#2012, pcwalton): Remove this method once `fragment` is not an `Option`. pub fn new() -> MarginCollapseInfo { MarginCollapseInfo { - state: AccumulatingCollapsibleTopMargin, + state: MarginCollapseState::AccumulatingCollapsibleTopMargin, block_start_margin: AdjoiningMargins::new(), margin_in: AdjoiningMargins::new(), } @@ -104,7 +104,7 @@ impl MarginCollapseInfo { fragment: &Fragment, can_collapse_block_start_margin_with_kids: bool) { if !can_collapse_block_start_margin_with_kids { - self.state = AccumulatingMarginIn + self.state = MarginCollapseState::AccumulatingMarginIn } self.block_start_margin = AdjoiningMargins::from_margin(fragment.margin.block_start) @@ -115,28 +115,28 @@ impl MarginCollapseInfo { can_collapse_block_end_margin_with_kids: bool) -> (CollapsibleMargins, Au) { let state = match self.state { - AccumulatingCollapsibleTopMargin => { + MarginCollapseState::AccumulatingCollapsibleTopMargin => { match fragment.style().content_block_size() { - LPA_Auto | LPA_Length(Au(0)) | LPA_Percentage(0.) => { + LengthOrPercentageOrAuto::Auto | LengthOrPercentageOrAuto::Length(Au(0)) | LengthOrPercentageOrAuto::Percentage(0.) => { match fragment.style().min_block_size() { - LP_Length(Au(0)) | LP_Percentage(0.) => { - MarginsCollapseThroughFinalMarginState + LengthOrPercentage::Length(Au(0)) | LengthOrPercentage::Percentage(0.) => { + FinalMarginState::MarginsCollapseThrough }, _ => { // If the fragment has non-zero min-block-size, margins may not // collapse through it. - BottomMarginCollapsesFinalMarginState + FinalMarginState::BottomMarginCollapses } } }, _ => { // If the fragment has an explicitly specified block-size, margins may not // collapse through it. - BottomMarginCollapsesFinalMarginState + FinalMarginState::BottomMarginCollapses } } } - AccumulatingMarginIn => BottomMarginCollapsesFinalMarginState, + MarginCollapseState::AccumulatingMarginIn => FinalMarginState::BottomMarginCollapses, }; // Different logic is needed here depending on whether this flow can collapse its block-end @@ -144,26 +144,26 @@ impl MarginCollapseInfo { let block_end_margin = fragment.margin.block_end; if !can_collapse_block_end_margin_with_kids { match state { - MarginsCollapseThroughFinalMarginState => { + FinalMarginState::MarginsCollapseThrough => { let advance = self.block_start_margin.collapse(); self.margin_in.union(AdjoiningMargins::from_margin(block_end_margin)); - (MarginsCollapse(self.block_start_margin, self.margin_in), advance) + (CollapsibleMargins::Collapse(self.block_start_margin, self.margin_in), advance) } - BottomMarginCollapsesFinalMarginState => { + FinalMarginState::BottomMarginCollapses => { let advance = self.margin_in.collapse(); self.margin_in.union(AdjoiningMargins::from_margin(block_end_margin)); - (MarginsCollapse(self.block_start_margin, self.margin_in), advance) + (CollapsibleMargins::Collapse(self.block_start_margin, self.margin_in), advance) } } } else { match state { - MarginsCollapseThroughFinalMarginState => { + FinalMarginState::MarginsCollapseThrough => { self.block_start_margin.union(AdjoiningMargins::from_margin(block_end_margin)); - (MarginsCollapseThrough(self.block_start_margin), Au(0)) + (CollapsibleMargins::CollapseThrough(self.block_start_margin), Au(0)) } - BottomMarginCollapsesFinalMarginState => { + FinalMarginState::BottomMarginCollapses => { self.margin_in.union(AdjoiningMargins::from_margin(block_end_margin)); - (MarginsCollapse(self.block_start_margin, self.margin_in), Au(0)) + (CollapsibleMargins::Collapse(self.block_start_margin, self.margin_in), Au(0)) } } } @@ -171,8 +171,8 @@ impl MarginCollapseInfo { pub fn current_float_ceiling(&mut self) -> Au { match self.state { - AccumulatingCollapsibleTopMargin => self.block_start_margin.collapse(), - AccumulatingMarginIn => self.margin_in.collapse(), + MarginCollapseState::AccumulatingCollapsibleTopMargin => self.block_start_margin.collapse(), + MarginCollapseState::AccumulatingMarginIn => self.margin_in.collapse(), } } @@ -181,27 +181,27 @@ impl MarginCollapseInfo { /// that should be added to the Y offset during block layout. pub fn advance_block_start_margin(&mut self, child_collapsible_margins: &CollapsibleMargins) -> Au { match (self.state, *child_collapsible_margins) { - (AccumulatingCollapsibleTopMargin, NoCollapsibleMargins(block_start, _)) => { - self.state = AccumulatingMarginIn; + (MarginCollapseState::AccumulatingCollapsibleTopMargin, CollapsibleMargins::None(block_start, _)) => { + self.state = MarginCollapseState::AccumulatingMarginIn; block_start } - (AccumulatingCollapsibleTopMargin, MarginsCollapse(block_start, _)) => { + (MarginCollapseState::AccumulatingCollapsibleTopMargin, CollapsibleMargins::Collapse(block_start, _)) => { self.block_start_margin.union(block_start); - self.state = AccumulatingMarginIn; + self.state = MarginCollapseState::AccumulatingMarginIn; Au(0) } - (AccumulatingMarginIn, NoCollapsibleMargins(block_start, _)) => { + (MarginCollapseState::AccumulatingMarginIn, CollapsibleMargins::None(block_start, _)) => { let previous_margin_value = self.margin_in.collapse(); self.margin_in = AdjoiningMargins::new(); previous_margin_value + block_start } - (AccumulatingMarginIn, MarginsCollapse(block_start, _)) => { + (MarginCollapseState::AccumulatingMarginIn, CollapsibleMargins::Collapse(block_start, _)) => { self.margin_in.union(block_start); let margin_value = self.margin_in.collapse(); self.margin_in = AdjoiningMargins::new(); margin_value } - (_, MarginsCollapseThrough(_)) => { + (_, CollapsibleMargins::CollapseThrough(_)) => { // For now, we ignore this; this will be handled by `advance_block-end_margin` below. Au(0) } @@ -213,23 +213,23 @@ impl MarginCollapseInfo { /// that should be added to the Y offset during block layout. pub fn advance_block_end_margin(&mut self, child_collapsible_margins: &CollapsibleMargins) -> Au { match (self.state, *child_collapsible_margins) { - (AccumulatingCollapsibleTopMargin, NoCollapsibleMargins(..)) | - (AccumulatingCollapsibleTopMargin, MarginsCollapse(..)) => { + (MarginCollapseState::AccumulatingCollapsibleTopMargin, CollapsibleMargins::None(..)) | + (MarginCollapseState::AccumulatingCollapsibleTopMargin, CollapsibleMargins::Collapse(..)) => { // Can't happen because the state will have been replaced with - // `AccumulatingMarginIn` above. + // `MarginCollapseState::AccumulatingMarginIn` above. panic!("should not be accumulating collapsible block_start margins anymore!") } - (AccumulatingCollapsibleTopMargin, MarginsCollapseThrough(margin)) => { + (MarginCollapseState::AccumulatingCollapsibleTopMargin, CollapsibleMargins::CollapseThrough(margin)) => { self.block_start_margin.union(margin); Au(0) } - (AccumulatingMarginIn, NoCollapsibleMargins(_, block_end)) => { + (MarginCollapseState::AccumulatingMarginIn, CollapsibleMargins::None(_, block_end)) => { assert_eq!(self.margin_in.most_positive, Au(0)); assert_eq!(self.margin_in.most_negative, Au(0)); block_end } - (AccumulatingMarginIn, MarginsCollapse(_, block_end)) | - (AccumulatingMarginIn, MarginsCollapseThrough(block_end)) => { + (MarginCollapseState::AccumulatingMarginIn, CollapsibleMargins::Collapse(_, block_end)) | + (MarginCollapseState::AccumulatingMarginIn, CollapsibleMargins::CollapseThrough(block_end)) => { self.margin_in.union(block_end); Au(0) } @@ -333,19 +333,19 @@ impl MaybeAuto { pub fn from_style(length: computed::LengthOrPercentageOrAuto, containing_length: Au) -> MaybeAuto { match length { - computed::LPA_Auto => Auto, - computed::LPA_Percentage(percent) => { - Specified(containing_length.scale_by(percent)) + computed::LengthOrPercentageOrAuto::Auto => MaybeAuto::Auto, + computed::LengthOrPercentageOrAuto::Percentage(percent) => { + MaybeAuto::Specified(containing_length.scale_by(percent)) } - computed::LPA_Length(length) => Specified(length) + computed::LengthOrPercentageOrAuto::Length(length) => MaybeAuto::Specified(length) } } #[inline] pub fn specified_or_default(&self, default: Au) -> Au { match *self { - Auto => default, - Specified(value) => value, + MaybeAuto::Auto => default, + MaybeAuto::Specified(value) => value, } } @@ -357,24 +357,24 @@ impl MaybeAuto { #[inline] pub fn map(&self, mapper: |Au| -> Au) -> MaybeAuto { match *self { - Auto => Auto, - Specified(value) => Specified(mapper(value)), + MaybeAuto::Auto => MaybeAuto::Auto, + MaybeAuto::Specified(value) => MaybeAuto::Specified(mapper(value)), } } } pub fn specified_or_none(length: computed::LengthOrPercentageOrNone, containing_length: Au) -> Option<Au> { match length { - computed::LPN_None => None, - computed::LPN_Percentage(percent) => Some(containing_length.scale_by(percent)), - computed::LPN_Length(length) => Some(length), + computed::LengthOrPercentageOrNone::None => None, + computed::LengthOrPercentageOrNone::Percentage(percent) => Some(containing_length.scale_by(percent)), + computed::LengthOrPercentageOrNone::Length(length) => Some(length), } } pub fn specified(length: computed::LengthOrPercentage, containing_length: Au) -> Au { match length { - computed::LP_Length(length) => length, - computed::LP_Percentage(p) => containing_length.scale_by(p) + computed::LengthOrPercentage::Length(length) => length, + computed::LengthOrPercentage::Percentage(p) => containing_length.scale_by(p) } } diff --git a/components/layout/table.rs b/components/layout/table.rs index 0e2af0b2f68..8f46ef868ff 100644 --- a/components/layout/table.rs +++ b/components/layout/table.rs @@ -6,18 +6,18 @@ #![deny(unsafe_blocks)] -use block::{BlockFlow, MarginsMayNotCollapse, ISizeAndMarginsComputer}; +use block::{BlockFlow, ISizeAndMarginsComputer, MarginsMayCollapseFlag}; use block::{ISizeConstraintInput, ISizeConstraintSolution}; use construct::FlowConstructor; use context::LayoutContext; use floats::FloatKind; use flow::{mod, Flow, FlowClass, IMPACTED_BY_LEFT_FLOATS, IMPACTED_BY_RIGHT_FLOATS}; -use flow::{ImmutableFlowUtils, TableFlowClass}; +use flow::ImmutableFlowUtils; use fragment::{Fragment, FragmentBoundsIterator}; use layout_debug; use model::{IntrinsicISizes, IntrinsicISizesContribution}; use table_row::CellIntrinsicInlineSize; -use table_wrapper::{TableLayout, FixedLayout, AutoLayout}; +use table_wrapper::TableLayout; use wrapper::ThreadSafeLayoutNode; use servo_util::geometry::Au; @@ -25,7 +25,7 @@ use servo_util::logical_geometry::LogicalRect; use std::cmp::max; use std::fmt; use style::{ComputedValues, CSSFloat}; -use style::computed_values::{LPA_Auto, LPA_Length, LPA_Percentage, table_layout}; +use style::computed_values::{LengthOrPercentageOrAuto, table_layout}; use sync::Arc; /// A table flow corresponded to the table's internal table fragment under a table wrapper flow. @@ -54,9 +54,9 @@ impl TableFlow { let mut block_flow = BlockFlow::from_node_and_fragment(node, fragment); let table_layout = if block_flow.fragment().style().get_table().table_layout == table_layout::fixed { - FixedLayout + TableLayout::Fixed } else { - AutoLayout + TableLayout::Auto }; TableFlow { block_flow: block_flow, @@ -72,9 +72,9 @@ impl TableFlow { let mut block_flow = BlockFlow::from_node(constructor, node); let table_layout = if block_flow.fragment().style().get_table().table_layout == table_layout::fixed { - FixedLayout + TableLayout::Fixed } else { - AutoLayout + TableLayout::Auto }; TableFlow { block_flow: block_flow, @@ -91,9 +91,9 @@ impl TableFlow { let mut block_flow = BlockFlow::float_from_node(constructor, node, float_kind); let table_layout = if block_flow.fragment().style().get_table().table_layout == table_layout::fixed { - FixedLayout + TableLayout::Fixed } else { - AutoLayout + TableLayout::Auto }; TableFlow { block_flow: block_flow, @@ -164,7 +164,7 @@ impl TableFlow { /// methods #[inline(always)] fn assign_block_size_table_base<'a>(&mut self, layout_context: &'a LayoutContext<'a>) { - self.block_flow.assign_block_size_block_base(layout_context, MarginsMayNotCollapse); + self.block_flow.assign_block_size_block_base(layout_context, MarginsMayCollapseFlag::MarginsMayNotCollapse); } /// Updates the minimum and preferred inline-size calculation for a single row. This is @@ -181,7 +181,7 @@ impl TableFlow { debug_assert!(child.is_table_row()); let row = child.as_table_row(); match table_layout { - FixedLayout => { + TableLayout::Fixed => { // Fixed table layout only looks at the first row. // // FIXME(pcwalton): This is really inefficient. We should stop after the first row! @@ -192,7 +192,7 @@ impl TableFlow { } } } - AutoLayout => { + TableLayout::Auto => { computation.union_block(&TableFlow::update_automatic_column_inline_sizes( column_inline_sizes, row.cell_intrinsic_inline_sizes.as_slice())) @@ -203,7 +203,7 @@ impl TableFlow { impl Flow for TableFlow { fn class(&self) -> FlowClass { - TableFlowClass + FlowClass::Table } fn as_table<'a>(&'a mut self) -> &'a mut TableFlow { @@ -242,12 +242,12 @@ impl Flow for TableFlow { for specified_inline_size in kid.as_table_colgroup().inline_sizes.iter() { self.column_intrinsic_inline_sizes.push(ColumnIntrinsicInlineSize { minimum_length: match *specified_inline_size { - LPA_Auto | LPA_Percentage(_) => Au(0), - LPA_Length(length) => length, + LengthOrPercentageOrAuto::Auto | LengthOrPercentageOrAuto::Percentage(_) => Au(0), + LengthOrPercentageOrAuto::Length(length) => length, }, percentage: match *specified_inline_size { - LPA_Auto | LPA_Length(_) => 0.0, - LPA_Percentage(percentage) => percentage, + LengthOrPercentageOrAuto::Auto | LengthOrPercentageOrAuto::Length(_) => 0.0, + LengthOrPercentageOrAuto::Percentage(percentage) => percentage, }, preferred: Au(0), constrained: false, @@ -308,7 +308,7 @@ impl Flow for TableFlow { self.block_flow.fragment.border_box.size.inline - padding_and_borders; match self.table_layout { - FixedLayout => { + TableLayout::Fixed => { // In fixed table layout, we distribute extra space among the unspecified columns // if there are any, or among all the columns if all are specified. self.column_computed_inline_sizes.clear(); diff --git a/components/layout/table_caption.rs b/components/layout/table_caption.rs index 210bc8019e7..65493e2c24a 100644 --- a/components/layout/table_caption.rs +++ b/components/layout/table_caption.rs @@ -9,7 +9,7 @@ use block::BlockFlow; use construct::FlowConstructor; use context::LayoutContext; -use flow::{TableCaptionFlowClass, FlowClass, Flow}; +use flow::{FlowClass, Flow}; use fragment::FragmentBoundsIterator; use wrapper::ThreadSafeLayoutNode; @@ -35,7 +35,7 @@ impl TableCaptionFlow { impl Flow for TableCaptionFlow { fn class(&self) -> FlowClass { - TableCaptionFlowClass + FlowClass::TableCaption } fn as_table_caption<'a>(&'a mut self) -> &'a mut TableCaptionFlow { diff --git a/components/layout/table_cell.rs b/components/layout/table_cell.rs index 0a4e7d05e24..45e4ab3a1c3 100644 --- a/components/layout/table_cell.rs +++ b/components/layout/table_cell.rs @@ -6,9 +6,9 @@ #![deny(unsafe_blocks)] -use block::{BlockFlow, MarginsMayNotCollapse, ISizeAndMarginsComputer}; +use block::{BlockFlow, ISizeAndMarginsComputer, MarginsMayCollapseFlag}; use context::LayoutContext; -use flow::{TableCellFlowClass, FlowClass, Flow}; +use flow::{FlowClass, Flow}; use fragment::{Fragment, FragmentBoundsIterator}; use model::{MaybeAuto}; use layout_debug; @@ -17,7 +17,7 @@ use wrapper::ThreadSafeLayoutNode; use servo_util::geometry::Au; use std::fmt; -use style::{ColSpanUnsignedIntegerAttribute, ComputedValues}; +use style::{UnsignedIntegerAttribute, ComputedValues}; use sync::Arc; /// A table formatting context. @@ -34,7 +34,7 @@ impl TableCellFlow { -> TableCellFlow { TableCellFlow { block_flow: BlockFlow::from_node_and_fragment(node, fragment), - column_span: node.get_unsigned_integer_attribute(ColSpanUnsignedIntegerAttribute) + column_span: node.get_unsigned_integer_attribute(UnsignedIntegerAttribute::ColSpanUnsignedIntegerAttribute) .unwrap_or(1), } } @@ -53,13 +53,13 @@ impl TableCellFlow { /// methods. #[inline(always)] fn assign_block_size_table_cell_base<'a>(&mut self, layout_context: &'a LayoutContext<'a>) { - self.block_flow.assign_block_size_block_base(layout_context, MarginsMayNotCollapse) + self.block_flow.assign_block_size_block_base(layout_context, MarginsMayCollapseFlag::MarginsMayNotCollapse) } } impl Flow for TableCellFlow { fn class(&self) -> FlowClass { - TableCellFlowClass + FlowClass::TableCell } fn as_table_cell<'a>(&'a mut self) -> &'a mut TableCellFlow { diff --git a/components/layout/table_colgroup.rs b/components/layout/table_colgroup.rs index e8caa10e88d..5ce9f559268 100644 --- a/components/layout/table_colgroup.rs +++ b/components/layout/table_colgroup.rs @@ -8,8 +8,8 @@ use context::LayoutContext; use css::node_style::StyledNode; -use flow::{BaseFlow, ForceNonfloated, TableColGroupFlowClass, FlowClass, Flow}; -use fragment::{Fragment, FragmentBoundsIterator, TableColumnFragment}; +use flow::{BaseFlow, FlowClass, Flow, ForceNonfloatedFlag}; +use fragment::{Fragment, FragmentBoundsIterator, SpecificFragmentInfo}; use layout_debug; use wrapper::ThreadSafeLayoutNode; @@ -44,7 +44,7 @@ impl TableColGroupFlow { -> TableColGroupFlow { let writing_mode = node.style().writing_mode; TableColGroupFlow { - base: BaseFlow::new(Some((*node).clone()), writing_mode, ForceNonfloated), + base: BaseFlow::new(Some((*node).clone()), writing_mode, ForceNonfloatedFlag::ForceNonfloated), fragment: Some(fragment), cols: fragments, inline_sizes: vec!(), @@ -54,7 +54,7 @@ impl TableColGroupFlow { impl Flow for TableColGroupFlow { fn class(&self) -> FlowClass { - TableColGroupFlowClass + FlowClass::TableColGroup } fn as_table_colgroup<'a>(&'a mut self) -> &'a mut TableColGroupFlow { @@ -69,7 +69,7 @@ impl Flow for TableColGroupFlow { // Retrieve the specified value from the appropriate CSS property. let inline_size = fragment.style().content_inline_size(); let span: int = match fragment.specific { - TableColumnFragment(col_fragment) => max(col_fragment.span, 1), + SpecificFragmentInfo::TableColumn(col_fragment) => max(col_fragment.span, 1), _ => panic!("non-table-column fragment inside table column?!"), }; for _ in range(0, span) { diff --git a/components/layout/table_row.rs b/components/layout/table_row.rs index e50f5b2f33e..d4979de8800 100644 --- a/components/layout/table_row.rs +++ b/components/layout/table_row.rs @@ -10,19 +10,19 @@ use block::BlockFlow; use block::ISizeAndMarginsComputer; use construct::FlowConstructor; use context::LayoutContext; -use flow::{TableRowFlowClass, FlowClass, Flow, ImmutableFlowUtils}; +use flow::{FlowClass, Flow, ImmutableFlowUtils}; use flow; use fragment::{Fragment, FragmentBoundsIterator}; use layout_debug; use table::{ColumnComputedInlineSize, ColumnIntrinsicInlineSize, InternalTable}; -use model::{MaybeAuto, Specified, Auto}; +use model::MaybeAuto; use wrapper::ThreadSafeLayoutNode; use servo_util::geometry::Au; use std::cmp::max; use std::fmt; use style::ComputedValues; -use style::computed_values::{LPA_Auto, LPA_Length, LPA_Percentage}; +use style::computed_values::LengthOrPercentageOrAuto; use sync::Arc; /// A single row of a table. @@ -120,8 +120,8 @@ impl TableRowFlow { .style() .content_block_size(), Au(0)) { - Auto => block_size, - Specified(value) => max(value, block_size) + MaybeAuto::Auto => block_size, + MaybeAuto::Specified(value) => max(value, block_size) }; // cur_y = cur_y + block-size; @@ -149,7 +149,7 @@ impl TableRowFlow { impl Flow for TableRowFlow { fn class(&self) -> FlowClass { - TableRowFlowClass + FlowClass::TableRow } fn as_table_row<'a>(&'a mut self) -> &'a mut TableRowFlow { @@ -205,19 +205,19 @@ impl Flow for TableRowFlow { let child_base = flow::mut_base(kid); let child_column_inline_size = ColumnIntrinsicInlineSize { minimum_length: match child_specified_inline_size { - LPA_Auto | LPA_Percentage(_) => { + LengthOrPercentageOrAuto::Auto | LengthOrPercentageOrAuto::Percentage(_) => { child_base.intrinsic_inline_sizes.minimum_inline_size } - LPA_Length(length) => length, + LengthOrPercentageOrAuto::Length(length) => length, }, percentage: match child_specified_inline_size { - LPA_Auto | LPA_Length(_) => 0.0, - LPA_Percentage(percentage) => percentage, + LengthOrPercentageOrAuto::Auto | LengthOrPercentageOrAuto::Length(_) => 0.0, + LengthOrPercentageOrAuto::Percentage(percentage) => percentage, }, preferred: child_base.intrinsic_inline_sizes.preferred_inline_size, constrained: match child_specified_inline_size { - LPA_Length(_) => true, - LPA_Auto | LPA_Percentage(_) => false, + LengthOrPercentageOrAuto::Length(_) => true, + LengthOrPercentageOrAuto::Auto | LengthOrPercentageOrAuto::Percentage(_) => false, }, }; min_inline_size = min_inline_size + child_column_inline_size.minimum_length; diff --git a/components/layout/table_rowgroup.rs b/components/layout/table_rowgroup.rs index 4f62cd10a75..e004890c53d 100644 --- a/components/layout/table_rowgroup.rs +++ b/components/layout/table_rowgroup.rs @@ -6,10 +6,10 @@ #![deny(unsafe_blocks)] -use block::{BlockFlow, ISizeAndMarginsComputer, MarginsMayNotCollapse}; +use block::{BlockFlow, ISizeAndMarginsComputer, MarginsMayCollapseFlag}; use construct::FlowConstructor; use context::LayoutContext; -use flow::{Flow, FlowClass, TableRowGroupFlowClass}; +use flow::{FlowClass, Flow}; use fragment::{Fragment, FragmentBoundsIterator}; use layout_debug; use table::{ColumnComputedInlineSize, ColumnIntrinsicInlineSize, InternalTable}; @@ -62,13 +62,13 @@ impl TableRowGroupFlow { /// methods. #[inline(always)] fn assign_block_size_table_rowgroup_base<'a>(&mut self, layout_context: &'a LayoutContext<'a>) { - self.block_flow.assign_block_size_block_base(layout_context, MarginsMayNotCollapse) + self.block_flow.assign_block_size_block_base(layout_context, MarginsMayCollapseFlag::MarginsMayNotCollapse) } } impl Flow for TableRowGroupFlow { fn class(&self) -> FlowClass { - TableRowGroupFlowClass + FlowClass::TableRowGroup } fn as_table_rowgroup<'a>(&'a mut self) -> &'a mut TableRowGroupFlow { diff --git a/components/layout/table_wrapper.rs b/components/layout/table_wrapper.rs index 0d785ce1ca3..e3d6433a36f 100644 --- a/components/layout/table_wrapper.rs +++ b/components/layout/table_wrapper.rs @@ -13,12 +13,11 @@ #![deny(unsafe_blocks)] -use block::{BlockFlow, BlockNonReplaced, FloatNonReplaced, ISizeAndMarginsComputer}; -use block::{MarginsMayNotCollapse}; +use block::{BlockFlow, BlockNonReplaced, FloatNonReplaced, ISizeAndMarginsComputer, MarginsMayCollapseFlag}; use construct::FlowConstructor; use context::LayoutContext; use floats::FloatKind; -use flow::{TableWrapperFlowClass, FlowClass, Flow, ImmutableFlowUtils}; +use flow::{FlowClass, Flow, ImmutableFlowUtils}; use flow::{IMPACTED_BY_LEFT_FLOATS, IMPACTED_BY_RIGHT_FLOATS}; use fragment::{Fragment, FragmentBoundsIterator}; use table::{ColumnComputedInlineSize, ColumnIntrinsicInlineSize}; @@ -33,8 +32,8 @@ use sync::Arc; #[deriving(Encodable, Show)] pub enum TableLayout { - FixedLayout, - AutoLayout + Fixed, + Auto } /// A table wrapper flow based on a block formatting context. @@ -56,9 +55,9 @@ impl TableWrapperFlow { let mut block_flow = BlockFlow::from_node_and_fragment(node, fragment); let table_layout = if block_flow.fragment().style().get_table().table_layout == table_layout::fixed { - FixedLayout + TableLayout::Fixed } else { - AutoLayout + TableLayout::Auto }; TableWrapperFlow { block_flow: block_flow, @@ -73,9 +72,9 @@ impl TableWrapperFlow { let mut block_flow = BlockFlow::from_node(constructor, node); let table_layout = if block_flow.fragment().style().get_table().table_layout == table_layout::fixed { - FixedLayout + TableLayout::Fixed } else { - AutoLayout + TableLayout::Auto }; TableWrapperFlow { block_flow: block_flow, @@ -91,9 +90,9 @@ impl TableWrapperFlow { let mut block_flow = BlockFlow::float_from_node_and_fragment(node, fragment, float_kind); let table_layout = if block_flow.fragment().style().get_table().table_layout == table_layout::fixed { - FixedLayout + TableLayout::Fixed } else { - AutoLayout + TableLayout::Auto }; TableWrapperFlow { block_flow: block_flow, @@ -158,7 +157,7 @@ impl TableWrapperFlow { // FIXME(pcwalton, spec): How do I deal with fractional excess? let excess_inline_size = available_inline_size - total_used_inline_size; if excess_inline_size > Au(0) && - selection == UsePreferredGuessAndDistributeExcessInlineSize { + selection == SelectedAutoLayoutCandidateGuess::UsePreferredGuessAndDistributeExcessInlineSize { let mut info = ExcessInlineSizeDistributionInfo::new(); for column_intrinsic_inline_size in self.column_intrinsic_inline_sizes.iter() { info.update(column_intrinsic_inline_size) @@ -214,7 +213,7 @@ impl TableWrapperFlow { impl Flow for TableWrapperFlow { fn class(&self) -> FlowClass { - TableWrapperFlowClass + FlowClass::TableWrapper } fn as_table_wrapper<'a>(&'a mut self) -> &'a mut TableWrapperFlow { @@ -274,8 +273,8 @@ impl Flow for TableWrapperFlow { self.compute_used_inline_size(layout_context, containing_block_inline_size); match self.table_layout { - FixedLayout => {} - AutoLayout => { + TableLayout::Fixed => {} + TableLayout::Auto => { self.calculate_table_column_sizes_for_automatic_layout( intermediate_column_inline_sizes.as_mut_slice()) } @@ -286,8 +285,8 @@ impl Flow for TableWrapperFlow { // In case of fixed layout, column inline-sizes are calculated in table flow. let assigned_column_inline_sizes = match self.table_layout { - FixedLayout => None, - AutoLayout => { + TableLayout::Fixed => None, + TableLayout::Auto => { Some(intermediate_column_inline_sizes.iter().map(|sizes| { ColumnComputedInlineSize { size: sizes.size, @@ -317,7 +316,7 @@ impl Flow for TableWrapperFlow { fn assign_block_size<'a>(&mut self, ctx: &'a LayoutContext<'a>) { debug!("assign_block_size: assigning block_size for table_wrapper"); - self.block_flow.assign_block_size_block_base(ctx, MarginsMayNotCollapse); + self.block_flow.assign_block_size_block_base(ctx, MarginsMayCollapseFlag::MarginsMayNotCollapse); } fn compute_absolute_position(&mut self) { @@ -449,17 +448,17 @@ impl AutoLayoutCandidateGuess { /// This does *not* distribute excess inline-size. That must be done later if necessary. fn calculate(&self, selection: SelectedAutoLayoutCandidateGuess) -> Au { match selection { - UseMinimumGuess => self.minimum_guess, - InterpolateBetweenMinimumGuessAndMinimumPercentageGuess(weight) => { + SelectedAutoLayoutCandidateGuess::UseMinimumGuess => self.minimum_guess, + SelectedAutoLayoutCandidateGuess::InterpolateBetweenMinimumGuessAndMinimumPercentageGuess(weight) => { interp(self.minimum_guess, self.minimum_percentage_guess, weight) } - InterpolateBetweenMinimumPercentageGuessAndMinimumSpecifiedGuess(weight) => { + SelectedAutoLayoutCandidateGuess::InterpolateBetweenMinimumPercentageGuessAndMinimumSpecifiedGuess(weight) => { interp(self.minimum_percentage_guess, self.minimum_specified_guess, weight) } - InterpolateBetweenMinimumSpecifiedGuessAndPreferredGuess(weight) => { + SelectedAutoLayoutCandidateGuess::InterpolateBetweenMinimumSpecifiedGuessAndPreferredGuess(weight) => { interp(self.minimum_specified_guess, self.preferred_guess, weight) } - UsePreferredGuessAndDistributeExcessInlineSize => { + SelectedAutoLayoutCandidateGuess::UsePreferredGuessAndDistributeExcessInlineSize => { self.preferred_guess } } @@ -498,24 +497,24 @@ impl SelectedAutoLayoutCandidateGuess { fn select(guess: &AutoLayoutCandidateGuess, assignable_inline_size: Au) -> SelectedAutoLayoutCandidateGuess { if assignable_inline_size < guess.minimum_guess { - UseMinimumGuess + SelectedAutoLayoutCandidateGuess::UseMinimumGuess } else if assignable_inline_size < guess.minimum_percentage_guess { let weight = weight(guess.minimum_guess, assignable_inline_size, guess.minimum_percentage_guess); - InterpolateBetweenMinimumGuessAndMinimumPercentageGuess(weight) + SelectedAutoLayoutCandidateGuess::InterpolateBetweenMinimumGuessAndMinimumPercentageGuess(weight) } else if assignable_inline_size < guess.minimum_specified_guess { let weight = weight(guess.minimum_percentage_guess, assignable_inline_size, guess.minimum_specified_guess); - InterpolateBetweenMinimumPercentageGuessAndMinimumSpecifiedGuess(weight) + SelectedAutoLayoutCandidateGuess::InterpolateBetweenMinimumPercentageGuessAndMinimumSpecifiedGuess(weight) } else if assignable_inline_size < guess.preferred_guess { let weight = weight(guess.minimum_specified_guess, assignable_inline_size, guess.preferred_guess); - InterpolateBetweenMinimumSpecifiedGuessAndPreferredGuess(weight) + SelectedAutoLayoutCandidateGuess::InterpolateBetweenMinimumSpecifiedGuessAndPreferredGuess(weight) } else { - UsePreferredGuessAndDistributeExcessInlineSize + SelectedAutoLayoutCandidateGuess::UsePreferredGuessAndDistributeExcessInlineSize } } } diff --git a/components/layout/text.rs b/components/layout/text.rs index ca837bf6117..ab53aa9a7f9 100644 --- a/components/layout/text.rs +++ b/components/layout/text.rs @@ -6,7 +6,7 @@ #![deny(unsafe_blocks)] -use fragment::{Fragment, ScannedTextFragmentInfo, UnscannedTextFragment}; +use fragment::{Fragment, SpecificFragmentInfo, ScannedTextFragmentInfo}; use inline::InlineFragments; use gfx::font::{FontMetrics, IGNORE_LIGATURES_SHAPING_FLAG, RunMetrics, ShapingFlags}; @@ -85,7 +85,7 @@ impl TextRunScanner { debug_assert!(!self.clump.is_empty()); match self.clump.front().unwrap().specific { - UnscannedTextFragment(_) => {} + SpecificFragmentInfo::UnscannedText(_) => {} _ => { debug_assert!(self.clump.len() == 1, "WAT: can't coalesce non-text nodes in flush_clump_to_list()!"); @@ -126,7 +126,7 @@ impl TextRunScanner { let mut run_text = String::new(); for in_fragment in self.clump.iter() { let in_fragment = match in_fragment.specific { - UnscannedTextFragment(ref text_fragment_info) => &text_fragment_info.text, + SpecificFragmentInfo::UnscannedText(ref text_fragment_info) => &text_fragment_info.text, _ => panic!("Expected an unscanned text fragment!"), }; @@ -181,7 +181,7 @@ impl TextRunScanner { mem::replace(&mut self.clump, DList::new()).into_iter().enumerate() { let range = *new_ranges.get(logical_offset); if range.is_empty() { - debug!("Elided an `UnscannedTextFragment` because it was zero-length after \ + debug!("Elided an `SpecificFragmentInfo::UnscannedText` because it was zero-length after \ compression; {}", old_fragment); continue diff --git a/components/layout/traversal.rs b/components/layout/traversal.rs index 26036ea4d46..4b824160902 100644 --- a/components/layout/traversal.rs +++ b/components/layout/traversal.rs @@ -5,7 +5,7 @@ //! Traversals over the DOM and flow trees, running the layout computations. use css::node_style::StyledNode; -use css::matching::{ApplicableDeclarations, CannotShare, MatchMethods, StyleWasShared}; +use css::matching::{ApplicableDeclarations, MatchMethods, StyleSharingResult}; use construct::FlowConstructor; use context::LayoutContext; use flow::{Flow, MutableFlowUtils}; @@ -152,7 +152,7 @@ impl<'a> PreorderDomTraversal for RecalcStyleForNode<'a> { }; // Otherwise, match and cascade selectors. match sharing_result { - CannotShare(mut shareable) => { + StyleSharingResult::CannotShare(mut shareable) => { let mut applicable_declarations = ApplicableDeclarations::new(); if node.is_element() { @@ -178,7 +178,7 @@ impl<'a> PreorderDomTraversal for RecalcStyleForNode<'a> { style_sharing_candidate_cache.insert_if_possible(&node); } } - StyleWasShared(index, damage) => { + StyleSharingResult::StyleWasShared(index, damage) => { style_sharing_candidate_cache.touch(index); ThreadSafeLayoutNode::new(&node).set_restyle_damage(damage); } diff --git a/components/layout/util.rs b/components/layout/util.rs index 2cefcac302b..368182e6c9e 100644 --- a/components/layout/util.rs +++ b/components/layout/util.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 construct::{ConstructionResult, NoConstructionResult}; +use construct::ConstructionResult; use incremental::RestyleDamage; use parallel::DomParallelInfo; use wrapper::{LayoutNode, TLayoutNode, ThreadSafeLayoutNode}; @@ -54,9 +54,9 @@ impl PrivateLayoutData { before_style: None, after_style: None, restyle_damage: RestyleDamage::empty(), - flow_construction_result: NoConstructionResult, - before_flow_construction_result: NoConstructionResult, - after_flow_construction_result: NoConstructionResult, + flow_construction_result: ConstructionResult::None, + before_flow_construction_result: ConstructionResult::None, + after_flow_construction_result: ConstructionResult::None, parallel: DomParallelInfo::new(), flags: LayoutDataFlags::empty(), } diff --git a/components/layout/wrapper.rs b/components/layout/wrapper.rs index 9517e7a2d45..e17f8ea4242 100644 --- a/components/layout/wrapper.rs +++ b/components/layout/wrapper.rs @@ -42,13 +42,13 @@ use script::dom::bindings::codegen::InheritTypes::{ElementCast, HTMLIFrameElemen use script::dom::bindings::codegen::InheritTypes::{HTMLImageElementCast, HTMLInputElementCast}; use script::dom::bindings::codegen::InheritTypes::{HTMLTextAreaElementCast, NodeCast, TextCast}; use script::dom::bindings::js::JS; -use script::dom::element::{Element, HTMLAreaElementTypeId, HTMLAnchorElementTypeId}; -use script::dom::element::{HTMLLinkElementTypeId, LayoutElementHelpers, RawLayoutElementHelpers}; +use script::dom::element::{Element, ElementTypeId}; +use script::dom::element::{LayoutElementHelpers, RawLayoutElementHelpers}; use script::dom::htmliframeelement::HTMLIFrameElement; use script::dom::htmlimageelement::LayoutHTMLImageElementHelpers; use script::dom::htmlinputelement::LayoutHTMLInputElementHelpers; use script::dom::htmltextareaelement::LayoutHTMLTextAreaElementHelpers; -use script::dom::node::{DocumentNodeTypeId, ElementNodeTypeId, Node, NodeTypeId}; +use script::dom::node::{Node, NodeTypeId}; use script::dom::node::{LayoutNodeHelpers, RawLayoutNodeHelpers, SharedLayoutData}; use script::dom::node::{HAS_CHANGED, IS_DIRTY, HAS_DIRTY_SIBLINGS, HAS_DIRTY_DESCENDANTS}; use script::dom::text::Text; @@ -59,8 +59,8 @@ use std::kinds::marker::ContravariantLifetime; use std::mem; use string_cache::{Atom, Namespace}; use style::computed_values::{content, display, white_space}; -use style::{AnyNamespace, AttrSelector, BorderUnsignedIntegerAttribute, IntegerAttribute}; -use style::{LengthAttribute, PropertyDeclarationBlock, SimpleColorAttribute, SpecificNamespace}; +use style::{NamespaceConstraint, AttrSelector, IntegerAttribute}; +use style::{LengthAttribute, PropertyDeclarationBlock, SimpleColorAttribute}; use style::{TElement, TElementAttributes, TNode, UnsignedIntegerAttribute}; use url::Url; @@ -87,14 +87,14 @@ pub trait TLayoutNode { fn node_is_element(&self) -> bool { match self.type_id() { - Some(ElementNodeTypeId(..)) => true, + Some(NodeTypeId::Element(..)) => true, _ => false } } fn node_is_document(&self) -> bool { match self.type_id() { - Some(DocumentNodeTypeId(..)) => true, + Some(NodeTypeId::Document(..)) => true, _ => false } } @@ -201,7 +201,7 @@ impl<'ln> TLayoutNode for LayoutNode<'ln> { impl<'ln> LayoutNode<'ln> { /// Creates a new layout node, scoped to the given closure. - pub unsafe fn with_layout_node<R>(node: JS<Node>, f: <'a> |LayoutNode<'a>| -> R) -> R { + pub unsafe fn with_layout_node<R>(node: JS<Node>, f: for <'a> |LayoutNode<'a>| -> R) -> R { f(LayoutNode { node: node, chain: ContravariantLifetime, @@ -375,11 +375,11 @@ impl<'ln> TNode<'ln, LayoutElement<'ln>> for LayoutNode<'ln> { &attr.name }; match attr.namespace { - SpecificNamespace(ref ns) => { + NamespaceConstraint::Specific(ref ns) => { let element = self.as_element(); element.get_attr(ns, name).map_or(false, |attr| test(attr)) }, - AnyNamespace => { + NamespaceConstraint::Any => { let element = self.as_element(); element.get_attrs(name).iter().any(|attr| test(*attr)) } @@ -516,9 +516,9 @@ impl<'le> TElement<'le> for LayoutElement<'le> { match NodeCast::from_actual(self.element).type_id_for_layout() { // http://www.whatwg.org/specs/web-apps/current-work/multipage/selectors.html# // selector-link - ElementNodeTypeId(HTMLAnchorElementTypeId) | - ElementNodeTypeId(HTMLAreaElementTypeId) | - ElementNodeTypeId(HTMLLinkElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLAnchorElement) | + NodeTypeId::Element(ElementTypeId::HTMLAreaElement) | + NodeTypeId::Element(ElementTypeId::HTMLLinkElement) => { unsafe { self.element.get_attr_val_for_layout(&ns!(""), &atom!("href")) } @@ -594,7 +594,7 @@ impl<'le> TElement<'le> for LayoutElement<'le> { fn has_nonzero_border(self) -> bool { unsafe { match self.element - .get_unsigned_integer_attribute_for_layout(BorderUnsignedIntegerAttribute) { + .get_unsigned_integer_attribute_for_layout(UnsignedIntegerAttribute::BorderUnsignedIntegerAttribute) { None | Some(0) => false, _ => true, } @@ -651,14 +651,14 @@ pub enum PseudoElementType { impl PseudoElementType { pub fn is_before(&self) -> bool { match *self { - Before(_) => true, + PseudoElementType::Before(_) => true, _ => false, } } pub fn is_after(&self) -> bool { match *self { - After(_) => true, + PseudoElementType::After(_) => true, _ => false, } } @@ -682,13 +682,13 @@ impl<'ln> TLayoutNode for ThreadSafeLayoutNode<'ln> { node: node.transmute_copy(), chain: self.node.chain, }, - pseudo: Normal, + pseudo: PseudoElementType::Normal, } } /// Returns `None` if this is a pseudo-element. fn type_id(&self) -> Option<NodeTypeId> { - if self.pseudo != Normal { + if self.pseudo != PseudoElementType::Normal { return None } @@ -704,20 +704,20 @@ impl<'ln> TLayoutNode for ThreadSafeLayoutNode<'ln> { } fn first_child(&self) -> Option<ThreadSafeLayoutNode<'ln>> { - if self.pseudo != Normal { + if self.pseudo != PseudoElementType::Normal { return None } if self.has_before_pseudo() { // FIXME(pcwalton): This logic looks weird. Is it right? match self.pseudo { - Normal => { - let pseudo_before_node = self.with_pseudo(Before(self.get_before_display())); + PseudoElementType::Normal => { + let pseudo_before_node = self.with_pseudo(PseudoElementType::Before(self.get_before_display())); return Some(pseudo_before_node) } - Before(display::inline) => {} - Before(_) => { - let pseudo_before_node = self.with_pseudo(Before(display::inline)); + PseudoElementType::Before(display::inline) => {} + PseudoElementType::Before(_) => { + let pseudo_before_node = self.with_pseudo(PseudoElementType::Before(display::inline)); return Some(pseudo_before_node) } _ => {} @@ -730,7 +730,7 @@ impl<'ln> TLayoutNode for ThreadSafeLayoutNode<'ln> { } fn text(&self) -> String { - if self.pseudo != Normal { + if self.pseudo != PseudoElementType::Normal { let layout_data_ref = self.borrow_layout_data(); let node_layout_data_wrapper = layout_data_ref.as_ref().unwrap(); @@ -751,7 +751,7 @@ impl<'ln> ThreadSafeLayoutNode<'ln> { pub fn new<'a>(node: &LayoutNode<'a>) -> ThreadSafeLayoutNode<'a> { ThreadSafeLayoutNode { node: node.clone(), - pseudo: Normal, + pseudo: PseudoElementType::Normal, } } @@ -1019,7 +1019,7 @@ impl<'a> Iterator<ThreadSafeLayoutNode<'a>> for ThreadSafeLayoutNodeChildrenIter match self.parent_node { Some(ref parent_node) => { - if parent_node.pseudo == Normal { + if parent_node.pseudo == PseudoElementType::Normal { self.current_node = self.current_node.clone().and_then(|node| { unsafe { node.next_sibling() @@ -1036,8 +1036,8 @@ impl<'a> Iterator<ThreadSafeLayoutNode<'a>> for ThreadSafeLayoutNodeChildrenIter match self.parent_node { Some(ref parent_node) => { if parent_node.has_after_pseudo() { - let pseudo_after_node = if parent_node.pseudo == Normal { - let pseudo = After(parent_node.get_after_display()); + let pseudo_after_node = if parent_node.pseudo == PseudoElementType::Normal { + let pseudo = PseudoElementType::After(parent_node.get_after_display()); Some(parent_node.with_pseudo(pseudo)) } else { None diff --git a/components/msg/constellation_msg.rs b/components/msg/constellation_msg.rs index 9b2a654310c..531b39360e5 100644 --- a/components/msg/constellation_msg.rs +++ b/components/msg/constellation_msg.rs @@ -60,127 +60,127 @@ pub enum KeyState { //N.B. Straight up copied from glfw-rs #[deriving(Show)] pub enum Key { - KeySpace, - KeyApostrophe, - KeyComma, - KeyMinus, - KeyPeriod, - KeySlash, - Key0, - Key1, - Key2, - Key3, - Key4, - Key5, - Key6, - Key7, - Key8, - Key9, - KeySemicolon, - KeyEqual, - KeyA, - KeyB, - KeyC, - KeyD, - KeyE, - KeyF, - KeyG, - KeyH, - KeyI, - KeyJ, - KeyK, - KeyL, - KeyM, - KeyN, - KeyO, - KeyP, - KeyQ, - KeyR, - KeyS, - KeyT, - KeyU, - KeyV, - KeyW, - KeyX, - KeyY, - KeyZ, - KeyLeftBracket, - KeyBackslash, - KeyRightBracket, - KeyGraveAccent, - KeyWorld1, - KeyWorld2, - - KeyEscape, - KeyEnter, - KeyTab, - KeyBackspace, - KeyInsert, - KeyDelete, - KeyRight, - KeyLeft, - KeyDown, - KeyUp, - KeyPageUp, - KeyPageDown, - KeyHome, - KeyEnd, - KeyCapsLock, - KeyScrollLock, - KeyNumLock, - KeyPrintScreen, - KeyPause, - KeyF1, - KeyF2, - KeyF3, - KeyF4, - KeyF5, - KeyF6, - KeyF7, - KeyF8, - KeyF9, - KeyF10, - KeyF11, - KeyF12, - KeyF13, - KeyF14, - KeyF15, - KeyF16, - KeyF17, - KeyF18, - KeyF19, - KeyF20, - KeyF21, - KeyF22, - KeyF23, - KeyF24, - KeyF25, - KeyKp0, - KeyKp1, - KeyKp2, - KeyKp3, - KeyKp4, - KeyKp5, - KeyKp6, - KeyKp7, - KeyKp8, - KeyKp9, - KeyKpDecimal, - KeyKpDivide, - KeyKpMultiply, - KeyKpSubtract, - KeyKpAdd, - KeyKpEnter, - KeyKpEqual, - KeyLeftShift, - KeyLeftControl, - KeyLeftAlt, - KeyLeftSuper, - KeyRightShift, - KeyRightControl, - KeyRightAlt, - KeyRightSuper, - KeyMenu, + Space, + Apostrophe, + Comma, + Minus, + Period, + Slash, + Num0, + Num1, + Num2, + Num3, + Num4, + Num5, + Num6, + Num7, + Num8, + Num9, + Semicolon, + Equal, + A, + B, + C, + D, + E, + F, + G, + H, + I, + J, + K, + L, + M, + N, + O, + P, + Q, + R, + S, + T, + U, + V, + W, + X, + Y, + Z, + LeftBracket, + Backslash, + RightBracket, + GraveAccent, + World1, + World2, + + Escape, + Enter, + Tab, + Backspace, + Insert, + Delete, + Right, + Left, + Down, + Up, + PageUp, + PageDown, + Home, + End, + CapsLock, + ScrollLock, + NumLock, + PrintScreen, + Pause, + F1, + F2, + F3, + F4, + F5, + F6, + F7, + F8, + F9, + F10, + F11, + F12, + F13, + F14, + F15, + F16, + F17, + F18, + F19, + F20, + F21, + F22, + F23, + F24, + F25, + Kp0, + Kp1, + Kp2, + Kp3, + Kp4, + Kp5, + Kp6, + Kp7, + Kp8, + Kp9, + KpDecimal, + KpDivide, + KpMultiply, + KpSubtract, + KpAdd, + KpEnter, + KpEqual, + LeftShift, + LeftControl, + LeftAlt, + LeftSuper, + RightShift, + RightControl, + RightAlt, + RightSuper, + Menu, } bitflags! { diff --git a/components/net/Cargo.toml b/components/net/Cargo.toml index f6f2c1abdf5..55d0676a71b 100644 --- a/components/net/Cargo.toml +++ b/components/net/Cargo.toml @@ -25,3 +25,6 @@ git = "https://github.com/servo/rust-stb-image" [dependencies.url] git = "https://github.com/servo/rust-url" + +[dependencies.time] +git = "https://github.com/rust-lang/time" diff --git a/components/net/about_loader.rs b/components/net/about_loader.rs index f8867cd5479..0a5f2c30ada 100644 --- a/components/net/about_loader.rs +++ b/components/net/about_loader.rs @@ -2,14 +2,16 @@ * 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_task::{TargetedLoadResponse, Metadata, Done, LoadData, start_sending, ResponseSenders}; +use resource_task::{TargetedLoadResponse, Metadata, LoadData, start_sending, ResponseSenders}; +use resource_task::ProgressMsg::Done; use file_loader; -use std::io::fs::PathExtensions; use url::Url; use hyper::http::RawStatus; use servo_util::resource_files::resources_dir_path; +use std::io::fs::PathExtensions; +use std::str::Slice; pub fn factory(mut load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) { let senders = ResponseSenders { @@ -23,7 +25,7 @@ pub fn factory(mut load_data: LoadData, start_chan: Sender<TargetedLoadResponse> content_type: Some(("text".to_string(), "html".to_string())), charset: Some("utf-8".to_string()), headers: None, - status: Some(RawStatus(200, "OK".into_string())) + status: Some(RawStatus(200, Slice("OK"))) }); chan.send(Done(Ok(()))); return diff --git a/components/net/data_loader.rs b/components/net/data_loader.rs index 8f9f551f5dc..b24c58e4b71 100644 --- a/components/net/data_loader.rs +++ b/components/net/data_loader.rs @@ -2,12 +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/. */ -use resource_task::{Done, Payload, Metadata, LoadData, TargetedLoadResponse, start_sending, ResponseSenders}; +use resource_task::{Metadata, LoadData, TargetedLoadResponse, start_sending, ResponseSenders}; +use resource_task::ProgressMsg::{Payload, Done}; use serialize::base64::FromBase64; use hyper::mime::Mime; -use url::{percent_decode, NonRelativeSchemeData}; +use url::{percent_decode, SchemeData}; pub fn factory(load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) { @@ -31,7 +32,7 @@ fn load(load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) { // Split out content type and data. let mut scheme_data = match url.scheme_data { - NonRelativeSchemeData(scheme_data) => scheme_data, + SchemeData::NonRelative(scheme_data) => scheme_data, _ => panic!("Expected a non-relative scheme URL.") }; match url.query { diff --git a/components/net/fetch/cors_cache.rs b/components/net/fetch/cors_cache.rs index b287e7999fe..70ae8af3faf 100644 --- a/components/net/fetch/cors_cache.rs +++ b/components/net/fetch/cors_cache.rs @@ -9,6 +9,9 @@ //! This library will eventually become the core of the Fetch crate //! with CORSRequest being expanded into FetchRequest (etc) +use self::CORSCacheTaskMsg::*; +use self::HeaderOrMethod::*; + use hyper::method::Method; use std::ascii::AsciiExt; use std::comm::{Sender, Receiver, channel}; diff --git a/components/net/fetch/request.rs b/components/net/fetch/request.rs index aa53337516b..9265cc540ee 100644 --- a/components/net/fetch/request.rs +++ b/components/net/fetch/request.rs @@ -2,6 +2,12 @@ * 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 self::ContextFrameType::*; +use self::CredentialsMode::*; +use self::Referer::*; +use self::RequestMode::*; +use self::ResponseTainting::*; + use url::Url; use hyper::method::{Get, Method}; use hyper::mime::{Mime, Text, Html, Charset, Utf8}; diff --git a/components/net/fetch/response.rs b/components/net/fetch/response.rs index 48a2794aed3..ffa32b14356 100644 --- a/components/net/fetch/response.rs +++ b/components/net/fetch/response.rs @@ -2,6 +2,9 @@ * 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 self::ResponseBody::*; +use self::ResponseType::*; + use url::Url; use hyper::status::StatusCode; use hyper::status::Ok as StatusOk; diff --git a/components/net/file_loader.rs b/components/net/file_loader.rs index cda398c6880..aa127f806d6 100644 --- a/components/net/file_loader.rs +++ b/components/net/file_loader.rs @@ -2,7 +2,8 @@ * 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_task::{ProgressMsg, Metadata, Payload, Done, LoadData, start_sending, TargetedLoadResponse, ResponseSenders}; +use resource_task::{ProgressMsg, Metadata, LoadData, start_sending, TargetedLoadResponse, ResponseSenders}; +use resource_task::ProgressMsg::{Payload, Done}; use std::io; use std::io::File; diff --git a/components/net/http_loader.rs b/components/net/http_loader.rs index 79a7dca25a1..7dde743a936 100644 --- a/components/net/http_loader.rs +++ b/components/net/http_loader.rs @@ -2,7 +2,8 @@ * 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_task::{Metadata, Payload, Done, TargetedLoadResponse, LoadData, start_sending_opt, ResponseSenders}; +use resource_task::{Metadata, TargetedLoadResponse, LoadData, start_sending_opt, ResponseSenders}; +use resource_task::ProgressMsg::{Payload, Done}; use log; use std::collections::HashSet; diff --git a/components/net/image/holder.rs b/components/net/image/holder.rs index 4703f2cecd9..7010b0bd245 100644 --- a/components/net/image/holder.rs +++ b/components/net/image/holder.rs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use image::base::Image; -use image_cache_task::{ImageReady, ImageNotReady, ImageFailed}; +use image_cache_task::ImageResponseMsg::*; use local_image_cache::LocalImageCache; use geom::size::Size2D; diff --git a/components/net/image_cache_task.rs b/components/net/image_cache_task.rs index 663842adb5e..73a6e5c6cb8 100644 --- a/components/net/image_cache_task.rs +++ b/components/net/image_cache_task.rs @@ -2,9 +2,15 @@ * 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 self::AfterPrefetch::*; +use self::ImageResponseMsg::*; +use self::ImageState::*; +use self::Msg::*; + use image::base::{Image, load_from_memory}; use resource_task; use resource_task::{LoadData, ResourceTask}; +use resource_task::ProgressMsg::{Payload, Done}; use servo_util::task::spawn_named; use servo_util::taskpool::TaskPool; @@ -443,20 +449,20 @@ impl ImageCacheTask { fn load_image_data(url: Url, resource_task: ResourceTask) -> Result<Vec<u8>, ()> { let (response_chan, response_port) = channel(); - resource_task.send(resource_task::Load(LoadData::new(url, response_chan))); + resource_task.send(resource_task::ControlMsg::Load(LoadData::new(url, response_chan))); let mut image_data = vec!(); let progress_port = response_port.recv().progress_port; loop { match progress_port.recv() { - resource_task::Payload(data) => { + Payload(data) => { image_data.push_all(data.as_slice()); } - resource_task::Done(result::Ok(..)) => { + Done(result::Ok(..)) => { return Ok(image_data); } - resource_task::Done(result::Err(..)) => { + Done(result::Err(..)) => { return Err(()); } } @@ -479,9 +485,12 @@ pub fn spawn_listener<A: Send>(f: proc(Receiver<A>):Send) -> Sender<A> { #[cfg(test)] mod tests { use super::*; + use super::ImageResponseMsg::*; + use super::Msg::*; use resource_task; use resource_task::{ResourceTask, Metadata, start_sending, ResponseSenders}; + use resource_task::ProgressMsg::{Payload, Done}; use sniffer_task; use image::base::test_image_bin; use servo_util::taskpool::TaskPool; @@ -500,31 +509,31 @@ mod tests { impl Closure for JustSendOK { fn invoke(&self, response: Sender<resource_task::ProgressMsg>) { self.url_requested_chan.send(()); - response.send(resource_task::Done(Ok(()))); + response.send(Done(Ok(()))); } } struct SendTestImage; impl Closure for SendTestImage { fn invoke(&self, response: Sender<resource_task::ProgressMsg>) { - response.send(resource_task::Payload(test_image_bin())); - response.send(resource_task::Done(Ok(()))); + response.send(Payload(test_image_bin())); + response.send(Done(Ok(()))); } } struct SendBogusImage; impl Closure for SendBogusImage { fn invoke(&self, response: Sender<resource_task::ProgressMsg>) { - response.send(resource_task::Payload(vec!())); - response.send(resource_task::Done(Ok(()))); + response.send(Payload(vec!())); + response.send(Done(Ok(()))); } } struct SendTestImageErr; impl Closure for SendTestImageErr { fn invoke(&self, response: Sender<resource_task::ProgressMsg>) { - response.send(resource_task::Payload(test_image_bin())); - response.send(resource_task::Done(Err("".to_string()))); + response.send(Payload(test_image_bin())); + response.send(Done(Err("".to_string()))); } } @@ -536,8 +545,8 @@ mod tests { // Don't send the data until after the client requests // the image self.wait_port.recv(); - response.send(resource_task::Payload(test_image_bin())); - response.send(resource_task::Done(Ok(()))); + response.send(Payload(test_image_bin())); + response.send(Done(Ok(()))); } } @@ -549,8 +558,8 @@ mod tests { // Don't send the data until after the client requests // the image self.wait_port.recv(); - response.send(resource_task::Payload(test_image_bin())); - response.send(resource_task::Done(Err("".to_string()))); + response.send(Payload(test_image_bin())); + response.send(Done(Err("".to_string()))); } } @@ -558,7 +567,7 @@ mod tests { spawn_listener(proc(port: Receiver<resource_task::ControlMsg>) { loop { match port.recv() { - resource_task::Load(response) => { + resource_task::ControlMsg::Load(response) => { let sniffer_task = sniffer_task::new_sniffer_task(); let senders = ResponseSenders { immediate_consumer: sniffer_task, @@ -568,7 +577,7 @@ mod tests { Url::parse("file:///fake").unwrap())); on_load.invoke(chan); } - resource_task::Exit => break + resource_task::ControlMsg::Exit => break } } }) @@ -581,7 +590,7 @@ mod tests { let image_cache_task = ImageCacheTask::new(mock_resource_task.clone(), TaskPool::new(4)); image_cache_task.exit(); - mock_resource_task.send(resource_task::Exit); + mock_resource_task.send(resource_task::ControlMsg::Exit); } #[test] @@ -609,7 +618,7 @@ mod tests { image_cache_task.send(Prefetch(url)); url_requested.recv(); image_cache_task.exit(); - mock_resource_task.send(resource_task::Exit); + mock_resource_task.send(resource_task::ControlMsg::Exit); } #[test] @@ -625,7 +634,7 @@ mod tests { image_cache_task.send(Prefetch(url)); url_requested.recv(); image_cache_task.exit(); - mock_resource_task.send(resource_task::Exit); + mock_resource_task.send(resource_task::ControlMsg::Exit); match url_requested.try_recv() { Err(_) => (), Ok(_) => panic!(), @@ -648,7 +657,7 @@ mod tests { assert!(response_port.recv() == ImageNotReady); wait_chan.send(()); image_cache_task.exit(); - mock_resource_task.send(resource_task::Exit); + mock_resource_task.send(resource_task::ControlMsg::Exit); } #[test] @@ -674,7 +683,7 @@ mod tests { } image_cache_task.exit(); - mock_resource_task.send(resource_task::Exit); + mock_resource_task.send(resource_task::ControlMsg::Exit); } #[test] @@ -702,7 +711,7 @@ mod tests { } image_cache_task.exit(); - mock_resource_task.send(resource_task::Exit); + mock_resource_task.send(resource_task::ControlMsg::Exit); } #[test] @@ -714,7 +723,7 @@ mod tests { let mock_resource_task = spawn_listener(proc(port: Receiver<resource_task::ControlMsg>) { loop { match port.recv() { - resource_task::Load(response) => { + resource_task::ControlMsg::Load(response) => { let sniffer_task = sniffer_task::new_sniffer_task(); let senders = ResponseSenders { immediate_consumer: sniffer_task, @@ -722,11 +731,11 @@ mod tests { }; let chan = start_sending(senders, Metadata::default( Url::parse("file:///fake").unwrap())); - chan.send(resource_task::Payload(test_image_bin())); - chan.send(resource_task::Done(Ok(()))); + chan.send(Payload(test_image_bin())); + chan.send(Done(Ok(()))); image_bin_sent_chan.send(()); } - resource_task::Exit => { + resource_task::ControlMsg::Exit => { resource_task_exited_chan.send(()); break } @@ -745,7 +754,7 @@ mod tests { image_cache_task.send(Prefetch(url.clone())); image_cache_task.exit(); - mock_resource_task.send(resource_task::Exit); + mock_resource_task.send(resource_task::ControlMsg::Exit); resource_task_exited.recv(); @@ -766,7 +775,7 @@ mod tests { let mock_resource_task = spawn_listener(proc(port: Receiver<resource_task::ControlMsg>) { loop { match port.recv() { - resource_task::Load(response) => { + resource_task::ControlMsg::Load(response) => { let sniffer_task = sniffer_task::new_sniffer_task(); let senders = ResponseSenders { immediate_consumer: sniffer_task, @@ -774,11 +783,11 @@ mod tests { }; let chan = start_sending(senders, Metadata::default( Url::parse("file:///fake").unwrap())); - chan.send(resource_task::Payload(test_image_bin())); - chan.send(resource_task::Done(Err("".to_string()))); + chan.send(Payload(test_image_bin())); + chan.send(Done(Err("".to_string()))); image_bin_sent_chan.send(()); } - resource_task::Exit => { + resource_task::ControlMsg::Exit => { resource_task_exited_chan.send(()); break } @@ -799,7 +808,7 @@ mod tests { image_cache_task.send(Decode(url.clone())); image_cache_task.exit(); - mock_resource_task.send(resource_task::Exit); + mock_resource_task.send(resource_task::ControlMsg::Exit); resource_task_exited.recv(); @@ -834,7 +843,7 @@ mod tests { } image_cache_task.exit(); - mock_resource_task.send(resource_task::Exit); + mock_resource_task.send(resource_task::ControlMsg::Exit); } #[test] @@ -868,7 +877,7 @@ mod tests { } image_cache_task.exit(); - mock_resource_task.send(resource_task::Exit); + mock_resource_task.send(resource_task::ControlMsg::Exit); } #[test] @@ -896,7 +905,7 @@ mod tests { } image_cache_task.exit(); - mock_resource_task.send(resource_task::Exit); + mock_resource_task.send(resource_task::ControlMsg::Exit); } #[test] @@ -922,7 +931,7 @@ mod tests { } image_cache_task.exit(); - mock_resource_task.send(resource_task::Exit); + mock_resource_task.send(resource_task::ControlMsg::Exit); } #[test] @@ -948,7 +957,7 @@ mod tests { } image_cache_task.exit(); - mock_resource_task.send(resource_task::Exit); + mock_resource_task.send(resource_task::ControlMsg::Exit); } #[test] @@ -974,7 +983,7 @@ mod tests { } image_cache_task.exit(); - mock_resource_task.send(resource_task::Exit); + mock_resource_task.send(resource_task::ControlMsg::Exit); } #[test] @@ -995,6 +1004,6 @@ mod tests { } image_cache_task.exit(); - mock_resource_task.send(resource_task::Exit); + mock_resource_task.send(resource_task::ControlMsg::Exit); } } diff --git a/components/net/local_image_cache.rs b/components/net/local_image_cache.rs index 089f7c6b237..f1c303d4062 100644 --- a/components/net/local_image_cache.rs +++ b/components/net/local_image_cache.rs @@ -8,8 +8,9 @@ extra message traffic, it also avoids waiting on the same image multiple times and thus triggering reflows multiple times. */ -use image_cache_task::{Decode, GetImage, ImageCacheTask, ImageFailed, ImageNotReady, ImageReady}; -use image_cache_task::{ImageResponseMsg, Prefetch, WaitForImage}; +use image_cache_task::{ImageCacheTask, ImageResponseMsg}; +use image_cache_task::ImageResponseMsg::*; +use image_cache_task::Msg::*; use std::comm::{Receiver, channel}; use std::collections::HashMap; diff --git a/components/net/resource_task.rs b/components/net/resource_task.rs index 0c473d42676..6a0aeb7306f 100644 --- a/components/net/resource_task.rs +++ b/components/net/resource_task.rs @@ -4,6 +4,9 @@ //! A task that takes a URL and streams back the binary data. +use self::ControlMsg::*; +use self::ProgressMsg::*; + use about_loader; use data_loader; use file_loader; @@ -11,16 +14,17 @@ use http_loader; use sniffer_task; use sniffer_task::SnifferTask; -use std::comm::{channel, Receiver, Sender}; -use hyper::mime::{Mime, Charset}; -use hyper::header::Headers; +use servo_util::task::spawn_named; + use hyper::header::common::UserAgent; +use hyper::header::Headers; +use hyper::http::RawStatus; use hyper::method::{Method, Get}; +use hyper::mime::{Mime, Charset}; use url::Url; -use hyper::http::RawStatus; - -use servo_util::task::spawn_named; +use std::comm::{channel, Receiver, Sender}; +use std::str::Slice; pub enum ControlMsg { /// Request the data associated with a particular URL @@ -85,7 +89,7 @@ impl Metadata { content_type: None, charset: None, headers: None, - status: Some(RawStatus(200, "OK".into_string())) // http://fetch.spec.whatwg.org/#concept-response-status-message + status: Some(RawStatus(200, Slice("OK"))) // http://fetch.spec.whatwg.org/#concept-response-status-message } } diff --git a/components/net/storage_task.rs b/components/net/storage_task.rs index 73e721c9255..85f087bc19a 100644 --- a/components/net/storage_task.rs +++ b/components/net/storage_task.rs @@ -1,6 +1,9 @@ /* 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 self::StorageTaskMsg::*; + use std::comm::{channel, Receiver, Sender}; use std::collections::HashMap; use std::collections::TreeMap; diff --git a/components/plugins/lints.rs b/components/plugins/lints.rs index a467ae7c91f..c48eeed9c80 100644 --- a/components/plugins/lints.rs +++ b/components/plugins/lints.rs @@ -75,7 +75,6 @@ impl LintPass for TransmutePass { // TODO (#3874, sort of): unwrap other types like Vec/Option/HashMap/etc fn lint_unrooted_ty(cx: &Context, ty: &ast::Ty, warning: &str) { match ty.node { - ast::TyUniq(ref t) | ast::TyVec(ref t) | ast::TyFixedLengthVec(ref t, _) | ast::TyPtr(ast::MutTy { ty: ref t, ..}) | ast::TyRptr(_, ast::MutTy { ty: ref t, ..}) => lint_unrooted_ty(cx, &**t, warning), ast::TyPath(_, _, id) => { diff --git a/components/script/Cargo.toml b/components/script/Cargo.toml index e9d049ca265..88074db8320 100644 --- a/components/script/Cargo.toml +++ b/components/script/Cargo.toml @@ -47,7 +47,6 @@ git = "https://github.com/servo/rust-geom" [dependencies.html5ever] git = "https://github.com/servo/html5ever" -branch = "servo" [dependencies.encoding] git = "https://github.com/lifthrasiir/rust-encoding" @@ -70,3 +69,6 @@ git = "https://github.com/servo/string-cache" [dependencies.string_cache_macros] git = "https://github.com/servo/string-cache" + +[dependencies.time] +git = "https://github.com/rust-lang/time" diff --git a/components/script/cors.rs b/components/script/cors.rs index 4b217508978..6b83bd889e9 100644 --- a/components/script/cors.rs +++ b/components/script/cors.rs @@ -23,7 +23,7 @@ use hyper::header::common::{ContentType, Host}; use hyper::method::{Method, Get, Head, Post, Options}; use hyper::status::Success; -use url::{RelativeSchemeData, Url}; +use url::{SchemeData, Url}; #[deriving(Clone)] pub struct CORSRequest { @@ -42,8 +42,8 @@ pub struct CORSRequest { /// `same-origin` and `no CORS` modes are unnecessary for XHR. #[deriving(PartialEq, Clone)] pub enum RequestMode { - CORSMode, // CORS - ForcedPreflightMode // CORS-with-forced-preflight + CORS, // CORS + ForcedPreflight // CORS-with-forced-preflight } impl CORSRequest { @@ -60,7 +60,7 @@ impl CORSRequest { // we can fetch a data URL normally. about:blank can also be fetched by XHR "http" | "https" => { let mut req = CORSRequest::new(referer, destination, mode, method, headers); - req.preflight_flag = !is_simple_method(&req.method) || mode == ForcedPreflightMode; + req.preflight_flag = !is_simple_method(&req.method) || mode == RequestMode::ForcedPreflight; if req.headers.iter().all(|h| is_simple_header(&h)) { req.preflight_flag = true; } @@ -73,7 +73,7 @@ impl CORSRequest { fn new(mut referer: Url, destination: Url, mode: RequestMode, method: Method, headers: Headers) -> CORSRequest { match referer.scheme_data { - RelativeSchemeData(ref mut data) => data.path = vec!(), + SchemeData::Relative(ref mut data) => data.path = vec!(), _ => {} }; referer.fragment = None; @@ -91,7 +91,7 @@ impl CORSRequest { /// http://fetch.spec.whatwg.org/#concept-http-fetch /// This method assumes that the CORS flag is set /// This does not perform the full HTTP fetch, rather it handles part of the CORS filtering - /// if self.mode is ForcedPreflightMode, then the CORS-with-forced-preflight + /// if self.mode is ForcedPreflight, then the CORS-with-forced-preflight /// fetch flag is set as well pub fn http_fetch(&self) -> CORSResponse { let response = CORSResponse::new(); @@ -103,7 +103,7 @@ impl CORSRequest { if self.preflight_flag && !cache.match_method(self, &self.method) && !self.headers.iter().all(|h| is_simple_header(&h) && cache.match_header(self, h.name())) { - if !is_simple_method(&self.method) || self.mode == ForcedPreflightMode { + if !is_simple_method(&self.method) || self.mode == RequestMode::ForcedPreflight { return self.preflight_fetch(); // Everything after this is part of XHR::fetch() // Expect the organization of code to improve once we have a fetch crate @@ -170,7 +170,7 @@ impl CORSRequest { }; // Substep 4 let methods_substep4 = [self.method.clone()]; - if methods.len() == 0 || preflight.mode == ForcedPreflightMode { + if methods.len() == 0 || preflight.mode == RequestMode::ForcedPreflight { methods = methods_substep4.as_slice(); } // Substep 5 @@ -201,14 +201,14 @@ impl CORSRequest { let cache_match = cache.match_method_and_update(self, m, max_age); if !cache_match { cache.insert(CORSCacheEntry::new(self.origin.clone(), self.destination.clone(), - max_age, false, MethodData(m.clone()))); + max_age, false, HeaderOrMethod::MethodData(m.clone()))); } } for h in response.headers.iter() { let cache_match = cache.match_header_and_update(self, h.name(), max_age); if !cache_match { cache.insert(CORSCacheEntry::new(self.origin.clone(), self.destination.clone(), - max_age, false, HeaderData(h.to_string()))); + max_age, false, HeaderOrMethod::HeaderData(h.to_string()))); } } cors_response @@ -254,14 +254,14 @@ pub enum HeaderOrMethod { impl HeaderOrMethod { fn match_header(&self, header_name: &str) -> bool { match *self { - HeaderData(ref s) => s.as_slice().eq_ignore_ascii_case(header_name), + HeaderOrMethod::HeaderData(ref s) => s.as_slice().eq_ignore_ascii_case(header_name), _ => false } } fn match_method(&self, method: &Method) -> bool { match *self { - MethodData(ref m) => m == method, + HeaderOrMethod::MethodData(ref m) => m == method, _ => false } } @@ -484,9 +484,9 @@ impl Header for AccessControlAllowOrigin { if raw.len() == 1 { from_utf8(raw[0].as_slice()).and_then(|s| { if s == "*" { - Some(AllowStar) + Some(AccessControlAllowOrigin::AllowStar) } else { - Url::parse(s).ok().map(|url| AllowOrigin(url)) + Url::parse(s).ok().map(|url| AccessControlAllowOrigin::AllowOrigin(url)) } }) } else { @@ -498,8 +498,8 @@ impl Header for AccessControlAllowOrigin { impl HeaderFormat for AccessControlAllowOrigin { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - AllowStar => "*".fmt(f), - AllowOrigin(ref url) => url.fmt(f) + AccessControlAllowOrigin::AllowStar => "*".fmt(f), + AccessControlAllowOrigin::AllowOrigin(ref url) => url.fmt(f) } } } @@ -531,8 +531,8 @@ impl HeaderFormat for AccessControlMaxAge { pub fn allow_cross_origin_request(req: &CORSRequest, headers: &Headers) -> bool { //FIXME(seanmonstar): use req.headers.get::<AccessControlAllowOrigin>() match headers.get() { - Some(&AllowStar) => true, // Not always true, depends on credentials mode - Some(&AllowOrigin(ref url)) => + Some(&AccessControlAllowOrigin::AllowStar) => true, // Not always true, depends on credentials mode + Some(&AccessControlAllowOrigin::AllowOrigin(ref url)) => url.scheme == req.origin.scheme && url.host() == req.origin.host() && url.port() == req.origin.port(), diff --git a/components/script/devtools.rs b/components/script/devtools.rs index a829a68293f..c92098db2be 100644 --- a/components/script/devtools.rs +++ b/components/script/devtools.rs @@ -4,8 +4,8 @@ use devtools_traits; use devtools_traits::{EvaluateJSReply, NodeInfo, Modification}; -use dom::bindings::conversions; use dom::bindings::conversions::FromJSValConvertible; +use dom::bindings::conversions::StringificationBehavior; use dom::bindings::js::{JSRef, Temporary, OptionalRootable}; use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast}; use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; @@ -36,7 +36,7 @@ pub fn handle_evaluate_js(page: &Rc<Page>, pipeline: PipelineId, eval: String, r devtools_traits::NumberValue(FromJSValConvertible::from_jsval(cx, rval, ()).unwrap()) } else if rval.is_string() { //FIXME: use jsstring_to_str when jsval grows to_jsstring - devtools_traits::StringValue(FromJSValConvertible::from_jsval(cx, rval, conversions::Default).unwrap()) + devtools_traits::StringValue(FromJSValConvertible::from_jsval(cx, rval, StringificationBehavior::Default).unwrap()) } else if rval.is_null() { devtools_traits::NullValue } else { diff --git a/components/script/dom/attr.rs b/components/script/dom/attr.rs index 34d8e121375..01074b42ac9 100644 --- a/components/script/dom/attr.rs +++ b/components/script/dom/attr.rs @@ -30,32 +30,32 @@ pub enum AttrSettingType { #[deriving(PartialEq, Clone)] #[jstraceable] pub enum AttrValue { - StringAttrValue(DOMString), - TokenListAttrValue(DOMString, Vec<Atom>), - UIntAttrValue(DOMString, u32), - AtomAttrValue(Atom), + String(DOMString), + TokenList(DOMString, Vec<Atom>), + UInt(DOMString, u32), + Atom(Atom), } impl AttrValue { pub fn from_tokenlist(tokens: DOMString) -> AttrValue { let atoms = split_html_space_chars(tokens.as_slice()) .map(|token| Atom::from_slice(token)).collect(); - TokenListAttrValue(tokens, atoms) + AttrValue::TokenList(tokens, atoms) } pub fn from_u32(string: DOMString, default: u32) -> AttrValue { let result: u32 = from_str(string.as_slice()).unwrap_or(default); - UIntAttrValue(string, result) + AttrValue::UInt(string, result) } pub fn from_atomic(string: DOMString) -> AttrValue { let value = Atom::from_slice(string.as_slice()); - AtomAttrValue(value) + AttrValue::Atom(value) } pub fn tokens<'a>(&'a self) -> Option<&'a [Atom]> { match *self { - TokenListAttrValue(_, ref tokens) => Some(tokens.as_slice()), + AttrValue::TokenList(_, ref tokens) => Some(tokens.as_slice()), _ => None } } @@ -64,10 +64,10 @@ impl AttrValue { impl Str for AttrValue { fn as_slice<'a>(&'a self) -> &'a str { match *self { - StringAttrValue(ref value) | - TokenListAttrValue(ref value, _) | - UIntAttrValue(ref value, _) => value.as_slice(), - AtomAttrValue(ref value) => value.as_slice(), + AttrValue::String(ref value) | + AttrValue::TokenList(ref value, _) | + AttrValue::UInt(ref value, _) => value.as_slice(), + AttrValue::Atom(ref value) => value.as_slice(), } } } @@ -141,12 +141,12 @@ impl<'a> AttrMethods for JSRef<'a, Attr> { fn SetValue(self, value: DOMString) { match self.owner { None => { - *self.value.borrow_mut() = StringAttrValue(value) + *self.value.borrow_mut() = AttrValue::String(value) } Some(o) => { let owner = o.root(); let value = owner.parse_attribute(&self.namespace, self.local_name(), value); - self.set_value(ReplacedAttr, value, *owner); + self.set_value(AttrSettingType::ReplacedAttr, value, *owner); } } } @@ -207,7 +207,8 @@ impl<'a> AttrHelpers<'a> for JSRef<'a, Attr> { let namespace_is_null = self.namespace == ns!(""); match set_type { - ReplacedAttr if namespace_is_null => vtable_for(&node).before_remove_attr(self), + AttrSettingType::ReplacedAttr if namespace_is_null => + vtable_for(&node).before_remove_attr(self), _ => () } @@ -255,7 +256,7 @@ impl AttrHelpersForLayout for Attr { unsafe fn value_atom_forever(&self) -> Option<Atom> { let value = self.value.borrow_for_layout(); match *value { - AtomAttrValue(ref val) => Some(val.clone()), + AttrValue::Atom(ref val) => Some(val.clone()), _ => None, } } @@ -265,7 +266,7 @@ impl AttrHelpersForLayout for Attr { // This transmute is used to cheat the lifetime restriction. let value = mem::transmute::<&AttrValue, &AttrValue>(self.value.borrow_for_layout()); match *value { - TokenListAttrValue(_, ref tokens) => Some(tokens.as_slice()), + AttrValue::TokenList(_, ref tokens) => Some(tokens.as_slice()), _ => None, } } diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 5ad8ab8b1b4..4a760225cf4 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -425,7 +425,7 @@ def typeNeedsRooting(type, descriptorProvider): def union_native_type(t): name = t.unroll().name - return 'UnionTypes::%s::%s' % (name, name) + return 'UnionTypes::%s' % name def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None, @@ -741,7 +741,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None, if defaultValue is not None: assert(defaultValue.type.tag() == IDLType.Tags.domstring) - default = "%sValues::%s" % (enum, getEnumValueName(defaultValue.value)) + default = "%s::%s" % (enum, getEnumValueName(defaultValue.value)) else: default = None @@ -1419,11 +1419,11 @@ class CGNamespace(CGWrapper): def DOMClass(descriptor): protoList = ['PrototypeList::id::' + proto for proto in descriptor.prototypeChain] - # Pad out the list to the right length with IDCount so we - # guarantee that all the lists are the same length. IDCount + # Pad out the list to the right length with id::Count so we + # guarantee that all the lists are the same length. id::Count # is never the ID of any prototype, so it's safe to use as # padding. - protoList.extend(['PrototypeList::id::IDCount'] * (descriptor.config.maxProtoChainLength - len(protoList))) + protoList.extend(['PrototypeList::id::Count'] * (descriptor.config.maxProtoChainLength - len(protoList))) prototypeChainString = ', '.join(protoList) return """DOMClass { interface_chain: [ %s ], @@ -1673,7 +1673,7 @@ def UnionTypes(descriptors, dictionaries, callbacks, config): 'dom::bindings::codegen::PrototypeList', 'dom::bindings::conversions::FromJSValConvertible', 'dom::bindings::conversions::ToJSValConvertible', - 'dom::bindings::conversions::Default', + 'dom::bindings::conversions::StringificationBehavior::Default', 'dom::bindings::error::throw_not_in_union', 'dom::bindings::js::JS', 'dom::types::*', @@ -1693,14 +1693,12 @@ def UnionTypes(descriptors, dictionaries, callbacks, config): name = str(t) if not name in unionStructs: provider = descriptor or config.getDescriptorProvider() - unionStructs[name] = CGNamespace(name, - CGImports(CGList([ - CGUnionStruct(t, provider), - CGUnionConversionStruct(t, provider) - ]), [], imports), - public=True) + unionStructs[name] = CGList([ + CGUnionStruct(t, provider), + CGUnionConversionStruct(t, provider) + ]) - return CGList(SortedDictValues(unionStructs), "\n\n") + return CGImports(CGList(SortedDictValues(unionStructs), "\n\n"), [], imports) class Argument(): @@ -1889,7 +1887,7 @@ class CGIDLInterface(CGThing): } return string.Template(""" impl IDLInterface for ${type} { - fn get_prototype_id(_: Option<${type}>) -> PrototypeList::id::ID { + fn get_prototype_id(_: Option<${type}>) -> PrototypeList::id { PrototypeList::id::${type} } fn get_prototype_depth(_: Option<${type}>) -> uint { @@ -2753,35 +2751,36 @@ def getEnumValueName(value): class CGEnum(CGThing): def __init__(self, enum): CGThing.__init__(self) - inner = """ -use dom::bindings::conversions::ToJSValConvertible; -use js::jsapi::JSContext; -use js::jsval::JSVal; + decl = """ #[repr(uint)] #[deriving(PartialEq)] #[jstraceable] -pub enum valuelist { +pub enum %s { %s } +""" % (enum.identifier.name, ",\n ".join(map(getEnumValueName, enum.values()))) + + inner = """ +use dom::bindings::conversions::ToJSValConvertible; +use js::jsapi::JSContext; +use js::jsval::JSVal; pub const strings: &'static [&'static str] = &[ %s, ]; -impl ToJSValConvertible for valuelist { +impl ToJSValConvertible for super::%s { fn to_jsval(&self, cx: *mut JSContext) -> JSVal { strings[*self as uint].to_string().to_jsval(cx) } } -""" % (",\n ".join(map(getEnumValueName, enum.values())), - ",\n ".join(['"%s"' % val for val in enum.values()])) +""" % (",\n ".join(['"%s"' % val for val in enum.values()]), enum.identifier.name) self.cgRoot = CGList([ + CGGeneric(decl), CGNamespace.build([enum.identifier.name + "Values"], CGIndenter(CGGeneric(inner)), public=True), - CGGeneric("pub type %s = self::%sValues::valuelist;\n" % - (enum.identifier.name, enum.identifier.name)), ]) def define(self): @@ -2876,7 +2875,7 @@ class CGUnionStruct(CGThing): " e%s(%s)," % (v["name"], v["typeName"]) for v in templateVars ] enumConversions = [ - " e%s(ref inner) => inner.to_jsval(cx)," % v["name"] for v in templateVars + " %s::e%s(ref inner) => inner.to_jsval(cx)," % (self.type, v["name"]) for v in templateVars ] # XXXManishearth The following should be #[must_root], # however we currently allow it till #2661 is fixed @@ -2922,9 +2921,9 @@ class CGUnionConversionStruct(CGThing): return ( "match %s::TryConvertTo%s(cx, value) {\n" " Err(_) => return Err(()),\n" - " Ok(Some(value)) => return Ok(e%s(value)),\n" + " Ok(Some(value)) => return Ok(%s::e%s(value)),\n" " Ok(None) => (),\n" - "}\n") % (self.type, name, name) + "}\n") % (self.type, name, self.type, name) typeNames = [get_name(memberType) for memberType in interfaceMemberTypes] interfaceObject = CGList(CGGeneric(get_match(typeName)) for typeName in typeNames) @@ -2990,9 +2989,9 @@ class CGUnionConversionStruct(CGThing): match = ( "match %s::TryConvertTo%s(cx, value) {\n" " Err(_) => return Err(()),\n" - " Ok(Some(value)) => return Ok(e%s(value)),\n" + " Ok(Some(value)) => return Ok(%s::e%s(value)),\n" " Ok(None) => (),\n" - "}\n") % (self.type, name, name) + "}\n") % (self.type, name, self.type, name) conversions.append(CGGeneric(match)) names.append(name) @@ -4182,8 +4181,8 @@ class CGDescriptor(CGThing): def define(self): return self.cgRoot.define() -class CGNamespacedEnum(CGThing): - def __init__(self, namespace, enumName, names, values, comment="", deriving=""): +class CGNonNamespacedEnum(CGThing): + def __init__(self, enumName, names, values, comment="", deriving=""): if not values: values = [] @@ -4198,7 +4197,7 @@ class CGNamespacedEnum(CGThing): entries.append(entry) # Append a Count. - entries.append(enumName + 'Count = ' + str(len(entries))) + entries.append('Count = ' + str(len(entries))) # Indent. entries = [' ' + e for e in entries] @@ -4212,9 +4211,6 @@ class CGNamespacedEnum(CGThing): # Add some whitespace padding. curr = CGWrapper(curr, pre='\n',post='\n') - # Add the namespace. - curr = CGNamespace(namespace, curr, public=True) - # Add the typedef #typedef = '\ntypedef %s::%s %s;\n\n' % (namespace, enumName, enumName) #curr = CGList([curr, CGGeneric(typedef)]) @@ -4504,23 +4500,25 @@ class CGBindingRoot(CGThing): 'dom::bindings::utils::{DOMJSClass, JSCLASS_DOM_GLOBAL}', 'dom::bindings::utils::{FindEnumStringIndex, GetArrayIndexFromId}', 'dom::bindings::utils::{GetPropertyOnPrototype, GetProtoOrIfaceArray}', - 'dom::bindings::utils::{HasPropertyOnPrototype, IntVal, UintVal}', + 'dom::bindings::utils::HasPropertyOnPrototype', 'dom::bindings::utils::{Reflectable}', 'dom::bindings::utils::{squirrel_away_unique}', 'dom::bindings::utils::{ThrowingConstructor, unwrap, unwrap_jsmanaged}', 'dom::bindings::utils::get_dictionary_property', 'dom::bindings::utils::{NativeProperties, NativePropertyHooks}', + 'dom::bindings::utils::ConstantVal::{IntVal, UintVal}', 'dom::bindings::trace::JSTraceable', 'dom::bindings::callback::{CallbackContainer,CallbackInterface,CallbackFunction}', 'dom::bindings::callback::{CallSetup,ExceptionHandling}', 'dom::bindings::callback::{WrapCallThisObject}', 'dom::bindings::conversions::{FromJSValConvertible, ToJSValConvertible}', 'dom::bindings::conversions::IDLInterface', - 'dom::bindings::conversions::{Default, Empty}', 'dom::bindings::conversions::jsid_to_str', + 'dom::bindings::conversions::StringificationBehavior::{Default, Empty}', 'dom::bindings::codegen::{PrototypeList, RegisterBindings, UnionTypes}', 'dom::bindings::codegen::Bindings::*', - 'dom::bindings::error::{FailureUnknown, Fallible, Error, ErrorResult}', + 'dom::bindings::error::{Fallible, Error, ErrorResult}', + 'dom::bindings::error::Error::FailureUnknown', 'dom::bindings::error::throw_dom_exception', 'dom::bindings::error::throw_type_error', 'dom::bindings::proxyhandler', @@ -5137,8 +5135,8 @@ class GlobalGenRoots(): return CGList([ CGGeneric(AUTOGENERATED_WARNING_COMMENT), CGGeneric("pub const MAX_PROTO_CHAIN_LENGTH: uint = %d;\n\n" % config.maxProtoChainLength), - CGNamespacedEnum('id', 'ID', protos, [0], deriving="PartialEq"), - CGNamespacedEnum('proxies', 'Proxy', proxies, [0], deriving="PartialEq"), + CGNonNamespacedEnum('id', protos, [0], deriving="PartialEq"), + CGNonNamespacedEnum('proxies', proxies, [0], deriving="PartialEq"), ]) diff --git a/components/script/dom/bindings/conversions.rs b/components/script/dom/bindings/conversions.rs index 596b722c77d..925311619a4 100644 --- a/components/script/dom/bindings/conversions.rs +++ b/components/script/dom/bindings/conversions.rs @@ -37,7 +37,7 @@ use dom::bindings::codegen::PrototypeList; // remove Option<Self> arguments. pub trait IDLInterface { /// Returns the prototype ID. - fn get_prototype_id(_: Option<Self>) -> PrototypeList::id::ID; + fn get_prototype_id(_: Option<Self>) -> PrototypeList::id; /// Returns the prototype depth, i.e., the number of interfaces this /// interface inherits from. fn get_prototype_depth(_: Option<Self>) -> uint; @@ -256,7 +256,7 @@ pub enum StringificationBehavior { impl default::Default for StringificationBehavior { fn default() -> StringificationBehavior { - Default + StringificationBehavior::Default } } @@ -283,7 +283,7 @@ pub fn jsid_to_str(cx: *mut JSContext, id: jsid) -> DOMString { impl FromJSValConvertible<StringificationBehavior> for DOMString { fn from_jsval(cx: *mut JSContext, value: JSVal, nullBehavior: StringificationBehavior) -> Result<DOMString, ()> { - if nullBehavior == Empty && value.is_null() { + if nullBehavior == StringificationBehavior::Empty && value.is_null() { Ok("".to_string()) } else { let jsstr = unsafe { JS_ValueToString(cx, value) }; diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 7f7e225a63b..549104856f9 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -7,6 +7,10 @@ //! This module contains smart pointers to global scopes, to simplify writing //! code that works in workers as well as window scopes. +pub use self::GlobalRef::*; +pub use self::GlobalRoot::*; +pub use self::GlobalField::*; + use dom::bindings::conversions::FromJSValConvertible; use dom::bindings::js::{JS, JSRef, Root}; use dom::bindings::utils::{Reflectable, Reflector}; diff --git a/components/script/dom/bindings/str.rs b/components/script/dom/bindings/str.rs index a06aaed5ec4..0882b3538e2 100644 --- a/components/script/dom/bindings/str.rs +++ b/components/script/dom/bindings/str.rs @@ -4,9 +4,9 @@ //! The `ByteString` struct. -use std::from_str::FromStr; use std::hash::{Hash, sip}; use std::str; +use std::str::FromStr; /// Encapsulates the IDL `ByteString` type. #[deriving(Clone,Eq,PartialEq)] @@ -89,31 +89,31 @@ impl ByteString { SPHT // SP or HT } let ByteString(ref vec) = *self; - let mut prev = Other; // The previous character + let mut prev = PreviousCharacter::Other; // The previous character vec.iter().all(|&x| { // http://tools.ietf.org/html/rfc2616#section-2.2 match x { 13 => { // CR - if prev == Other || prev == SPHT { - prev = CR; + if prev == PreviousCharacter::Other || prev == PreviousCharacter::SPHT { + prev = PreviousCharacter::CR; true } else { false } }, 10 => { // LF - if prev == CR { - prev = LF; + if prev == PreviousCharacter::CR { + prev = PreviousCharacter::LF; true } else { false } }, 32 => { // SP - if prev == LF || prev == SPHT { - prev = SPHT; + if prev == PreviousCharacter::LF || prev == PreviousCharacter::SPHT { + prev = PreviousCharacter::SPHT; true - } else if prev == Other { + } else if prev == PreviousCharacter::Other { // Counts as an Other here, since it's not preceded by a CRLF // SP is not a CTL, so it can be used anywhere // though if used immediately after a CR the CR is invalid @@ -124,8 +124,8 @@ impl ByteString { } }, 9 => { // HT - if prev == LF || prev == SPHT { - prev = SPHT; + if prev == PreviousCharacter::LF || prev == PreviousCharacter::SPHT { + prev = PreviousCharacter::SPHT; true } else { false @@ -133,8 +133,8 @@ impl ByteString { }, 0...31 | 127 => false, // CTLs x if x > 127 => false, // non ASCII - _ if prev == Other || prev == SPHT => { - prev = Other; + _ if prev == PreviousCharacter::Other || prev == PreviousCharacter::SPHT => { + prev = PreviousCharacter::Other; true }, _ => false // Previous character was a CR/LF but not part of the [CRLF] (SP|HT) rule diff --git a/components/script/dom/bindings/utils.rs b/components/script/dom/bindings/utils.rs index cf7561d4e79..a08b664b3dd 100644 --- a/components/script/dom/bindings/utils.rs +++ b/components/script/dom/bindings/utils.rs @@ -124,7 +124,7 @@ pub unsafe fn get_dom_class(obj: *mut JSObject) -> Result<DOMClass, ()> { /// not a reflector for a DOM object of the given type (as defined by the /// proto_id and proto_depth). pub fn unwrap_jsmanaged<T: Reflectable>(mut obj: *mut JSObject, - proto_id: PrototypeList::id::ID, + proto_id: PrototypeList::id, proto_depth: uint) -> Result<JS<T>, ()> { unsafe { let dom_class = get_dom_class(obj).or_else(|_| { @@ -212,11 +212,11 @@ impl ConstantSpec { /// Returns a `JSVal` that represents the value of this `ConstantSpec`. pub fn get_value(&self) -> JSVal { match self.value { - NullVal => NullValue(), - IntVal(i) => Int32Value(i), - UintVal(u) => UInt32Value(u), - DoubleVal(d) => DoubleValue(d), - BoolVal(b) => BooleanValue(b), + ConstantVal::NullVal => NullValue(), + ConstantVal::IntVal(i) => Int32Value(i), + ConstantVal::UintVal(u) => UInt32Value(u), + ConstantVal::DoubleVal(d) => DoubleValue(d), + ConstantVal::BoolVal(b) => BooleanValue(b), } } } @@ -234,7 +234,7 @@ pub struct NativePropertyHooks { pub struct DOMClass { /// A list of interfaces that this object implements, in order of decreasing /// derivedness. - pub interface_chain: [PrototypeList::id::ID, ..MAX_PROTO_CHAIN_LENGTH], + pub interface_chain: [PrototypeList::id, ..MAX_PROTO_CHAIN_LENGTH], /// The NativePropertyHooks for the interface associated with this class. pub native_hooks: &'static NativePropertyHooks, @@ -421,7 +421,7 @@ pub unsafe extern fn ThrowingConstructor(cx: *mut JSContext, _argc: c_uint, _vp: /// Construct and cache the ProtoOrIfaceArray for the given global. /// Fails if the argument is not a DOM global. pub fn initialize_global(global: *mut JSObject) { - let protoArray = box () ([0 as *mut JSObject, ..PrototypeList::id::IDCount as uint]); + let protoArray = box () ([0 as *mut JSObject, ..PrototypeList::id::Count as uint]); unsafe { assert!(((*JS_GetClass(global)).flags & JSCLASS_DOM_GLOBAL) != 0); let box_ = squirrel_away_unique(protoArray); @@ -722,10 +722,10 @@ pub fn xml_name_type(name: &str) -> XMLName { let mut non_qname_colons = false; let mut seen_colon = false; match iter.next() { - None => return InvalidXMLName, + None => return XMLName::InvalidXMLName, Some(c) => { if !is_valid_start(c) { - return InvalidXMLName; + return XMLName::InvalidXMLName; } if c == ':' { non_qname_colons = true; @@ -735,7 +735,7 @@ pub fn xml_name_type(name: &str) -> XMLName { for c in name.chars() { if !is_valid_continuation(c) { - return InvalidXMLName; + return XMLName::InvalidXMLName; } if c == ':' { match seen_colon { @@ -746,7 +746,7 @@ pub fn xml_name_type(name: &str) -> XMLName { } match non_qname_colons { - false => QName, - true => Name + false => XMLName::QName, + true => XMLName::Name } } diff --git a/components/script/dom/blob.rs b/components/script/dom/blob.rs index cbe98b13a47..e51eca2d186 100644 --- a/components/script/dom/blob.rs +++ b/components/script/dom/blob.rs @@ -14,15 +14,15 @@ use servo_util::str::DOMString; use std::cmp::{min, max}; #[jstraceable] -pub enum BlobType { - BlobTypeId, - FileTypeId +pub enum BlobTypeId { + Blob, + File, } #[dom_struct] pub struct Blob { reflector_: Reflector, - type_: BlobType, + type_: BlobTypeId, bytes: Option<Vec<u8>>, typeString: DOMString, global: GlobalField @@ -30,7 +30,7 @@ pub struct Blob { } impl Blob { - pub fn new_inherited(global: &GlobalRef, type_: BlobType, + pub fn new_inherited(global: &GlobalRef, type_: BlobTypeId, bytes: Option<Vec<u8>>) -> Blob { Blob { reflector_: Reflector::new(), @@ -43,7 +43,7 @@ impl Blob { } pub fn new(global: &GlobalRef, bytes: Option<Vec<u8>>) -> Temporary<Blob> { - reflect_dom_object(box Blob::new_inherited(global, BlobTypeId, bytes), + reflect_dom_object(box Blob::new_inherited(global, BlobTypeId::Blob, bytes), *global, BlobBinding::Wrap) } @@ -133,7 +133,7 @@ impl Reflectable for Blob { impl FileDerived for Blob { fn is_file(&self) -> bool { match self.type_ { - FileTypeId => true, + BlobTypeId::File => true, _ => false } } diff --git a/components/script/dom/characterdata.rs b/components/script/dom/characterdata.rs index f1331ceacd4..91bb1de46c2 100644 --- a/components/script/dom/characterdata.rs +++ b/components/script/dom/characterdata.rs @@ -7,12 +7,13 @@ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataDerived, NodeCast}; -use dom::bindings::error::{Fallible, ErrorResult, IndexSize}; +use dom::bindings::error::{Fallible, ErrorResult}; +use dom::bindings::error::Error::IndexSize; use dom::bindings::js::JSRef; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; -use dom::node::{CommentNodeTypeId, Node, NodeTypeId, TextNodeTypeId, ProcessingInstructionNodeTypeId, NodeHelpers}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; +use dom::node::{Node, NodeHelpers, NodeTypeId}; use servo_util::str::DOMString; @@ -27,9 +28,9 @@ pub struct CharacterData { impl CharacterDataDerived for EventTarget { fn is_characterdata(&self) -> bool { match *self.type_id() { - NodeTargetTypeId(TextNodeTypeId) | - NodeTargetTypeId(CommentNodeTypeId) | - NodeTargetTypeId(ProcessingInstructionNodeTypeId) => true, + EventTargetTypeId::Node(NodeTypeId::Text) | + EventTargetTypeId::Node(NodeTypeId::Comment) | + EventTargetTypeId::Node(NodeTypeId::ProcessingInstruction) => true, _ => false } } diff --git a/components/script/dom/comment.rs b/components/script/dom/comment.rs index e55483f39cd..11c7bf68b44 100644 --- a/components/script/dom/comment.rs +++ b/components/script/dom/comment.rs @@ -11,8 +11,8 @@ use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::characterdata::CharacterData; use dom::document::Document; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; -use dom::node::{CommentNodeTypeId, Node}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; /// An HTML comment. @@ -23,14 +23,14 @@ pub struct Comment { impl CommentDerived for EventTarget { fn is_comment(&self) -> bool { - *self.type_id() == NodeTargetTypeId(CommentNodeTypeId) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Comment) } } impl Comment { fn new_inherited(text: DOMString, document: JSRef<Document>) -> Comment { Comment { - characterdata: CharacterData::new_inherited(CommentNodeTypeId, text, document) + characterdata: CharacterData::new_inherited(NodeTypeId::Comment, text, document) } } diff --git a/components/script/dom/create.rs b/components/script/dom/create.rs index 59b6bb756bc..1848df54a09 100644 --- a/components/script/dom/create.rs +++ b/components/script/dom/create.rs @@ -29,7 +29,7 @@ use dom::htmlformelement::HTMLFormElement; use dom::htmlframeelement::HTMLFrameElement; use dom::htmlframesetelement::HTMLFrameSetElement; use dom::htmlheadelement::HTMLHeadElement; -use dom::htmlheadingelement::{Heading1, Heading2, Heading3, Heading4, Heading5, Heading6}; +use dom::htmlheadingelement::HeadingLevel::*; use dom::htmlheadingelement::HTMLHeadingElement; use dom::htmlhrelement::HTMLHRElement; use dom::htmlhtmlelement::HTMLHtmlElement; diff --git a/components/script/dom/customevent.rs b/components/script/dom/customevent.rs index 0f49f0c7d02..ee047e14c44 100644 --- a/components/script/dom/customevent.rs +++ b/components/script/dom/customevent.rs @@ -10,7 +10,7 @@ use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; -use dom::event::{Event, EventTypeId, CustomEventTypeId}; +use dom::event::{Event, EventTypeId}; use js::jsapi::JSContext; use js::jsval::{JSVal, NullValue}; use servo_util::str::DOMString; @@ -25,7 +25,7 @@ pub struct CustomEvent { impl CustomEventDerived for Event { fn is_customevent(&self) -> bool { - *self.type_id() == CustomEventTypeId + *self.type_id() == EventTypeId::CustomEvent } } @@ -38,7 +38,7 @@ impl CustomEvent { } pub fn new_uninitialized(global: GlobalRef) -> Temporary<CustomEvent> { - reflect_dom_object(box CustomEvent::new_inherited(CustomEventTypeId), + reflect_dom_object(box CustomEvent::new_inherited(EventTypeId::CustomEvent), global, CustomEventBinding::Wrap) } diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index 4a158f3673f..04211e9349d 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -7,20 +7,20 @@ use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding::Dedicat use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::InheritTypes::DedicatedWorkerGlobalScopeDerived; use dom::bindings::codegen::InheritTypes::{EventTargetCast, WorkerGlobalScopeCast}; -use dom::bindings::error::{ErrorResult, DataClone}; +use dom::bindings::error::ErrorResult; +use dom::bindings::error::Error::DataClone; use dom::bindings::global; use dom::bindings::js::{JSRef, Temporary, RootCollection}; use dom::bindings::utils::{Reflectable, Reflector}; -use dom::eventtarget::{EventTarget, EventTargetHelpers}; -use dom::eventtarget::WorkerGlobalScopeTypeId; +use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; use dom::messageevent::MessageEvent; use dom::worker::{Worker, TrustedWorkerAddress}; -use dom::workerglobalscope::DedicatedGlobalScope; use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers}; +use dom::workerglobalscope::WorkerGlobalScopeTypeId; use dom::xmlhttprequest::XMLHttpRequest; -use script_task::{ScriptTask, ScriptChan}; -use script_task::{ScriptMsg, FromWorker, DOMMessage, FireTimerMsg, XHRProgressMsg, XHRReleaseMsg, WorkerRelease}; -use script_task::WorkerPostMessage; +use script_task::{ScriptTask, ScriptChan, ScriptMsg, TimerSource}; +use script_task::ScriptMsg::{DOMMessage, FireTimerMsg, XHRProgressMsg}; +use script_task::ScriptMsg::{XHRReleaseMsg, WorkerRelease, WorkerPostMessage}; use script_task::StackRootTLS; use servo_net::resource_task::{ResourceTask, load_whole_resource}; @@ -57,8 +57,8 @@ impl DedicatedWorkerGlobalScope { -> DedicatedWorkerGlobalScope { DedicatedWorkerGlobalScope { workerglobalscope: WorkerGlobalScope::new_inherited( - DedicatedGlobalScope, worker_url, cx, resource_task, - own_sender), + WorkerGlobalScopeTypeId::DedicatedGlobalScope, worker_url, cx, + resource_task, own_sender), receiver: receiver, parent_sender: parent_sender, worker: worker, @@ -145,7 +145,7 @@ impl DedicatedWorkerGlobalScope { Ok(WorkerRelease(addr)) => { Worker::handle_release(addr) }, - Ok(FireTimerMsg(FromWorker, timer_id)) => { + Ok(FireTimerMsg(TimerSource::FromWorker, timer_id)) => { scope.handle_fire_timer(timer_id); } Ok(_) => panic!("Unexpected message"), @@ -197,7 +197,7 @@ impl Reflectable for DedicatedWorkerGlobalScope { impl DedicatedWorkerGlobalScopeDerived for EventTarget { fn is_dedicatedworkerglobalscope(&self) -> bool { match *self.type_id() { - WorkerGlobalScopeTypeId(DedicatedGlobalScope) => true, + EventTargetTypeId::WorkerGlobalScope(WorkerGlobalScopeTypeId::DedicatedGlobalScope) => true, _ => false } } diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index 4fdb8a9befd..8f6dab404f7 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -2,11 +2,10 @@ * 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, StringAttrValue}; +use dom::attr::{Attr, AttrHelpers, AttrValue}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::DocumentBinding; use dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, DocumentReadyState}; -use dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyStateValues; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::EventTargetBinding::EventTargetMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; @@ -20,24 +19,25 @@ use dom::bindings::codegen::InheritTypes::{HTMLAnchorElementDerived, HTMLAppletE use dom::bindings::codegen::InheritTypes::{HTMLAreaElementDerived, HTMLEmbedElementDerived}; use dom::bindings::codegen::InheritTypes::{HTMLFormElementDerived, HTMLImageElementDerived}; use dom::bindings::codegen::InheritTypes::{HTMLScriptElementDerived}; -use dom::bindings::error::{ErrorResult, Fallible, NotSupported, InvalidCharacter}; -use dom::bindings::error::{HierarchyRequest, NamespaceError}; +use dom::bindings::error::{ErrorResult, Fallible}; +use dom::bindings::error::Error::{NotSupported, InvalidCharacter}; +use dom::bindings::error::Error::{HierarchyRequest, NamespaceError}; use dom::bindings::global::GlobalRef; use dom::bindings::global; use dom::bindings::js::{MutNullableJS, JS, JSRef, Temporary, OptionalSettable, TemporaryPushable}; use dom::bindings::js::OptionalRootable; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; -use dom::bindings::utils::{xml_name_type, InvalidXMLName, Name, QName}; +use dom::bindings::utils::xml_name_type; +use dom::bindings::utils::XMLName::{QName, Name, InvalidXMLName}; use dom::comment::Comment; use dom::customevent::CustomEvent; use dom::documentfragment::DocumentFragment; use dom::documenttype::DocumentType; use dom::domimplementation::DOMImplementation; -use dom::element::{Element, ScriptCreated, AttributeHandlers, get_attribute_parts}; -use dom::element::{HTMLHeadElementTypeId, HTMLTitleElementTypeId}; -use dom::element::{HTMLBodyElementTypeId, HTMLFrameSetElementTypeId}; -use dom::event::{Event, DoesNotBubble, NotCancelable}; -use dom::eventtarget::{EventTarget, NodeTargetTypeId, EventTargetHelpers}; +use dom::element::{Element, ElementCreator, AttributeHandlers, get_attribute_parts}; +use dom::element::ElementTypeId; +use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::eventtarget::{EventTarget, EventTargetTypeId, EventTargetHelpers}; use dom::htmlanchorelement::HTMLAnchorElement; use dom::htmlcollection::{HTMLCollection, CollectionFilter}; use dom::htmlelement::HTMLElement; @@ -48,8 +48,7 @@ use dom::location::Location; use dom::mouseevent::MouseEvent; use dom::keyboardevent::KeyboardEvent; use dom::messageevent::MessageEvent; -use dom::node::{Node, ElementNodeTypeId, DocumentNodeTypeId, NodeHelpers}; -use dom::node::{CloneChildren, DoNotCloneChildren, NodeDamage, OtherNodeDamage}; +use dom::node::{Node, NodeHelpers, NodeTypeId, CloneChildrenFlag, NodeDamage}; use dom::nodelist::NodeList; use dom::text::Text; use dom::processinginstruction::ProcessingInstruction; @@ -107,7 +106,7 @@ pub struct Document { impl DocumentDerived for EventTarget { fn is_document(&self) -> bool { - *self.type_id() == NodeTargetTypeId(DocumentNodeTypeId) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Document) } } @@ -341,7 +340,8 @@ impl<'a> DocumentHelpers<'a> for JSRef<'a, Document> { let window = self.window.root(); let event = Event::new(global::Window(*window), "readystatechange".to_string(), - DoesNotBubble, NotCancelable).root(); + EventBubbles::DoesNotBubble, + EventCancelable::NotCancelable).root(); let target: JSRef<EventTarget> = EventTargetCast::from_ref(self); let _ = target.DispatchEvent(*event); } @@ -379,7 +379,7 @@ impl<'a> DocumentHelpers<'a> for JSRef<'a, Document> { fn dirty_all_nodes(self) { let root: JSRef<Node> = NodeCast::from_ref(self); for node in root.traverse_preorder() { - node.dirty(OtherNodeDamage) + node.dirty(NodeDamage::OtherNodeDamage) } } } @@ -410,14 +410,14 @@ impl Document { source: DocumentSource) -> Document { let url = url.unwrap_or_else(|| Url::parse("about:blank").unwrap()); - let ready_state = if source == FromParser { - DocumentReadyStateValues::Loading + let ready_state = if source == DocumentSource::FromParser { + DocumentReadyState::Loading } else { - DocumentReadyStateValues::Complete + DocumentReadyState::Complete }; Document { - node: Node::new_without_doc(DocumentNodeTypeId), + node: Node::new_without_doc(NodeTypeId::Document), window: JS::from_rooted(window), idmap: DOMRefCell::new(HashMap::new()), implementation: Default::default(), @@ -425,9 +425,9 @@ impl Document { Some(string) => string.clone(), None => match is_html_document { // http://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument - HTMLDocument => "text/html".to_string(), + IsHTMLDocument::HTMLDocument => "text/html".to_string(), // http://dom.spec.whatwg.org/#concept-document-content-type - NonHTMLDocument => "application/xml".to_string() + IsHTMLDocument::NonHTMLDocument => "application/xml".to_string() } }, last_modified: DOMRefCell::new(None), @@ -436,7 +436,7 @@ impl Document { quirks_mode: Cell::new(NoQuirks), // http://dom.spec.whatwg.org/#concept-document-encoding encoding_name: DOMRefCell::new("UTF-8".to_string()), - is_html_document: is_html_document == HTMLDocument, + is_html_document: is_html_document == IsHTMLDocument::HTMLDocument, images: Default::default(), embeds: Default::default(), links: Default::default(), @@ -452,7 +452,9 @@ impl Document { // http://dom.spec.whatwg.org/#dom-document pub fn Constructor(global: &GlobalRef) -> Fallible<Temporary<Document>> { - Ok(Document::new(global.as_window(), None, NonHTMLDocument, None, NotFromParser)) + Ok(Document::new(global.as_window(), None, + IsHTMLDocument::NonHTMLDocument, None, + DocumentSource::NotFromParser)) } pub fn new(window: JSRef<Window>, @@ -596,7 +598,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { local_name }; let name = QualName::new(ns!(HTML), Atom::from_slice(local_name.as_slice())); - Ok(Element::create(name, None, self, ScriptCreated)) + Ok(Element::create(name, None, self, ElementCreator::ScriptCreated)) } // http://dom.spec.whatwg.org/#dom-document-createelementns @@ -641,7 +643,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { let name = QualName::new(ns, Atom::from_slice(local_name_from_qname)); Ok(Element::create(name, prefix_from_qname.map(|s| s.to_string()), self, - ScriptCreated)) + ElementCreator::ScriptCreated)) } // http://dom.spec.whatwg.org/#dom-document-createattribute @@ -655,7 +657,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { let name = Atom::from_slice(local_name.as_slice()); // repetition used because string_cache::atom::Atom is non-copyable let l_name = Atom::from_slice(local_name.as_slice()); - let value = StringAttrValue("".to_string()); + let value = AttrValue::String("".to_string()); Ok(Attr::new(*window, name, value, l_name, ns!(""), None, None)) } @@ -702,8 +704,8 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { // Step 2. let clone_children = match deep { - true => CloneChildren, - false => DoNotCloneChildren + true => CloneChildrenFlag::CloneChildren, + false => CloneChildrenFlag::DoNotCloneChildren }; Ok(Node::clone(node, Some(self), clone_children)) @@ -748,7 +750,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { fn LastModified(self) -> DOMString { match *self.last_modified.borrow() { Some(ref t) => t.clone(), - None => time::now().strftime("%m/%d/%Y %H:%M:%S").unwrap(), + None => format!("{}", time::now().strftime("%m/%d/%Y %H:%M:%S").unwrap()), } } @@ -769,7 +771,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { self.GetDocumentElement().root().map(|root| { let root: JSRef<Node> = NodeCast::from_ref(*root); root.traverse_preorder() - .find(|node| node.type_id() == ElementNodeTypeId(HTMLTitleElementTypeId)) + .find(|node| node.type_id() == NodeTypeId::Element(ElementTypeId::HTMLTitleElement)) .map(|title_elem| { for text in title_elem.children().filter_map::<JSRef<Text>>(TextCast::to_ref) { title.push_str(text.characterdata().data().as_slice()); @@ -785,11 +787,11 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { self.GetDocumentElement().root().map(|root| { let root: JSRef<Node> = NodeCast::from_ref(*root); let head_node = root.traverse_preorder().find(|child| { - child.type_id() == ElementNodeTypeId(HTMLHeadElementTypeId) + child.type_id() == NodeTypeId::Element(ElementTypeId::HTMLHeadElement) }); head_node.map(|head| { let title_node = head.children().find(|child| { - child.type_id() == ElementNodeTypeId(HTMLTitleElementTypeId) + child.type_id() == NodeTypeId::Element(ElementTypeId::HTMLTitleElement) }); match title_node { @@ -834,8 +836,8 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { let node: JSRef<Node> = NodeCast::from_ref(*root); node.children().find(|child| { match child.type_id() { - ElementNodeTypeId(HTMLBodyElementTypeId) | - ElementNodeTypeId(HTMLFrameSetElementTypeId) => true, + NodeTypeId::Element(ElementTypeId::HTMLBodyElement) | + NodeTypeId::Element(ElementTypeId::HTMLFrameSetElement) => true, _ => false } }).map(|node| { @@ -854,8 +856,8 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { let node: JSRef<Node> = NodeCast::from_ref(new_body); match node.type_id() { - ElementNodeTypeId(HTMLBodyElementTypeId) | - ElementNodeTypeId(HTMLFrameSetElementTypeId) => {} + NodeTypeId::Element(ElementTypeId::HTMLBodyElement) | + NodeTypeId::Element(ElementTypeId::HTMLFrameSetElement) => {} _ => return Err(HierarchyRequest) } diff --git a/components/script/dom/documentfragment.rs b/components/script/dom/documentfragment.rs index 65fa818e033..951aac09351 100644 --- a/components/script/dom/documentfragment.rs +++ b/components/script/dom/documentfragment.rs @@ -12,9 +12,9 @@ use dom::bindings::global::GlobalRef; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::Element; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlcollection::HTMLCollection; -use dom::node::{DocumentFragmentNodeTypeId, Node, NodeHelpers, window_from_node}; +use dom::node::{Node, NodeHelpers, NodeTypeId, window_from_node}; use dom::nodelist::NodeList; use servo_util::str::DOMString; @@ -25,7 +25,7 @@ pub struct DocumentFragment { impl DocumentFragmentDerived for EventTarget { fn is_documentfragment(&self) -> bool { - *self.type_id() == NodeTargetTypeId(DocumentFragmentNodeTypeId) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::DocumentFragment) } } @@ -33,7 +33,7 @@ impl DocumentFragment { /// Creates a new DocumentFragment. fn new_inherited(document: JSRef<Document>) -> DocumentFragment { DocumentFragment { - node: Node::new_inherited(DocumentFragmentNodeTypeId, document), + node: Node::new_inherited(NodeTypeId::DocumentFragment, document), } } diff --git a/components/script/dom/documenttype.rs b/components/script/dom/documenttype.rs index f293208d1f9..9bd1357553a 100644 --- a/components/script/dom/documenttype.rs +++ b/components/script/dom/documenttype.rs @@ -8,8 +8,8 @@ use dom::bindings::codegen::InheritTypes::{DocumentTypeDerived, NodeCast}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; -use dom::node::{Node, DoctypeNodeTypeId, NodeHelpers}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; +use dom::node::{Node, NodeHelpers, NodeTypeId}; use servo_util::str::DOMString; /// The `DOCTYPE` tag. @@ -23,7 +23,7 @@ pub struct DocumentType { impl DocumentTypeDerived for EventTarget { fn is_documenttype(&self) -> bool { - *self.type_id() == NodeTargetTypeId(DoctypeNodeTypeId) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::DocumentType) } } @@ -34,7 +34,7 @@ impl DocumentType { document: JSRef<Document>) -> DocumentType { DocumentType { - node: Node::new_inherited(DoctypeNodeTypeId, document), + node: Node::new_inherited(NodeTypeId::DocumentType, document), name: name, public_id: public_id.unwrap_or("".to_string()), system_id: system_id.unwrap_or("".to_string()) diff --git a/components/script/dom/domexception.rs b/components/script/dom/domexception.rs index 50aafb6eedb..1d6906f1be6 100644 --- a/components/script/dom/domexception.rs +++ b/components/script/dom/domexception.rs @@ -5,7 +5,6 @@ use dom::bindings::codegen::Bindings::DOMExceptionBinding; use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionConstants; use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods; -use dom::bindings::error; use dom::bindings::error::Error; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; @@ -42,21 +41,21 @@ pub enum DOMErrorName { impl DOMErrorName { fn from_error(error: Error) -> DOMErrorName { match error { - error::IndexSize => IndexSizeError, - error::NotFound => NotFoundError, - error::HierarchyRequest => HierarchyRequestError, - error::InvalidCharacter => InvalidCharacterError, - error::NotSupported => NotSupportedError, - error::InvalidState => InvalidStateError, - error::Syntax => SyntaxError, - error::NamespaceError => NamespaceError, - error::InvalidAccess => InvalidAccessError, - error::Security => SecurityError, - error::Network => NetworkError, - error::Abort => AbortError, - error::Timeout => TimeoutError, - error::DataClone => DataCloneError, - error::FailureUnknown => panic!(), + Error::IndexSize => DOMErrorName::IndexSizeError, + Error::NotFound => DOMErrorName::NotFoundError, + Error::HierarchyRequest => DOMErrorName::HierarchyRequestError, + Error::InvalidCharacter => DOMErrorName::InvalidCharacterError, + Error::NotSupported => DOMErrorName::NotSupportedError, + Error::InvalidState => DOMErrorName::InvalidStateError, + Error::Syntax => DOMErrorName::SyntaxError, + Error::NamespaceError => DOMErrorName::NamespaceError, + Error::InvalidAccess => DOMErrorName::InvalidAccessError, + Error::Security => DOMErrorName::SecurityError, + Error::Network => DOMErrorName::NetworkError, + Error::Abort => DOMErrorName::AbortError, + Error::Timeout => DOMErrorName::TimeoutError, + Error::DataClone => DOMErrorName::DataCloneError, + Error::FailureUnknown => panic!(), } } } @@ -95,7 +94,7 @@ impl<'a> DOMExceptionMethods for JSRef<'a, DOMException> { fn Code(self) -> u16 { match self.code { // http://dom.spec.whatwg.org/#concept-throw - EncodingError => 0, + DOMErrorName::EncodingError => 0, code => code as u16 } } @@ -108,27 +107,27 @@ impl<'a> DOMExceptionMethods for JSRef<'a, DOMException> { // http://dom.spec.whatwg.org/#error-names-0 fn Message(self) -> DOMString { let message = match self.code { - IndexSizeError => "The index is not in the allowed range.", - HierarchyRequestError => "The operation would yield an incorrect node tree.", - WrongDocumentError => "The object is in the wrong document.", - InvalidCharacterError => "The string contains invalid characters.", - NoModificationAllowedError => "The object can not be modified.", - NotFoundError => "The object can not be found here.", - NotSupportedError => "The operation is not supported.", - InvalidStateError => "The object is in an invalid state.", - SyntaxError => "The string did not match the expected pattern.", - InvalidModificationError => "The object can not be modified in this way.", - NamespaceError => "The operation is not allowed by Namespaces in XML.", - InvalidAccessError => "The object does not support the operation or argument.", - SecurityError => "The operation is insecure.", - NetworkError => "A network error occurred.", - AbortError => "The operation was aborted.", - URLMismatchError => "The given URL does not match another URL.", - QuotaExceededError => "The quota has been exceeded.", - TimeoutError => "The operation timed out.", - InvalidNodeTypeError => "The supplied node is incorrect or has an incorrect ancestor for this operation.", - DataCloneError => "The object can not be cloned.", - EncodingError => "The encoding operation (either encoded or decoding) failed." + DOMErrorName::IndexSizeError => "The index is not in the allowed range.", + DOMErrorName::HierarchyRequestError => "The operation would yield an incorrect node tree.", + DOMErrorName::WrongDocumentError => "The object is in the wrong document.", + DOMErrorName::InvalidCharacterError => "The string contains invalid characters.", + DOMErrorName::NoModificationAllowedError => "The object can not be modified.", + DOMErrorName::NotFoundError => "The object can not be found here.", + DOMErrorName::NotSupportedError => "The operation is not supported.", + DOMErrorName::InvalidStateError => "The object is in an invalid state.", + DOMErrorName::SyntaxError => "The string did not match the expected pattern.", + DOMErrorName::InvalidModificationError => "The object can not be modified in this way.", + DOMErrorName::NamespaceError => "The operation is not allowed by Namespaces in XML.", + DOMErrorName::InvalidAccessError => "The object does not support the operation or argument.", + DOMErrorName::SecurityError => "The operation is insecure.", + DOMErrorName::NetworkError => "A network error occurred.", + DOMErrorName::AbortError => "The operation was aborted.", + DOMErrorName::URLMismatchError => "The given URL does not match another URL.", + DOMErrorName::QuotaExceededError => "The quota has been exceeded.", + DOMErrorName::TimeoutError => "The operation timed out.", + DOMErrorName::InvalidNodeTypeError => "The supplied node is incorrect or has an incorrect ancestor for this operation.", + DOMErrorName::DataCloneError => "The object can not be cloned.", + DOMErrorName::EncodingError => "The encoding operation (either encoded or decoding) failed." }; message.to_string() diff --git a/components/script/dom/domimplementation.rs b/components/script/dom/domimplementation.rs index 29e34d48b51..6e84e7a0194 100644 --- a/components/script/dom/domimplementation.rs +++ b/components/script/dom/domimplementation.rs @@ -7,13 +7,15 @@ use dom::bindings::codegen::Bindings::DOMImplementationBinding; use dom::bindings::codegen::Bindings::DOMImplementationBinding::DOMImplementationMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::codegen::InheritTypes::NodeCast; -use dom::bindings::error::{Fallible, InvalidCharacter, NamespaceError}; +use dom::bindings::error::Fallible; +use dom::bindings::error::Error::{InvalidCharacter, NamespaceError}; use dom::bindings::global::Window; use dom::bindings::js::{JS, JSRef, Root, Temporary, OptionalRootable}; use dom::bindings::utils::{Reflector, Reflectable, reflect_dom_object}; -use dom::bindings::utils::{QName, Name, InvalidXMLName, xml_name_type}; -use dom::document::{Document, DocumentHelpers, HTMLDocument, NonHTMLDocument}; -use dom::document::NotFromParser; +use dom::bindings::utils::xml_name_type; +use dom::bindings::utils::XMLName::{QName, Name, InvalidXMLName}; +use dom::document::{Document, DocumentHelpers, IsHTMLDocument}; +use dom::document::DocumentSource; use dom::documenttype::DocumentType; use dom::htmlbodyelement::HTMLBodyElement; use dom::htmlheadelement::HTMLHeadElement; @@ -75,7 +77,8 @@ impl<'a> DOMImplementationMethods for JSRef<'a, DOMImplementation> { let win = doc.window().root(); // Step 1. - let doc = Document::new(*win, None, NonHTMLDocument, None, NotFromParser).root(); + let doc = Document::new(*win, None, IsHTMLDocument::NonHTMLDocument, + None, DocumentSource::NotFromParser).root(); // Step 2-3. let maybe_elem = if qname.is_empty() { None @@ -120,7 +123,8 @@ impl<'a> DOMImplementationMethods for JSRef<'a, DOMImplementation> { let win = document.window().root(); // Step 1-2. - let doc = Document::new(*win, None, HTMLDocument, None, NotFromParser).root(); + let doc = Document::new(*win, None, IsHTMLDocument::HTMLDocument, None, + DocumentSource::NotFromParser).root(); let doc_node: JSRef<Node> = NodeCast::from_ref(*doc); { diff --git a/components/script/dom/domparser.rs b/components/script/dom/domparser.rs index fe543162da8..91d340aa791 100644 --- a/components/script/dom/domparser.rs +++ b/components/script/dom/domparser.rs @@ -2,17 +2,18 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyStateValues; +use dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState; use dom::bindings::codegen::Bindings::DOMParserBinding; use dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods; -use dom::bindings::codegen::Bindings::DOMParserBinding::SupportedTypeValues::{Text_html, Text_xml}; -use dom::bindings::error::{Fallible, FailureUnknown}; +use dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::{Text_html, Text_xml}; +use dom::bindings::error::Fallible; +use dom::bindings::error::Error::FailureUnknown; use dom::bindings::global::GlobalRef; use dom::bindings::global; use dom::bindings::js::{JS, JSRef, Temporary}; use dom::bindings::utils::{Reflector, Reflectable, reflect_dom_object}; -use dom::document::{Document, DocumentHelpers, HTMLDocument, NonHTMLDocument}; -use dom::document::{FromParser, NotFromParser}; +use dom::document::{Document, DocumentHelpers, IsHTMLDocument}; +use dom::document::DocumentSource; use dom::servohtmlparser::ServoHTMLParser; use dom::window::Window; use parse::Parser; @@ -53,18 +54,22 @@ impl<'a> DOMParserMethods for JSRef<'a, DOMParser> { let content_type = DOMParserBinding::SupportedTypeValues::strings[ty as uint].to_string(); match ty { Text_html => { - let document = Document::new(window, url.clone(), HTMLDocument, - Some(content_type), FromParser).root().clone(); + let document = Document::new(window, url.clone(), + IsHTMLDocument::HTMLDocument, + Some(content_type), + DocumentSource::FromParser).root().clone(); let parser = ServoHTMLParser::new(url.clone(), document).root().clone(); parser.parse_chunk(s); parser.finish(); - document.set_ready_state(DocumentReadyStateValues::Complete); + document.set_ready_state(DocumentReadyState::Complete); Ok(Temporary::from_rooted(document)) } Text_xml => { //FIXME: this should probably be FromParser when we actually parse the string (#3756). - Ok(Document::new(window, url.clone(), NonHTMLDocument, Some(content_type), - NotFromParser)) + Ok(Document::new(window, url.clone(), + IsHTMLDocument::NonHTMLDocument, + Some(content_type), + DocumentSource::NotFromParser)) } _ => { Err(FailureUnknown) diff --git a/components/script/dom/domrect.rs b/components/script/dom/domrect.rs index e6c7b06ddfd..109e263061b 100644 --- a/components/script/dom/domrect.rs +++ b/components/script/dom/domrect.rs @@ -9,6 +9,7 @@ use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::window::Window; use servo_util::geometry::Au; +use std::num::Float; #[dom_struct] pub struct DOMRect { diff --git a/components/script/dom/domtokenlist.rs b/components/script/dom/domtokenlist.rs index 30318e0bd78..fecccad8fea 100644 --- a/components/script/dom/domtokenlist.rs +++ b/components/script/dom/domtokenlist.rs @@ -5,7 +5,8 @@ use dom::attr::{Attr, AttrHelpers}; use dom::bindings::codegen::Bindings::DOMTokenListBinding; use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods; -use dom::bindings::error::{Fallible, InvalidCharacter, Syntax}; +use dom::bindings::error::Fallible; +use dom::bindings::error::Error::{InvalidCharacter, Syntax}; use dom::bindings::global::Window; use dom::bindings::js::{JS, JSRef, Temporary, OptionalRootable}; use dom::bindings::utils::{Reflector, Reflectable, reflect_dom_object}; diff --git a/components/script/dom/element.rs b/components/script/dom/element.rs index a8beed315fe..ec97ee451e5 100644 --- a/components/script/dom/element.rs +++ b/components/script/dom/element.rs @@ -5,8 +5,8 @@ //! Element nodes. use dom::activation::Activatable; -use dom::attr::{Attr, ReplacedAttr, FirstSetAttr, AttrHelpers, AttrHelpersForLayout}; -use dom::attr::{AttrValue, StringAttrValue, UIntAttrValue, AtomAttrValue}; +use dom::attr::{Attr, AttrSettingType, AttrHelpers, AttrHelpersForLayout}; +use dom::attr::AttrValue; use dom::namednodemap::NamedNodeMap; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; @@ -21,18 +21,20 @@ use dom::bindings::codegen::InheritTypes::{HTMLInputElementDerived, HTMLTableEle use dom::bindings::codegen::InheritTypes::{HTMLTableElementDerived, HTMLTableCellElementDerived}; use dom::bindings::codegen::InheritTypes::{HTMLTableRowElementDerived, HTMLTextAreaElementDerived}; use dom::bindings::codegen::InheritTypes::{HTMLTableSectionElementDerived, NodeCast}; +use dom::bindings::error::{ErrorResult, Fallible}; +use dom::bindings::error::Error::{NamespaceError, InvalidCharacter, Syntax}; use dom::bindings::js::{MutNullableJS, JS, JSRef, Temporary, TemporaryPushable}; use dom::bindings::js::{OptionalRootable, Root}; use dom::bindings::utils::{Reflectable, Reflector}; -use dom::bindings::error::{ErrorResult, Fallible, NamespaceError, InvalidCharacter, Syntax}; -use dom::bindings::utils::{QName, Name, InvalidXMLName, xml_name_type}; +use dom::bindings::utils::xml_name_type; +use dom::bindings::utils::XMLName::{QName, Name, InvalidXMLName}; use dom::create::create_element; use dom::domrect::DOMRect; use dom::domrectlist::DOMRectList; use dom::document::{Document, DocumentHelpers, LayoutDocumentHelpers}; use dom::domtokenlist::DOMTokenList; use dom::event::Event; -use dom::eventtarget::{EventTarget, NodeTargetTypeId, EventTargetHelpers}; +use dom::eventtarget::{EventTarget, EventTargetTypeId, EventTargetHelpers}; use dom::htmlbodyelement::{HTMLBodyElement, HTMLBodyElementHelpers}; use dom::htmlcollection::HTMLCollection; use dom::htmlinputelement::{HTMLInputElement, RawLayoutHTMLInputElementHelpers, HTMLInputElementHelpers}; @@ -42,16 +44,14 @@ use dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementHelper use dom::htmltablerowelement::{HTMLTableRowElement, HTMLTableRowElementHelpers}; use dom::htmltablesectionelement::{HTMLTableSectionElement, HTMLTableSectionElementHelpers}; use dom::htmltextareaelement::{HTMLTextAreaElement, RawLayoutHTMLTextAreaElementHelpers}; -use dom::node::{CLICK_IN_PROGRESS, ElementNodeTypeId, LayoutNodeHelpers, Node, NodeHelpers}; -use dom::node::{NodeIterator, NodeStyleDamaged, OtherNodeDamage, document_from_node}; +use dom::node::{CLICK_IN_PROGRESS, LayoutNodeHelpers, Node, NodeHelpers, NodeTypeId}; +use dom::node::{NodeIterator, document_from_node, NodeDamage}; use dom::node::{window_from_node}; use dom::nodelist::NodeList; use dom::virtualmethods::{VirtualMethods, vtable_for}; use devtools_traits::AttrInfo; -use style::{mod, AuthorOrigin, BgColorSimpleColorAttribute, BorderUnsignedIntegerAttribute}; -use style::{ColSpanUnsignedIntegerAttribute, IntegerAttribute, LengthAttribute, ParserContext}; -use style::{SimpleColorAttribute, SizeIntegerAttribute, ColsIntegerAttribute, RowsIntegerAttribute}; -use style::{UnsignedIntegerAttribute, WidthLengthAttribute, matches}; +use style::{mod, StylesheetOrigin, SimpleColorAttribute, UnsignedIntegerAttribute}; +use style::{IntegerAttribute, LengthAttribute, ParserContext, matches}; use servo_util::namespace; use servo_util::str::{DOMString, LengthOrPercentageOrAuto}; @@ -79,7 +79,7 @@ impl ElementDerived for EventTarget { #[inline] fn is_element(&self) -> bool { match *self.type_id() { - NodeTargetTypeId(ElementNodeTypeId(_)) => true, + EventTargetTypeId::Node(NodeTypeId::Element(_)) => true, _ => false } } @@ -94,75 +94,75 @@ impl Reflectable for Element { #[deriving(PartialEq, Show)] #[jstraceable] pub enum ElementTypeId { - HTMLElementTypeId, - HTMLAnchorElementTypeId, - HTMLAppletElementTypeId, - HTMLAreaElementTypeId, - HTMLAudioElementTypeId, - HTMLBaseElementTypeId, - HTMLBRElementTypeId, - HTMLBodyElementTypeId, - HTMLButtonElementTypeId, - HTMLCanvasElementTypeId, - HTMLDataElementTypeId, - HTMLDataListElementTypeId, - HTMLDirectoryElementTypeId, - HTMLDListElementTypeId, - HTMLDivElementTypeId, - HTMLEmbedElementTypeId, - HTMLFieldSetElementTypeId, - HTMLFontElementTypeId, - HTMLFormElementTypeId, - HTMLFrameElementTypeId, - HTMLFrameSetElementTypeId, - HTMLHRElementTypeId, - HTMLHeadElementTypeId, - HTMLHeadingElementTypeId, - HTMLHtmlElementTypeId, - HTMLIFrameElementTypeId, - HTMLImageElementTypeId, - HTMLInputElementTypeId, - HTMLLabelElementTypeId, - HTMLLegendElementTypeId, - HTMLLinkElementTypeId, - HTMLLIElementTypeId, - HTMLMapElementTypeId, - HTMLMediaElementTypeId, - HTMLMetaElementTypeId, - HTMLMeterElementTypeId, - HTMLModElementTypeId, - HTMLObjectElementTypeId, - HTMLOListElementTypeId, - HTMLOptGroupElementTypeId, - HTMLOptionElementTypeId, - HTMLOutputElementTypeId, - HTMLParagraphElementTypeId, - HTMLParamElementTypeId, - HTMLPreElementTypeId, - HTMLProgressElementTypeId, - HTMLQuoteElementTypeId, - HTMLScriptElementTypeId, - HTMLSelectElementTypeId, - HTMLSourceElementTypeId, - HTMLSpanElementTypeId, - HTMLStyleElementTypeId, - HTMLTableElementTypeId, - HTMLTableCaptionElementTypeId, - HTMLTableDataCellElementTypeId, - HTMLTableHeaderCellElementTypeId, - HTMLTableColElementTypeId, - HTMLTableRowElementTypeId, - HTMLTableSectionElementTypeId, - HTMLTemplateElementTypeId, - HTMLTextAreaElementTypeId, - HTMLTimeElementTypeId, - HTMLTitleElementTypeId, - HTMLTrackElementTypeId, - HTMLUListElementTypeId, - HTMLVideoElementTypeId, - HTMLUnknownElementTypeId, - - ElementTypeId_, + HTMLElement, + HTMLAnchorElement, + HTMLAppletElement, + HTMLAreaElement, + HTMLAudioElement, + HTMLBaseElement, + HTMLBRElement, + HTMLBodyElement, + HTMLButtonElement, + HTMLCanvasElement, + HTMLDataElement, + HTMLDataListElement, + HTMLDirectoryElement, + HTMLDListElement, + HTMLDivElement, + HTMLEmbedElement, + HTMLFieldSetElement, + HTMLFontElement, + HTMLFormElement, + HTMLFrameElement, + HTMLFrameSetElement, + HTMLHRElement, + HTMLHeadElement, + HTMLHeadingElement, + HTMLHtmlElement, + HTMLIFrameElement, + HTMLImageElement, + HTMLInputElement, + HTMLLabelElement, + HTMLLegendElement, + HTMLLinkElement, + HTMLLIElement, + HTMLMapElement, + HTMLMediaElement, + HTMLMetaElement, + HTMLMeterElement, + HTMLModElement, + HTMLObjectElement, + HTMLOListElement, + HTMLOptGroupElement, + HTMLOptionElement, + HTMLOutputElement, + HTMLParagraphElement, + HTMLParamElement, + HTMLPreElement, + HTMLProgressElement, + HTMLQuoteElement, + HTMLScriptElement, + HTMLSelectElement, + HTMLSourceElement, + HTMLSpanElement, + HTMLStyleElement, + HTMLTableElement, + HTMLTableCaptionElement, + HTMLTableDataCellElement, + HTMLTableHeaderCellElement, + HTMLTableColElement, + HTMLTableRowElement, + HTMLTableSectionElement, + HTMLTemplateElement, + HTMLTextAreaElement, + HTMLTimeElement, + HTMLTitleElement, + HTMLTrackElement, + HTMLUListElement, + HTMLVideoElement, + HTMLUnknownElement, + + Element, } #[deriving(PartialEq)] @@ -183,7 +183,7 @@ impl Element { pub fn new_inherited(type_id: ElementTypeId, local_name: DOMString, namespace: Namespace, prefix: Option<DOMString>, document: JSRef<Document>) -> Element { Element { - node: Node::new_inherited(ElementNodeTypeId(type_id), document), + node: Node::new_inherited(NodeTypeId::Element(type_id), document), local_name: Atom::from_slice(local_name.as_slice()), namespace: namespace, prefix: prefix, @@ -195,7 +195,7 @@ impl Element { } pub fn new(local_name: DOMString, namespace: Namespace, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<Element> { - Node::reflect_node(box Element::new_inherited(ElementTypeId_, local_name, namespace, prefix, document), + Node::reflect_node(box Element::new_inherited(ElementTypeId::Element, local_name, namespace, prefix, document), document, ElementBinding::Wrap) } } @@ -300,7 +300,7 @@ impl RawLayoutElementHelpers for Element { unsafe fn get_length_attribute_for_layout(&self, length_attribute: LengthAttribute) -> LengthOrPercentageOrAuto { match length_attribute { - WidthLengthAttribute => { + LengthAttribute::Width => { if self.is_htmltableelement() { let this: &HTMLTableElement = mem::transmute(self); this.get_width() @@ -318,21 +318,21 @@ impl RawLayoutElementHelpers for Element { unsafe fn get_integer_attribute_for_layout(&self, integer_attribute: IntegerAttribute) -> Option<i32> { match integer_attribute { - SizeIntegerAttribute => { + IntegerAttribute::Size => { if !self.is_htmlinputelement() { panic!("I'm not a form input!") } let this: &HTMLInputElement = mem::transmute(self); Some(this.get_size_for_layout() as i32) } - ColsIntegerAttribute => { + IntegerAttribute::Cols => { if !self.is_htmltextareaelement() { panic!("I'm not a textarea element!") } let this: &HTMLTextAreaElement = mem::transmute(self); Some(this.get_cols_for_layout() as i32) } - RowsIntegerAttribute => { + IntegerAttribute::Rows => { if !self.is_htmltextareaelement() { panic!("I'm not a textarea element!") } @@ -369,7 +369,7 @@ impl RawLayoutElementHelpers for Element { attribute: UnsignedIntegerAttribute) -> Option<u32> { match attribute { - BorderUnsignedIntegerAttribute => { + UnsignedIntegerAttribute::BorderUnsignedIntegerAttribute => { if self.is_htmltableelement() { let this: &HTMLTableElement = mem::transmute(self); this.get_border() @@ -379,7 +379,7 @@ impl RawLayoutElementHelpers for Element { None } } - ColSpanUnsignedIntegerAttribute => { + UnsignedIntegerAttribute::ColSpanUnsignedIntegerAttribute => { if self.is_htmltablecellelement() { let this: &HTMLTableCellElement = mem::transmute(self); this.get_colspan() @@ -397,7 +397,7 @@ impl RawLayoutElementHelpers for Element { unsafe fn get_simple_color_attribute_for_layout(&self, attribute: SimpleColorAttribute) -> Option<RGBA> { match attribute { - BgColorSimpleColorAttribute => { + SimpleColorAttribute::BgColorSimpleColorAttribute => { if self.is_htmlbodyelement() { let this: &HTMLBodyElement = mem::transmute(self); this.get_background_color() @@ -612,13 +612,13 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> { .map(|attr| attr.root()) .position(|attr| cb(*attr)); let (idx, set_type) = match idx { - Some(idx) => (idx, ReplacedAttr), + Some(idx) => (idx, AttrSettingType::ReplacedAttr), None => { let window = window_from_node(self).root(); let attr = Attr::new(*window, local_name, value.clone(), name, namespace.clone(), prefix, Some(self)); self.attrs.borrow_mut().push_unrooted(&attr); - (self.attrs.borrow().len() - 1, FirstSetAttr) + (self.attrs.borrow().len() - 1, AttrSettingType::FirstSetAttr) } }; @@ -631,7 +631,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> { vtable_for(&NodeCast::from_ref(self)) .parse_plain_attribute(local_name, value) } else { - StringAttrValue(value) + AttrValue::String(value) } } @@ -657,9 +657,9 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> { if node.is_in_doc() { let document = document_from_node(self).root(); if local_name == atom!("style") { - document.content_changed(node, NodeStyleDamaged); + document.content_changed(node, NodeDamage::NodeStyleDamaged); } else { - document.content_changed(node, OtherNodeDamage); + document.content_changed(node, NodeDamage::OtherNodeDamage); } } } @@ -725,7 +725,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> { } fn set_string_attribute(self, name: &Atom, value: DOMString) { assert!(name.as_slice() == name.as_slice().to_ascii_lower().as_slice()); - self.set_attribute(name, StringAttrValue(value)); + self.set_attribute(name, AttrValue::String(value)); } fn set_tokenlist_attribute(self, name: &Atom, value: DOMString) { @@ -741,8 +741,8 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> { match attribute { Some(attribute) => { match *attribute.value() { - UIntAttrValue(_, value) => value, - _ => panic!("Expected a UIntAttrValue: \ + AttrValue::UInt(_, value) => value, + _ => panic!("Expected an AttrValue::UInt: \ implement parse_plain_attribute"), } } @@ -751,7 +751,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> { } fn set_uint_attribute(self, name: &Atom, value: u32) { assert!(name.as_slice() == name.as_slice().to_ascii_lower().as_slice()); - self.set_attribute(name, UIntAttrValue(value.to_string(), value)); + self.set_attribute(name, AttrValue::UInt(value.to_string(), value)); } } @@ -1049,7 +1049,7 @@ impl<'a> ElementMethods for JSRef<'a, Element> { // http://dom.spec.whatwg.org/#dom-element-matches fn Matches(self, selectors: DOMString) -> Fallible<bool> { let parser_context = ParserContext { - origin: AuthorOrigin, + origin: StylesheetOrigin::Author, }; match style::parse_selector_list_from_str(&parser_context, selectors.as_slice()) { Err(()) => Err(Syntax), @@ -1097,7 +1097,7 @@ impl<'a> VirtualMethods for JSRef<'a, Element> { *self.style_attribute.borrow_mut() = style; if node.is_in_doc() { - doc.content_changed(node, NodeStyleDamaged); + doc.content_changed(node, NodeDamage::NodeStyleDamaged); } } &atom!("class") => { @@ -1105,7 +1105,7 @@ impl<'a> VirtualMethods for JSRef<'a, Element> { let node: JSRef<Node> = NodeCast::from_ref(*self); if node.is_in_doc() { let document = document_from_node(*self).root(); - document.content_changed(node, NodeStyleDamaged); + document.content_changed(node, NodeDamage::NodeStyleDamaged); } } &atom!("id") => { @@ -1118,7 +1118,7 @@ impl<'a> VirtualMethods for JSRef<'a, Element> { let value = Atom::from_slice(value.as_slice()); doc.register_named_element(*self, value); } - doc.content_changed(node, NodeStyleDamaged); + doc.content_changed(node, NodeDamage::NodeStyleDamaged); } } _ => { @@ -1126,7 +1126,7 @@ impl<'a> VirtualMethods for JSRef<'a, Element> { let node: JSRef<Node> = NodeCast::from_ref(*self); if node.is_in_doc() { let document = document_from_node(*self).root(); - document.content_changed(node, OtherNodeDamage); + document.content_changed(node, NodeDamage::OtherNodeDamage); } } } @@ -1146,7 +1146,7 @@ impl<'a> VirtualMethods for JSRef<'a, Element> { let node: JSRef<Node> = NodeCast::from_ref(*self); if node.is_in_doc() { let doc = document_from_node(*self).root(); - doc.content_changed(node, NodeStyleDamaged); + doc.content_changed(node, NodeDamage::NodeStyleDamaged); } } &atom!("id") => { @@ -1159,7 +1159,7 @@ impl<'a> VirtualMethods for JSRef<'a, Element> { let value = Atom::from_slice(value.as_slice()); doc.unregister_named_element(*self, value); } - doc.content_changed(node, NodeStyleDamaged); + doc.content_changed(node, NodeDamage::NodeStyleDamaged); } } &atom!("class") => { @@ -1167,7 +1167,7 @@ impl<'a> VirtualMethods for JSRef<'a, Element> { let node: JSRef<Node> = NodeCast::from_ref(*self); if node.is_in_doc() { let document = document_from_node(*self).root(); - document.content_changed(node, NodeStyleDamaged); + document.content_changed(node, NodeDamage::NodeStyleDamaged); } } _ => { @@ -1175,7 +1175,7 @@ impl<'a> VirtualMethods for JSRef<'a, Element> { let node: JSRef<Node> = NodeCast::from_ref(*self); if node.is_in_doc() { let doc = document_from_node(*self).root(); - doc.content_changed(node, OtherNodeDamage); + doc.content_changed(node, NodeDamage::OtherNodeDamage); } } } @@ -1251,9 +1251,9 @@ impl<'a> style::TElement<'a> for JSRef<'a, Element> { match node.type_id() { // http://www.whatwg.org/specs/web-apps/current-work/multipage/selectors.html# // selector-link - ElementNodeTypeId(HTMLAnchorElementTypeId) | - ElementNodeTypeId(HTMLAreaElementTypeId) | - ElementNodeTypeId(HTMLLinkElementTypeId) => self.get_attr(&ns!(""), &atom!("href")), + NodeTypeId::Element(ElementTypeId::HTMLAnchorElement) | + NodeTypeId::Element(ElementTypeId::HTMLAreaElement) | + NodeTypeId::Element(ElementTypeId::HTMLLinkElement) => self.get_attr(&ns!(""), &atom!("href")), _ => None, } } @@ -1283,8 +1283,8 @@ impl<'a> style::TElement<'a> for JSRef<'a, Element> { self.get_attribute(ns!(""), &atom!("id")).map(|attr| { let attr = attr.root(); match *attr.value() { - AtomAttrValue(ref val) => val.clone(), - _ => panic!("`id` attribute should be AtomAttrValue"), + AttrValue::Atom(ref val) => val.clone(), + _ => panic!("`id` attribute should be AttrValue::Atom"), } }) } @@ -1357,7 +1357,7 @@ impl<'a> ActivationElementHelpers<'a> for JSRef<'a, Element> { fn as_maybe_activatable(&'a self) -> Option<&'a Activatable + 'a> { let node: JSRef<Node> = NodeCast::from_ref(*self); match node.type_id() { - ElementNodeTypeId(HTMLInputElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLInputElement) => { let element: &'a JSRef<'a, HTMLInputElement> = HTMLInputElementCast::to_borrowed_ref(self).unwrap(); Some(element as &'a Activatable + 'a) }, diff --git a/components/script/dom/errorevent.rs b/components/script/dom/errorevent.rs index ce7eb7184a9..01e10003639 100644 --- a/components/script/dom/errorevent.rs +++ b/components/script/dom/errorevent.rs @@ -13,7 +13,7 @@ use js::jsapi::JSContext; use dom::bindings::trace::JSTraceable; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; -use dom::event::{Event, EventTypeId, ErrorEventTypeId, EventBubbles, Bubbles, DoesNotBubble, EventCancelable, Cancelable, NotCancelable}; +use dom::event::{Event, EventTypeId, EventBubbles, EventCancelable}; use servo_util::str::DOMString; use dom::bindings::cell::DOMRefCell; @@ -32,7 +32,7 @@ pub struct ErrorEvent { impl ErrorEventDerived for Event { fn is_errorevent(&self) -> bool { - *self.type_id() == ErrorEventTypeId + *self.type_id() == EventTypeId::ErrorEvent } } @@ -49,7 +49,7 @@ impl ErrorEvent { } pub fn new_uninitialized(global: &GlobalRef) -> Temporary<ErrorEvent> { - reflect_dom_object(box ErrorEvent::new_inherited(ErrorEventTypeId), + reflect_dom_object(box ErrorEvent::new_inherited(EventTypeId::ErrorEvent), *global, ErrorEventBinding::Wrap) } @@ -65,7 +65,8 @@ impl ErrorEvent { error: JSVal) -> Temporary<ErrorEvent> { let ev = ErrorEvent::new_uninitialized(global).root(); let event: JSRef<Event> = EventCast::from_ref(*ev); - event.InitEvent(type_, bubbles == Bubbles, cancelable == Cancelable); + event.InitEvent(type_, bubbles == EventBubbles::Bubbles, + cancelable == EventCancelable::Cancelable); *ev.message.borrow_mut() = message; *ev.filename.borrow_mut() = filename; ev.lineno.set(lineno); @@ -91,9 +92,9 @@ impl ErrorEvent { let col_num = init.colno.unwrap_or(0); - let bubbles = if init.parent.bubbles { Bubbles } else { DoesNotBubble }; + let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble }; - let cancelable = if init.parent.cancelable { Cancelable } else { NotCancelable }; + let cancelable = if init.parent.cancelable { EventCancelable::Cancelable } else { EventCancelable::NotCancelable }; let event = ErrorEvent::new(global, type_, bubbles, cancelable, diff --git a/components/script/dom/event.rs b/components/script/dom/event.rs index 6d7ce64bf5e..5224945f086 100644 --- a/components/script/dom/event.rs +++ b/components/script/dom/event.rs @@ -18,23 +18,23 @@ use time; #[jstraceable] pub enum EventPhase { - PhaseNone = EventConstants::NONE as int, - PhaseCapturing = EventConstants::CAPTURING_PHASE as int, - PhaseAtTarget = EventConstants::AT_TARGET as int, - PhaseBubbling = EventConstants::BUBBLING_PHASE as int, + None = EventConstants::NONE as int, + Capturing = EventConstants::CAPTURING_PHASE as int, + AtTarget = EventConstants::AT_TARGET as int, + Bubbling = EventConstants::BUBBLING_PHASE as int, } #[deriving(PartialEq)] #[jstraceable] pub enum EventTypeId { - CustomEventTypeId, - HTMLEventTypeId, - KeyboardEventTypeId, - MessageEventTypeId, - MouseEventTypeId, - ProgressEventTypeId, - UIEventTypeId, - ErrorEventTypeId + CustomEvent, + HTMLEvent, + KeyboardEvent, + MessageEvent, + MouseEvent, + ProgressEvent, + UIEvent, + ErrorEvent } #[deriving(PartialEq)] @@ -75,7 +75,7 @@ impl Event { reflector_: Reflector::new(), current_target: Default::default(), target: Default::default(), - phase: Cell::new(PhaseNone), + phase: Cell::new(EventPhase::None), type_: DOMRefCell::new("".to_string()), canceled: Cell::new(false), cancelable: Cell::new(false), @@ -90,7 +90,7 @@ impl Event { } pub fn new_uninitialized(global: GlobalRef) -> Temporary<Event> { - reflect_dom_object(box Event::new_inherited(HTMLEventTypeId), + reflect_dom_object(box Event::new_inherited(EventTypeId::HTMLEvent), global, EventBinding::Wrap) } @@ -100,15 +100,15 @@ impl Event { bubbles: EventBubbles, cancelable: EventCancelable) -> Temporary<Event> { let event = Event::new_uninitialized(global).root(); - event.InitEvent(type_, bubbles == Bubbles, cancelable == Cancelable); + event.InitEvent(type_, bubbles == EventBubbles::Bubbles, cancelable == EventCancelable::Cancelable); Temporary::from_rooted(*event) } pub fn Constructor(global: &GlobalRef, type_: DOMString, init: &EventBinding::EventInit) -> Fallible<Temporary<Event>> { - let bubbles = if init.bubbles { Bubbles } else { DoesNotBubble }; - let cancelable = if init.cancelable { Cancelable } else { NotCancelable }; + let bubbles = if init.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble }; + let cancelable = if init.cancelable { EventCancelable::Cancelable } else { EventCancelable::NotCancelable }; Ok(Event::new(*global, type_, bubbles, cancelable)) } diff --git a/components/script/dom/eventdispatcher.rs b/components/script/dom/eventdispatcher.rs index 74ffc1f5136..412b0cdcb4d 100644 --- a/components/script/dom/eventdispatcher.rs +++ b/components/script/dom/eventdispatcher.rs @@ -2,12 +2,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use dom::bindings::callback::ReportExceptions; +use dom::bindings::callback::ExceptionHandling::ReportExceptions; use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::InheritTypes::{EventTargetCast, NodeCast, NodeDerived}; use dom::bindings::js::{JS, JSRef, OptionalRootable, Root}; -use dom::eventtarget::{Capturing, Bubbling, EventTarget}; -use dom::event::{Event, PhaseAtTarget, PhaseNone, PhaseBubbling, PhaseCapturing}; +use dom::eventtarget::{EventTarget, ListenerPhase}; +use dom::event::{Event, EventPhase}; use dom::node::{Node, NodeHelpers}; use dom::virtualmethods::vtable_for; @@ -37,13 +37,13 @@ pub fn dispatch_event<'a, 'b>(target: JSRef<'a, EventTarget>, vec!() }; - event.set_phase(PhaseCapturing); + event.set_phase(EventPhase::Capturing); //FIXME: The "callback this value" should be currentTarget /* capturing */ for cur_target in chain.as_slice().iter().rev() { - let stopped = match cur_target.get_listeners_for(type_.as_slice(), Capturing) { + let stopped = match cur_target.get_listeners_for(type_.as_slice(), ListenerPhase::Capturing) { Some(listeners) => { event.set_current_target(cur_target.deref().clone()); for listener in listeners.iter() { @@ -67,7 +67,7 @@ pub fn dispatch_event<'a, 'b>(target: JSRef<'a, EventTarget>, /* at target */ if !event.stop_propagation() { - event.set_phase(PhaseAtTarget); + event.set_phase(EventPhase::AtTarget); event.set_current_target(target.clone()); let opt_listeners = target.get_listeners(type_.as_slice()); @@ -85,10 +85,10 @@ pub fn dispatch_event<'a, 'b>(target: JSRef<'a, EventTarget>, /* bubbling */ if event.bubbles() && !event.stop_propagation() { - event.set_phase(PhaseBubbling); + event.set_phase(EventPhase::Bubbling); for cur_target in chain.iter() { - let stopped = match cur_target.get_listeners_for(type_.as_slice(), Bubbling) { + let stopped = match cur_target.get_listeners_for(type_.as_slice(), ListenerPhase::Bubbling) { Some(listeners) => { event.set_current_target(cur_target.deref().clone()); for listener in listeners.iter() { @@ -133,7 +133,7 @@ pub fn dispatch_event<'a, 'b>(target: JSRef<'a, EventTarget>, } event.set_dispatching(false); - event.set_phase(PhaseNone); + event.set_phase(EventPhase::None); event.clear_current_target(); !event.DefaultPrevented() diff --git a/components/script/dom/eventtarget.rs b/components/script/dom/eventtarget.rs index 394b66e6acc..3b353bf27de 100644 --- a/components/script/dom/eventtarget.rs +++ b/components/script/dom/eventtarget.rs @@ -7,14 +7,15 @@ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::EventListenerBinding::EventListener; use dom::bindings::codegen::Bindings::EventTargetBinding::EventTargetMethods; -use dom::bindings::error::{Fallible, InvalidState, report_pending_exception}; +use dom::bindings::error::{Fallible, report_pending_exception}; +use dom::bindings::error::Error::InvalidState; use dom::bindings::js::JSRef; use dom::bindings::utils::{Reflectable, Reflector}; use dom::event::Event; use dom::eventdispatcher::dispatch_event; use dom::node::NodeTypeId; -use dom::workerglobalscope::WorkerGlobalScopeId; -use dom::xmlhttprequest::XMLHttpRequestId; +use dom::workerglobalscope::WorkerGlobalScopeTypeId; +use dom::xmlhttprequesteventtarget::XMLHttpRequestEventTargetTypeId; use dom::virtualmethods::VirtualMethods; use js::jsapi::{JS_CompileUCFunction, JS_GetFunctionObject, JS_CloneFunctionObject}; use js::jsapi::{JSContext, JSObject}; @@ -37,12 +38,12 @@ pub enum ListenerPhase { #[deriving(PartialEq)] #[jstraceable] pub enum EventTargetTypeId { - NodeTargetTypeId(NodeTypeId), - WebSocketTypeId, - WindowTypeId, - WorkerTypeId, - WorkerGlobalScopeTypeId(WorkerGlobalScopeId), - XMLHttpRequestTargetTypeId(XMLHttpRequestId) + Node(NodeTypeId), + WebSocket, + Window, + Worker, + WorkerGlobalScope(WorkerGlobalScopeTypeId), + XMLHttpRequestEventTarget(XMLHttpRequestEventTargetTypeId) } #[deriving(PartialEq)] @@ -55,7 +56,8 @@ pub enum EventListenerType { impl EventListenerType { fn get_listener(&self) -> EventListener { match *self { - Additive(listener) | Inline(listener) => listener + EventListenerType::Additive(listener) | + EventListenerType::Inline(listener) => listener } } } @@ -148,7 +150,7 @@ impl<'a> EventTargetHelpers for JSRef<'a, EventTarget> { let idx = entries.iter().position(|&entry| { match entry.listener { - Inline(_) => true, + EventListenerType::Inline(_) => true, _ => false, } }); @@ -156,7 +158,7 @@ impl<'a> EventTargetHelpers for JSRef<'a, EventTarget> { match idx { Some(idx) => { match listener { - Some(listener) => entries[idx].listener = Inline(listener), + Some(listener) => entries[idx].listener = EventListenerType::Inline(listener), None => { entries.remove(idx); } @@ -165,8 +167,8 @@ impl<'a> EventTargetHelpers for JSRef<'a, EventTarget> { None => { if listener.is_some() { entries.push(EventListenerEntry { - phase: Bubbling, - listener: Inline(listener.unwrap()), + phase: ListenerPhase::Bubbling, + listener: EventListenerType::Inline(listener.unwrap()), }); } } @@ -178,7 +180,7 @@ impl<'a> EventTargetHelpers for JSRef<'a, EventTarget> { let entries = handlers.get(&ty); entries.and_then(|entries| entries.iter().find(|entry| { match entry.listener { - Inline(_) => true, + EventListenerType::Inline(_) => true, _ => false, } }).map(|entry| entry.listener.get_listener())) @@ -254,10 +256,10 @@ impl<'a> EventTargetMethods for JSRef<'a, EventTarget> { Vacant(entry) => entry.set(vec!()), }; - let phase = if capture { Capturing } else { Bubbling }; + let phase = if capture { ListenerPhase::Capturing } else { ListenerPhase::Bubbling }; let new_entry = EventListenerEntry { phase: phase, - listener: Additive(listener) + listener: EventListenerType::Additive(listener) }; if entry.as_slice().position_elem(&new_entry).is_none() { entry.push(new_entry); @@ -276,10 +278,10 @@ impl<'a> EventTargetMethods for JSRef<'a, EventTarget> { let mut handlers = self.handlers.borrow_mut(); let mut entry = handlers.get_mut(&ty); for entry in entry.iter_mut() { - let phase = if capture { Capturing } else { Bubbling }; + let phase = if capture { ListenerPhase::Capturing } else { ListenerPhase::Bubbling }; let old_entry = EventListenerEntry { phase: phase, - listener: Additive(listener) + listener: EventListenerType::Additive(listener) }; let position = entry.as_slice().position_elem(&old_entry); for &position in position.iter() { diff --git a/components/script/dom/file.rs b/components/script/dom/file.rs index 985386321c3..f79631c9d52 100644 --- a/components/script/dom/file.rs +++ b/components/script/dom/file.rs @@ -7,7 +7,7 @@ use dom::bindings::codegen::Bindings::FileBinding::FileMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; -use dom::blob::{Blob, BlobType, FileTypeId}; +use dom::blob::{Blob, BlobTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -17,7 +17,7 @@ pub struct File { } impl File { - fn new_inherited(global: &GlobalRef, type_: BlobType, + fn new_inherited(global: &GlobalRef, type_: BlobTypeId, _file_bits: JSRef<Blob>, name: DOMString) -> File { File { blob: Blob::new_inherited(global, type_, None), @@ -28,7 +28,7 @@ impl File { } pub fn new(global: &GlobalRef, file_bits: JSRef<Blob>, name: DOMString) -> Temporary<File> { - reflect_dom_object(box File::new_inherited(global, FileTypeId, file_bits, name), + reflect_dom_object(box File::new_inherited(global, BlobTypeId::File, file_bits, name), *global, FileBinding::Wrap) } diff --git a/components/script/dom/formdata.rs b/components/script/dom/formdata.rs index 0c9a5e81f8b..5a76dda5511 100644 --- a/components/script/dom/formdata.rs +++ b/components/script/dom/formdata.rs @@ -6,7 +6,8 @@ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::FormDataBinding; use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods; use dom::bindings::codegen::InheritTypes::FileCast; -use dom::bindings::codegen::UnionTypes::FileOrString::{FileOrString, eFile, eString}; +use dom::bindings::codegen::UnionTypes::FileOrString; +use dom::bindings::codegen::UnionTypes::FileOrString::{eFile, eString}; use dom::bindings::error::{Fallible}; use dom::bindings::global::{GlobalRef, GlobalField}; use dom::bindings::js::{JS, JSRef, Temporary}; @@ -57,7 +58,7 @@ impl FormData { impl<'a> FormDataMethods for JSRef<'a, FormData> { #[allow(unrooted_must_root)] fn Append(self, name: DOMString, value: JSRef<Blob>, filename: Option<DOMString>) { - let file = FileData(JS::from_rooted(self.get_file_from_blob(value, filename))); + 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) { Occupied(entry) => entry.into_mut().push(file), @@ -70,8 +71,8 @@ impl<'a> FormDataMethods for JSRef<'a, FormData> { fn Append_(self, name: DOMString, value: DOMString) { let mut data = self.data.borrow_mut(); match data.entry(name) { - Occupied(entry) => entry.into_mut().push(StringData(value)), - Vacant (entry) => { entry.set(vec!(StringData(value))); }, + Occupied(entry) => entry.into_mut().push(FormDatum::StringData(value)), + Vacant (entry) => { entry.set(vec!(FormDatum::StringData(value))); }, } } @@ -82,8 +83,8 @@ impl<'a> FormDataMethods for JSRef<'a, FormData> { fn Get(self, name: DOMString) -> Option<FileOrString> { if self.data.borrow().contains_key_equiv(&name) { match (*self.data.borrow())[name][0].clone() { - StringData(ref s) => Some(eString(s.clone())), - FileData(ref f) => { + FormDatum::StringData(ref s) => Some(eString(s.clone())), + FormDatum::FileData(ref f) => { Some(eFile(f.clone())) } } @@ -97,12 +98,12 @@ impl<'a> FormDataMethods for JSRef<'a, FormData> { } #[allow(unrooted_must_root)] fn Set(self, name: DOMString, value: JSRef<Blob>, filename: Option<DOMString>) { - let file = FileData(JS::from_rooted(self.get_file_from_blob(value, filename))); + let file = FormDatum::FileData(JS::from_rooted(self.get_file_from_blob(value, filename))); self.data.borrow_mut().insert(name, vec!(file)); } fn Set_(self, name: DOMString, value: DOMString) { - self.data.borrow_mut().insert(name, vec!(StringData(value))); + self.data.borrow_mut().insert(name, vec!(FormDatum::StringData(value))); } } diff --git a/components/script/dom/htmlanchorelement.rs b/components/script/dom/htmlanchorelement.rs index c712ddad60e..10d574672a3 100644 --- a/components/script/dom/htmlanchorelement.rs +++ b/components/script/dom/htmlanchorelement.rs @@ -14,11 +14,11 @@ use dom::bindings::js::{MutNullableJS, JSRef, Temporary, OptionalRootable}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::{Document, DocumentHelpers}; use dom::domtokenlist::DOMTokenList; -use dom::element::{Element, AttributeHandlers, HTMLAnchorElementTypeId}; +use dom::element::{Element, AttributeHandlers, ElementTypeId}; use dom::event::Event; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, NodeHelpers, ElementNodeTypeId}; +use dom::node::{Node, NodeHelpers, NodeTypeId}; use dom::virtualmethods::VirtualMethods; use std::default::Default; @@ -33,14 +33,14 @@ pub struct HTMLAnchorElement { impl HTMLAnchorElementDerived for EventTarget { fn is_htmlanchorelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLAnchorElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLAnchorElement)) } } impl HTMLAnchorElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLAnchorElement { HTMLAnchorElement { - htmlelement: HTMLElement::new_inherited(HTMLAnchorElementTypeId, localName, prefix, document), + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLAnchorElement, localName, prefix, document), rel_list: Default::default(), } } diff --git a/components/script/dom/htmlappletelement.rs b/components/script/dom/htmlappletelement.rs index 4360d288b2c..f54a3f32125 100644 --- a/components/script/dom/htmlappletelement.rs +++ b/components/script/dom/htmlappletelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLAppletElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLAppletElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLAppletElement { impl HTMLAppletElementDerived for EventTarget { fn is_htmlappletelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLAppletElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLAppletElement)) } } impl HTMLAppletElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLAppletElement { HTMLAppletElement { - htmlelement: HTMLElement::new_inherited(HTMLAppletElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLAppletElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlareaelement.rs b/components/script/dom/htmlareaelement.rs index fc4c29bc085..1ede87d380d 100644 --- a/components/script/dom/htmlareaelement.rs +++ b/components/script/dom/htmlareaelement.rs @@ -11,10 +11,10 @@ use dom::bindings::js::{MutNullableJS, JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::domtokenlist::DOMTokenList; -use dom::element::HTMLAreaElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, NodeHelpers, ElementNodeTypeId}; +use dom::node::{Node, NodeHelpers, NodeTypeId}; use dom::virtualmethods::VirtualMethods; use std::default::Default; @@ -31,14 +31,14 @@ pub struct HTMLAreaElement { impl HTMLAreaElementDerived for EventTarget { fn is_htmlareaelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLAreaElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLAreaElement)) } } impl HTMLAreaElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLAreaElement { HTMLAreaElement { - htmlelement: HTMLElement::new_inherited(HTMLAreaElementTypeId, localName, prefix, document), + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLAreaElement, localName, prefix, document), rel_list: Default::default(), } } diff --git a/components/script/dom/htmlaudioelement.rs b/components/script/dom/htmlaudioelement.rs index 216b255816a..d850d65a309 100644 --- a/components/script/dom/htmlaudioelement.rs +++ b/components/script/dom/htmlaudioelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLAudioElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLAudioElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlmediaelement::HTMLMediaElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLAudioElement { impl HTMLAudioElementDerived for EventTarget { fn is_htmlaudioelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLAudioElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLAudioElement)) } } impl HTMLAudioElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLAudioElement { HTMLAudioElement { - htmlmediaelement: HTMLMediaElement::new_inherited(HTMLAudioElementTypeId, localName, prefix, document) + htmlmediaelement: HTMLMediaElement::new_inherited(ElementTypeId::HTMLAudioElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlbaseelement.rs b/components/script/dom/htmlbaseelement.rs index a91b6bd9791..cc72295080c 100644 --- a/components/script/dom/htmlbaseelement.rs +++ b/components/script/dom/htmlbaseelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLBaseElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLBaseElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLBaseElement { impl HTMLBaseElementDerived for EventTarget { fn is_htmlbaseelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLBaseElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLBaseElement)) } } impl HTMLBaseElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLBaseElement { HTMLBaseElement { - htmlelement: HTMLElement::new_inherited(HTMLBaseElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLBaseElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlbodyelement.rs b/components/script/dom/htmlbodyelement.rs index 917b02913a7..a692243db2d 100644 --- a/components/script/dom/htmlbodyelement.rs +++ b/components/script/dom/htmlbodyelement.rs @@ -11,10 +11,10 @@ use dom::bindings::codegen::InheritTypes::{HTMLBodyElementDerived, HTMLElementCa use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLBodyElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId, EventTargetHelpers}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId, EventTargetHelpers}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId, window_from_node}; +use dom::node::{Node, NodeTypeId, window_from_node}; use dom::virtualmethods::VirtualMethods; use cssparser::RGBA; @@ -29,7 +29,7 @@ pub struct HTMLBodyElement { impl HTMLBodyElementDerived for EventTarget { fn is_htmlbodyelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLBodyElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLBodyElement)) } } @@ -37,7 +37,7 @@ impl HTMLBodyElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLBodyElement { HTMLBodyElement { - htmlelement: HTMLElement::new_inherited(HTMLBodyElementTypeId, + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLBodyElement, localName, prefix, document), diff --git a/components/script/dom/htmlbrelement.rs b/components/script/dom/htmlbrelement.rs index e2716c39357..fdfe2abd98e 100644 --- a/components/script/dom/htmlbrelement.rs +++ b/components/script/dom/htmlbrelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLBRElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLBRElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLBRElement { impl HTMLBRElementDerived for EventTarget { fn is_htmlbrelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLBRElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLBRElement)) } } impl HTMLBRElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLBRElement { HTMLBRElement { - htmlelement: HTMLElement::new_inherited(HTMLBRElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLBRElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlbuttonelement.rs b/components/script/dom/htmlbuttonelement.rs index 58019cbc5f5..d0ca30025d5 100644 --- a/components/script/dom/htmlbuttonelement.rs +++ b/components/script/dom/htmlbuttonelement.rs @@ -11,10 +11,10 @@ use dom::bindings::codegen::InheritTypes::{HTMLButtonElementDerived, HTMLFieldSe use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::{AttributeHandlers, Element, HTMLButtonElementTypeId}; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::{AttributeHandlers, Element, ElementTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId, window_from_node}; +use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; @@ -29,14 +29,14 @@ pub struct HTMLButtonElement { impl HTMLButtonElementDerived for EventTarget { fn is_htmlbuttonelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLButtonElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLButtonElement)) } } impl HTMLButtonElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLButtonElement { HTMLButtonElement { - htmlelement: HTMLElement::new_inherited(HTMLButtonElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLButtonElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlcanvaselement.rs b/components/script/dom/htmlcanvaselement.rs index 5de1ccd5400..70da494f314 100644 --- a/components/script/dom/htmlcanvaselement.rs +++ b/components/script/dom/htmlcanvaselement.rs @@ -13,10 +13,10 @@ use dom::bindings::js::{MutNullableJS, JSRef, Temporary, OptionalSettable}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::canvasrenderingcontext2d::CanvasRenderingContext2D; use dom::document::Document; -use dom::element::{Element, HTMLCanvasElementTypeId, AttributeHandlers}; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::{Element, ElementTypeId, AttributeHandlers}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId, window_from_node}; +use dom::node::{Node, NodeTypeId, window_from_node}; use dom::virtualmethods::VirtualMethods; use servo_util::str::{DOMString, parse_unsigned_integer}; @@ -39,14 +39,14 @@ pub struct HTMLCanvasElement { impl HTMLCanvasElementDerived for EventTarget { fn is_htmlcanvaselement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLCanvasElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLCanvasElement)) } } impl HTMLCanvasElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLCanvasElement { HTMLCanvasElement { - htmlelement: HTMLElement::new_inherited(HTMLCanvasElementTypeId, localName, prefix, document), + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLCanvasElement, localName, prefix, document), context: Default::default(), width: Cell::new(DEFAULT_WIDTH), height: Cell::new(DEFAULT_HEIGHT), diff --git a/components/script/dom/htmlcollection.rs b/components/script/dom/htmlcollection.rs index 86f977c843a..647b5ee66af 100644 --- a/components/script/dom/htmlcollection.rs +++ b/components/script/dom/htmlcollection.rs @@ -53,7 +53,7 @@ impl HTMLCollection { impl HTMLCollection { pub fn create(window: JSRef<Window>, root: JSRef<Node>, filter: Box<CollectionFilter+'static>) -> Temporary<HTMLCollection> { - HTMLCollection::new(window, Live(JS::from_rooted(root), filter)) + HTMLCollection::new(window, CollectionTypeId::Live(JS::from_rooted(root), filter)) } fn all_elements(window: JSRef<Window>, root: JSRef<Node>, @@ -178,8 +178,8 @@ impl<'a> HTMLCollectionMethods for JSRef<'a, HTMLCollection> { // http://dom.spec.whatwg.org/#dom-htmlcollection-length fn Length(self) -> u32 { match self.collection { - Static(ref elems) => elems.len() as u32, - Live(ref root, ref filter) => { + CollectionTypeId::Static(ref elems) => elems.len() as u32, + CollectionTypeId::Live(ref root, ref filter) => { let root = root.root(); HTMLCollection::traverse(*root) .filter(|element| filter.filter(*element, *root)) @@ -191,11 +191,11 @@ impl<'a> HTMLCollectionMethods for JSRef<'a, HTMLCollection> { // http://dom.spec.whatwg.org/#dom-htmlcollection-item fn Item(self, index: u32) -> Option<Temporary<Element>> { match self.collection { - Static(ref elems) => elems + CollectionTypeId::Static(ref elems) => elems .as_slice() .get(index as uint) .map(|elem| Temporary::new(elem.clone())), - Live(ref root, ref filter) => { + CollectionTypeId::Live(ref root, ref filter) => { let root = root.root(); HTMLCollection::traverse(*root) .filter(|element| filter.filter(*element, *root)) @@ -215,13 +215,13 @@ impl<'a> HTMLCollectionMethods for JSRef<'a, HTMLCollection> { // Step 2. match self.collection { - Static(ref elems) => elems.iter() + CollectionTypeId::Static(ref elems) => elems.iter() .map(|elem| elem.root()) .find(|elem| { elem.get_string_attribute(&atom!("name")) == key || elem.get_string_attribute(&atom!("id")) == key }) .map(|maybe_elem| Temporary::from_rooted(*maybe_elem)), - Live(ref root, ref filter) => { + CollectionTypeId::Live(ref root, ref filter) => { let root = root.root(); HTMLCollection::traverse(*root) .filter(|element| filter.filter(*element, *root)) diff --git a/components/script/dom/htmldataelement.rs b/components/script/dom/htmldataelement.rs index 33dfbfd7bd7..85480e4e41f 100644 --- a/components/script/dom/htmldataelement.rs +++ b/components/script/dom/htmldataelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLDataElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLDataElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLDataElement { impl HTMLDataElementDerived for EventTarget { fn is_htmldataelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLDataElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLDataElement)) } } impl HTMLDataElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLDataElement { HTMLDataElement { - htmlelement: HTMLElement::new_inherited(HTMLDataElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLDataElement, localName, prefix, document) } } diff --git a/components/script/dom/htmldatalistelement.rs b/components/script/dom/htmldatalistelement.rs index 210c22b33a3..0083af0cc25 100644 --- a/components/script/dom/htmldatalistelement.rs +++ b/components/script/dom/htmldatalistelement.rs @@ -9,11 +9,11 @@ use dom::bindings::codegen::InheritTypes::NodeCast; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::{Element, HTMLDataListElementTypeId}; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::{Element, ElementTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlcollection::{HTMLCollection, CollectionFilter}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId, window_from_node}; +use dom::node::{Node, NodeTypeId, window_from_node}; use servo_util::str::DOMString; #[dom_struct] @@ -23,14 +23,14 @@ pub struct HTMLDataListElement { impl HTMLDataListElementDerived for EventTarget { fn is_htmldatalistelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLDataListElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLDataListElement)) } } impl HTMLDataListElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLDataListElement { HTMLDataListElement { - htmlelement: HTMLElement::new_inherited(HTMLDataListElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLDataListElement, localName, prefix, document) } } diff --git a/components/script/dom/htmldirectoryelement.rs b/components/script/dom/htmldirectoryelement.rs index 21c675458b9..3969c56e886 100644 --- a/components/script/dom/htmldirectoryelement.rs +++ b/components/script/dom/htmldirectoryelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLDirectoryElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLDirectoryElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLDirectoryElement { impl HTMLDirectoryElementDerived for EventTarget { fn is_htmldirectoryelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLDirectoryElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLDirectoryElement)) } } impl HTMLDirectoryElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLDirectoryElement { HTMLDirectoryElement { - htmlelement: HTMLElement::new_inherited(HTMLDirectoryElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLDirectoryElement, localName, prefix, document) } } diff --git a/components/script/dom/htmldivelement.rs b/components/script/dom/htmldivelement.rs index 899c35f571a..a5f9eb3238c 100644 --- a/components/script/dom/htmldivelement.rs +++ b/components/script/dom/htmldivelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLDivElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLDivElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLDivElement { impl HTMLDivElementDerived for EventTarget { fn is_htmldivelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLDivElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLDivElement)) } } impl HTMLDivElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLDivElement { HTMLDivElement { - htmlelement: HTMLElement::new_inherited(HTMLDivElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLDivElement, localName, prefix, document) } } diff --git a/components/script/dom/htmldlistelement.rs b/components/script/dom/htmldlistelement.rs index 38828fb3957..aeb23b7afb4 100644 --- a/components/script/dom/htmldlistelement.rs +++ b/components/script/dom/htmldlistelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLDListElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLDListElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLDListElement { impl HTMLDListElementDerived for EventTarget { fn is_htmldlistelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLDListElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLDListElement)) } } impl HTMLDListElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLDListElement { HTMLDListElement { - htmlelement: HTMLElement::new_inherited(HTMLDListElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLDListElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlelement.rs b/components/script/dom/htmlelement.rs index 010946fabc4..f8a8ea7ce5c 100644 --- a/components/script/dom/htmlelement.rs +++ b/components/script/dom/htmlelement.rs @@ -15,9 +15,9 @@ use dom::bindings::codegen::InheritTypes::{HTMLElementDerived, HTMLBodyElementDe use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::{Element, ElementTypeId, ElementTypeId_, HTMLElementTypeId, ActivationElementHelpers}; -use dom::eventtarget::{EventTarget, EventTargetHelpers, NodeTargetTypeId}; -use dom::node::{Node, ElementNodeTypeId, window_from_node}; +use dom::element::{Element, ElementTypeId, ActivationElementHelpers}; +use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; +use dom::node::{Node, NodeTypeId, window_from_node}; use dom::virtualmethods::VirtualMethods; use servo_util::str::DOMString; @@ -32,8 +32,8 @@ pub struct HTMLElement { impl HTMLElementDerived for EventTarget { fn is_htmlelement(&self) -> bool { match *self.type_id() { - NodeTargetTypeId(ElementNodeTypeId(ElementTypeId_)) => false, - NodeTargetTypeId(ElementNodeTypeId(_)) => true, + EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::Element)) => false, + EventTargetTypeId::Node(NodeTypeId::Element(_)) => true, _ => false } } @@ -48,7 +48,7 @@ impl HTMLElement { #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLElement> { - let element = HTMLElement::new_inherited(HTMLElementTypeId, localName, prefix, document); + let element = HTMLElement::new_inherited(ElementTypeId::HTMLElement, localName, prefix, document); Node::reflect_node(box element, document, HTMLElementBinding::Wrap) } } diff --git a/components/script/dom/htmlembedelement.rs b/components/script/dom/htmlembedelement.rs index f99d0f821df..fd4945f2ded 100644 --- a/components/script/dom/htmlembedelement.rs +++ b/components/script/dom/htmlembedelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLEmbedElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLEmbedElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLEmbedElement { impl HTMLEmbedElementDerived for EventTarget { fn is_htmlembedelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLEmbedElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLEmbedElement)) } } impl HTMLEmbedElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLEmbedElement { HTMLEmbedElement { - htmlelement: HTMLElement::new_inherited(HTMLEmbedElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLEmbedElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlfieldsetelement.rs b/components/script/dom/htmlfieldsetelement.rs index 3ed4a82200c..a2396a847c9 100644 --- a/components/script/dom/htmlfieldsetelement.rs +++ b/components/script/dom/htmlfieldsetelement.rs @@ -11,12 +11,11 @@ use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLLegendElementDer use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::{AttributeHandlers, Element, ElementHelpers, HTMLFieldSetElementTypeId, HTMLButtonElementTypeId}; -use dom::element::{HTMLInputElementTypeId, HTMLSelectElementTypeId, HTMLTextAreaElementTypeId}; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::{AttributeHandlers, Element, ElementHelpers, ElementTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlcollection::{HTMLCollection, CollectionFilter}; use dom::htmlelement::HTMLElement; -use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId, window_from_node}; +use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; @@ -30,14 +29,14 @@ pub struct HTMLFieldSetElement { impl HTMLFieldSetElementDerived for EventTarget { fn is_htmlfieldsetelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLFieldSetElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLFieldSetElement)) } } impl HTMLFieldSetElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLFieldSetElement { HTMLFieldSetElement { - htmlelement: HTMLElement::new_inherited(HTMLFieldSetElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLFieldSetElement, localName, prefix, document) } } @@ -101,10 +100,10 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLFieldSetElement> { }).collect(); for descendant in filtered.iter().flat_map(|child| child.traverse_preorder()) { match descendant.type_id() { - ElementNodeTypeId(HTMLButtonElementTypeId) | - ElementNodeTypeId(HTMLInputElementTypeId) | - ElementNodeTypeId(HTMLSelectElementTypeId) | - ElementNodeTypeId(HTMLTextAreaElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLButtonElement) | + NodeTypeId::Element(ElementTypeId::HTMLInputElement) | + NodeTypeId::Element(ElementTypeId::HTMLSelectElement) | + NodeTypeId::Element(ElementTypeId::HTMLTextAreaElement) => { descendant.set_disabled_state(true); descendant.set_enabled_state(false); }, @@ -133,10 +132,10 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLFieldSetElement> { }).collect(); for descendant in filtered.iter().flat_map(|child| child.traverse_preorder()) { match descendant.type_id() { - ElementNodeTypeId(HTMLButtonElementTypeId) | - ElementNodeTypeId(HTMLInputElementTypeId) | - ElementNodeTypeId(HTMLSelectElementTypeId) | - ElementNodeTypeId(HTMLTextAreaElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLButtonElement) | + NodeTypeId::Element(ElementTypeId::HTMLInputElement) | + NodeTypeId::Element(ElementTypeId::HTMLSelectElement) | + NodeTypeId::Element(ElementTypeId::HTMLTextAreaElement) => { descendant.check_disabled_attribute(); descendant.check_ancestors_disabled_state_for_form_control(); }, diff --git a/components/script/dom/htmlfontelement.rs b/components/script/dom/htmlfontelement.rs index 3edf195f2dc..4303668b0e5 100644 --- a/components/script/dom/htmlfontelement.rs +++ b/components/script/dom/htmlfontelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLFontElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLFontElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLFontElement { impl HTMLFontElementDerived for EventTarget { fn is_htmlfontelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLFontElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLFontElement)) } } impl HTMLFontElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLFontElement { HTMLFontElement { - htmlelement: HTMLElement::new_inherited(HTMLFontElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLFontElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlformelement.rs b/components/script/dom/htmlformelement.rs index 62f5e3aa62e..58a0e0e175b 100644 --- a/components/script/dom/htmlformelement.rs +++ b/components/script/dom/htmlformelement.rs @@ -14,19 +14,18 @@ use dom::bindings::global::Window; use dom::bindings::js::{JSRef, Temporary, OptionalRootable}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::{Document, DocumentHelpers}; -use dom::element::{Element, AttributeHandlers, HTMLFormElementTypeId, HTMLTextAreaElementTypeId, HTMLDataListElementTypeId}; -use dom::element::{HTMLInputElementTypeId, HTMLButtonElementTypeId, HTMLObjectElementTypeId, HTMLSelectElementTypeId}; -use dom::element::{HTMLOutputElementTypeId}; -use dom::event::{Event, EventHelpers, Bubbles, Cancelable}; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::{Element, AttributeHandlers, ElementTypeId}; +use dom::event::{Event, EventHelpers, EventBubbles, EventCancelable}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::htmlinputelement::HTMLInputElement; use dom::htmltextareaelement::HTMLTextAreaElement; -use dom::node::{Node, NodeHelpers, ElementNodeTypeId, document_from_node, window_from_node}; +use dom::node::{Node, NodeHelpers, NodeTypeId, document_from_node, window_from_node}; use hyper::method::Post; use servo_msg::constellation_msg::LoadData; use servo_util::str::DOMString; -use script_task::{ScriptChan, TriggerLoadMsg}; +use script_task::ScriptChan; +use script_task::ScriptMsg::TriggerLoadMsg; use std::ascii::OwnedAsciiExt; use url::UrlParser; use url::form_urlencoded::serialize; @@ -42,14 +41,14 @@ pub struct HTMLFormElement { impl HTMLFormElementDerived for EventTarget { fn is_htmlformelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLFormElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLFormElement)) } } impl HTMLFormElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLFormElement { HTMLFormElement { - htmlelement: HTMLElement::new_inherited(HTMLFormElementTypeId, localName, prefix, document), + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLFormElement, localName, prefix, document), marked_for_reset: Cell::new(false), } } @@ -122,12 +121,12 @@ impl<'a> HTMLFormElementMethods for JSRef<'a, HTMLFormElement> { // https://html.spec.whatwg.org/multipage/forms.html#the-form-element:concept-form-submit fn Submit(self) { - self.submit(FromFormSubmitMethod, FormElement(self)); + self.submit(SubmittedFrom::FromFormSubmitMethod, FormSubmitter::FormElement(self)); } // https://html.spec.whatwg.org/multipage/forms.html#dom-form-reset fn Reset(self) { - self.reset(FromFormResetMethod); + self.reset(ResetFrom::FromFormResetMethod); } } @@ -160,7 +159,8 @@ impl<'a> HTMLFormElementHelpers for JSRef<'a, HTMLFormElement> { // TODO: Handle validation let event = Event::new(Window(*win), "submit".to_string(), - Bubbles, Cancelable).root(); + EventBubbles::Bubbles, + EventCancelable::Cancelable).root(); event.set_trusted(true); let target: JSRef<EventTarget> = EventTargetCast::from_ref(self); target.DispatchEvent(*event).ok(); @@ -185,23 +185,23 @@ impl<'a> HTMLFormElementHelpers for JSRef<'a, HTMLFormElement> { // TODO: Handle browsing contexts, partially loaded documents (step 16-17) let parsed_data = match enctype { - UrlEncoded => serialize(form_data.iter().map(|d| (d.name.as_slice(), d.value.as_slice())), None), + FormEncType::UrlEncoded => serialize(form_data.iter().map(|d| (d.name.as_slice(), d.value.as_slice()))), _ => "".to_string() // TODO: Add serializers for the other encoding types }; let mut load_data = LoadData::new(action_components); // Step 18 match (scheme.as_slice(), method) { - (_, FormDialog) => return, // Unimplemented - ("http", FormGet) | ("https", FormGet) => { + (_, FormMethod::FormDialog) => return, // Unimplemented + ("http", FormMethod::FormGet) | ("https", FormMethod::FormGet) => { load_data.url.query = Some(parsed_data); }, - ("http", FormPost) | ("https", FormPost) => { + ("http", FormMethod::FormPost) | ("https", FormMethod::FormPost) => { load_data.method = Post; load_data.data = Some(parsed_data.into_bytes()); }, // https://html.spec.whatwg.org/multipage/forms.html#submit-get-action - ("ftp", _) | ("javascript", _) | ("data", FormGet) => (), + ("ftp", _) | ("javascript", _) | ("data", FormMethod::FormGet) => (), _ => return // Unimplemented (data and mailto) } @@ -250,12 +250,12 @@ impl<'a> HTMLFormElementHelpers for JSRef<'a, HTMLFormElement> { if child.get_disabled_state() { return None; } - if child.ancestors().any(|a| a.type_id() == ElementNodeTypeId(HTMLDataListElementTypeId)) { + if child.ancestors().any(|a| a.type_id() == NodeTypeId::Element(ElementTypeId::HTMLDataListElement)) { return None; } // XXXManishearth don't include it if it is a button but not the submitter match child.type_id() { - ElementNodeTypeId(HTMLInputElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLInputElement) => { let input: JSRef<HTMLInputElement> = HTMLInputElementCast::to_ref(child).unwrap(); let ty = input.Type(); let name = input.Name(); @@ -275,7 +275,7 @@ impl<'a> HTMLFormElementHelpers for JSRef<'a, HTMLFormElement> { let mut value = input.Value(); let is_submitter = match submitter { - Some(InputElement(s)) => { + Some(FormSubmitter::InputElement(s)) => { input == s }, _ => false @@ -302,19 +302,19 @@ impl<'a> HTMLFormElementHelpers for JSRef<'a, HTMLFormElement> { }) } } - ElementNodeTypeId(HTMLButtonElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLButtonElement) => { // Unimplemented None } - ElementNodeTypeId(HTMLSelectElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLSelectElement) => { // Unimplemented None } - ElementNodeTypeId(HTMLObjectElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLObjectElement) => { // Unimplemented None } - ElementNodeTypeId(HTMLTextAreaElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLTextAreaElement) => { // Unimplemented None } @@ -347,7 +347,8 @@ impl<'a> HTMLFormElementHelpers for JSRef<'a, HTMLFormElement> { let win = window_from_node(self).root(); let event = Event::new(Window(*win), "reset".to_string(), - Bubbles, Cancelable).root(); + EventBubbles::Bubbles, + EventCancelable::Cancelable).root(); let target: JSRef<EventTarget> = EventTargetCast::from_ref(self); target.DispatchEvent(*event).ok(); if event.DefaultPrevented() { @@ -360,26 +361,26 @@ impl<'a> HTMLFormElementHelpers for JSRef<'a, HTMLFormElement> { // by the form, but good enough until html5ever lands for child in node.traverse_preorder() { match child.type_id() { - ElementNodeTypeId(HTMLInputElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLInputElement) => { let input: JSRef<HTMLInputElement> = HTMLInputElementCast::to_ref(child) .unwrap(); input.reset() } // TODO HTMLKeygenElement unimplemented - //ElementNodeTypeID(HTMLKeygenElementTypeId) => { + //NodeTypeId::Element(ElementTypeId::HTMLKeygenElement) => { // // Unimplemented // {} //} - ElementNodeTypeId(HTMLSelectElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLSelectElement) => { // Unimplemented {} } - ElementNodeTypeId(HTMLTextAreaElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLTextAreaElement) => { let textarea: JSRef<HTMLTextAreaElement> = HTMLTextAreaElementCast::to_ref(child) .unwrap(); textarea.reset() } - ElementNodeTypeId(HTMLOutputElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLOutputElement) => { // Unimplemented {} } @@ -424,8 +425,8 @@ pub enum FormSubmitter<'a> { impl<'a> FormSubmitter<'a> { fn action(&self) -> DOMString { match *self { - FormElement(form) => form.Action(), - InputElement(input_element) => { + FormSubmitter::FormElement(form) => form.Action(), + FormSubmitter::InputElement(input_element) => { // FIXME(pcwalton): Make this a static atom. input_element.get_form_attribute(&Atom::from_slice("formaction"), |i| i.FormAction(), @@ -436,8 +437,8 @@ impl<'a> FormSubmitter<'a> { fn enctype(&self) -> FormEncType { let attr = match *self { - FormElement(form) => form.Enctype(), - InputElement(input_element) => { + FormSubmitter::FormElement(form) => form.Enctype(), + FormSubmitter::InputElement(input_element) => { // FIXME(pcwalton): Make this a static atom. input_element.get_form_attribute(&Atom::from_slice("formenctype"), |i| i.FormEnctype(), @@ -445,18 +446,18 @@ impl<'a> FormSubmitter<'a> { } }; match attr.as_slice() { - "multipart/form-data" => FormDataEncoded, - "text/plain" => TextPlainEncoded, + "multipart/form-data" => FormEncType::FormDataEncoded, + "text/plain" => FormEncType::TextPlainEncoded, // https://html.spec.whatwg.org/multipage/forms.html#attr-fs-enctype // urlencoded is the default - _ => UrlEncoded + _ => FormEncType::UrlEncoded } } fn method(&self) -> FormMethod { let attr = match *self { - FormElement(form) => form.Method(), - InputElement(input_element) => { + FormSubmitter::FormElement(form) => form.Method(), + FormSubmitter::InputElement(input_element) => { // FIXME(pcwalton): Make this a static atom. input_element.get_form_attribute(&Atom::from_slice("formmethod"), |i| i.FormMethod(), @@ -464,16 +465,16 @@ impl<'a> FormSubmitter<'a> { } }; match attr.as_slice() { - "dialog" => FormDialog, - "post" => FormPost, - _ => FormGet + "dialog" => FormMethod::FormDialog, + "post" => FormMethod::FormPost, + _ => FormMethod::FormGet } } fn target(&self) -> DOMString { match *self { - FormElement(form) => form.Target(), - InputElement(input_element) => { + FormSubmitter::FormElement(form) => form.Target(), + FormSubmitter::InputElement(input_element) => { // FIXME(pcwalton): Make this a static atom. input_element.get_form_attribute(&Atom::from_slice("formtarget"), |i| i.FormTarget(), diff --git a/components/script/dom/htmlframeelement.rs b/components/script/dom/htmlframeelement.rs index 23448387033..87b286d6094 100644 --- a/components/script/dom/htmlframeelement.rs +++ b/components/script/dom/htmlframeelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLFrameElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLFrameElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLFrameElement { impl HTMLFrameElementDerived for EventTarget { fn is_htmlframeelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLFrameElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLFrameElement)) } } impl HTMLFrameElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLFrameElement { HTMLFrameElement { - htmlelement: HTMLElement::new_inherited(HTMLFrameElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLFrameElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlframesetelement.rs b/components/script/dom/htmlframesetelement.rs index 9afa3ca02ef..8b92ced546d 100644 --- a/components/script/dom/htmlframesetelement.rs +++ b/components/script/dom/htmlframesetelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLFrameSetElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLFrameSetElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLFrameSetElement { impl HTMLFrameSetElementDerived for EventTarget { fn is_htmlframesetelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLFrameSetElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLFrameSetElement)) } } impl HTMLFrameSetElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLFrameSetElement { HTMLFrameSetElement { - htmlelement: HTMLElement::new_inherited(HTMLFrameSetElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLFrameSetElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlheadelement.rs b/components/script/dom/htmlheadelement.rs index b4bff814681..f37e50c688f 100644 --- a/components/script/dom/htmlheadelement.rs +++ b/components/script/dom/htmlheadelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLHeadElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLHeadElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLHeadElement { impl HTMLHeadElementDerived for EventTarget { fn is_htmlheadelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLHeadElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLHeadElement)) } } impl HTMLHeadElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLHeadElement { HTMLHeadElement { - htmlelement: HTMLElement::new_inherited(HTMLHeadElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLHeadElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlheadingelement.rs b/components/script/dom/htmlheadingelement.rs index c52c7cf7c0f..c8deabe4670 100644 --- a/components/script/dom/htmlheadingelement.rs +++ b/components/script/dom/htmlheadingelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLHeadingElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLHeadingElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[jstraceable] @@ -31,14 +31,14 @@ pub struct HTMLHeadingElement { impl HTMLHeadingElementDerived for EventTarget { fn is_htmlheadingelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLHeadingElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLHeadingElement)) } } impl HTMLHeadingElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>, level: HeadingLevel) -> HTMLHeadingElement { HTMLHeadingElement { - htmlelement: HTMLElement::new_inherited(HTMLHeadingElementTypeId, localName, prefix, document), + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLHeadingElement, localName, prefix, document), level: level, } } diff --git a/components/script/dom/htmlhrelement.rs b/components/script/dom/htmlhrelement.rs index ec71ea141bd..e849716e3b5 100644 --- a/components/script/dom/htmlhrelement.rs +++ b/components/script/dom/htmlhrelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLHRElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLHRElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLHRElement { impl HTMLHRElementDerived for EventTarget { fn is_htmlhrelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLHRElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLHRElement)) } } impl HTMLHRElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLHRElement { HTMLHRElement { - htmlelement: HTMLElement::new_inherited(HTMLHRElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLHRElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlhtmlelement.rs b/components/script/dom/htmlhtmlelement.rs index dddde174b73..cf60c1e9568 100644 --- a/components/script/dom/htmlhtmlelement.rs +++ b/components/script/dom/htmlhtmlelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLHtmlElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLHtmlElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLHtmlElement { impl HTMLHtmlElementDerived for EventTarget { fn is_htmlhtmlelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLHtmlElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLHtmlElement)) } } impl HTMLHtmlElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLHtmlElement { HTMLHtmlElement { - htmlelement: HTMLElement::new_inherited(HTMLHtmlElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLHtmlElement, localName, prefix, document) } } diff --git a/components/script/dom/htmliframeelement.rs b/components/script/dom/htmliframeelement.rs index 59c7011a9c7..8a9bfe572a4 100644 --- a/components/script/dom/htmliframeelement.rs +++ b/components/script/dom/htmliframeelement.rs @@ -12,11 +12,11 @@ use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLIFrameElementDer use dom::bindings::js::{JSRef, Temporary, OptionalRootable}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::{HTMLIFrameElementTypeId, Element}; +use dom::element::{ElementTypeId, Element}; use dom::element::AttributeHandlers; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, NodeHelpers, ElementNodeTypeId, window_from_node}; +use dom::node::{Node, NodeHelpers, NodeTypeId, window_from_node}; use dom::urlhelper::UrlHelper; use dom::virtualmethods::VirtualMethods; use dom::window::Window; @@ -50,7 +50,7 @@ pub struct HTMLIFrameElement { impl HTMLIFrameElementDerived for EventTarget { fn is_htmliframeelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLIFrameElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLIFrameElement)) } } @@ -129,7 +129,7 @@ impl<'a> HTMLIFrameElementHelpers for JSRef<'a, HTMLIFrameElement> { impl HTMLIFrameElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLIFrameElement { HTMLIFrameElement { - htmlelement: HTMLElement::new_inherited(HTMLIFrameElementTypeId, localName, prefix, document), + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLIFrameElement, localName, prefix, document), size: Cell::new(None), sandbox: Cell::new(None), } @@ -214,16 +214,16 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLIFrameElement> { match attr.local_name() { &atom!("sandbox") => { - let mut modes = AllowNothing as u8; + let mut modes = SandboxAllowance::AllowNothing as u8; for word in attr.value().as_slice().split(' ') { modes |= match word.to_ascii_lower().as_slice() { - "allow-same-origin" => AllowSameOrigin, - "allow-forms" => AllowForms, - "allow-pointer-lock" => AllowPointerLock, - "allow-popups" => AllowPopups, - "allow-scripts" => AllowScripts, - "allow-top-navigation" => AllowTopNavigation, - _ => AllowNothing + "allow-same-origin" => SandboxAllowance::AllowSameOrigin, + "allow-forms" => SandboxAllowance::AllowForms, + "allow-pointer-lock" => SandboxAllowance::AllowPointerLock, + "allow-popups" => SandboxAllowance::AllowPopups, + "allow-scripts" => SandboxAllowance::AllowScripts, + "allow-top-navigation" => SandboxAllowance::AllowTopNavigation, + _ => SandboxAllowance::AllowNothing } as u8; } self.sandbox.set(Some(modes)); diff --git a/components/script/dom/htmlimageelement.rs b/components/script/dom/htmlimageelement.rs index dc1ef7d6e26..151a5215319 100644 --- a/components/script/dom/htmlimageelement.rs +++ b/components/script/dom/htmlimageelement.rs @@ -11,11 +11,11 @@ use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast, HTMLElementCas use dom::bindings::js::{JS, JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::{Document, DocumentHelpers}; -use dom::element::{Element, HTMLImageElementTypeId}; +use dom::element::{Element, ElementTypeId}; use dom::element::AttributeHandlers; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId, NodeHelpers, OtherNodeDamage, window_from_node}; +use dom::node::{Node, NodeTypeId, NodeHelpers, NodeDamage, window_from_node}; use dom::virtualmethods::VirtualMethods; use servo_net::image_cache_task; use servo_util::geometry::to_px; @@ -32,7 +32,7 @@ pub struct HTMLImageElement { impl HTMLImageElementDerived for EventTarget { fn is_htmlimageelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLImageElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLImageElement)) } } @@ -69,7 +69,7 @@ impl<'a> PrivateHTMLImageElementHelpers for JSRef<'a, HTMLImageElement> { impl HTMLImageElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLImageElement { HTMLImageElement { - htmlelement: HTMLElement::new_inherited(HTMLImageElementTypeId, localName, prefix, document), + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLImageElement, localName, prefix, document), image: DOMRefCell::new(None), } } @@ -118,7 +118,7 @@ impl<'a> HTMLImageElementMethods for JSRef<'a, HTMLImageElement> { // recreate the flow (picking up image changes on the way). The image cache task needs a // rewrite to modern Rust. let node: JSRef<Node> = NodeCast::from_ref(self); - node.dirty(OtherNodeDamage); + node.dirty(NodeDamage::OtherNodeDamage); let rect = node.get_bounding_content_box(); to_px(rect.size.width) as u32 @@ -136,7 +136,7 @@ impl<'a> HTMLImageElementMethods for JSRef<'a, HTMLImageElement> { // recreate the flow (picking up image changes on the way). The image cache task needs a // rewrite to modern Rust. let node: JSRef<Node> = NodeCast::from_ref(self); - node.dirty(OtherNodeDamage); + node.dirty(NodeDamage::OtherNodeDamage); let rect = node.get_bounding_content_box(); to_px(rect.size.height) as u32 diff --git a/components/script/dom/htmlinputelement.rs b/components/script/dom/htmlinputelement.rs index 3ea2a38a686..b051a4f8f43 100644 --- a/components/script/dom/htmlinputelement.rs +++ b/components/script/dom/htmlinputelement.rs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::activation::Activatable; -use dom::attr::{Attr, AttrValue, UIntAttrValue}; +use dom::attr::{Attr, AttrValue}; use dom::attr::AttrHelpers; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; @@ -19,18 +19,20 @@ use dom::bindings::js::{Comparable, JS, JSRef, Root, Temporary, OptionalRootable use dom::bindings::js::{ResultRootable, RootedReference, MutNullableJS}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::{Document, DocumentHelpers}; -use dom::element::{AttributeHandlers, Element, HTMLInputElementTypeId}; +use dom::element::{AttributeHandlers, Element, ElementTypeId}; use dom::element::{RawLayoutElementHelpers, ActivationElementHelpers}; -use dom::event::{Event, Bubbles, NotCancelable, EventHelpers}; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::keyboardevent::KeyboardEvent; -use dom::htmlformelement::{InputElement, FormControl, HTMLFormElement, HTMLFormElementHelpers}; -use dom::htmlformelement::{NotFromFormSubmitMethod, NotFromFormResetMethod}; -use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId, OtherNodeDamage}; +use dom::htmlformelement::{FormSubmitter, FormControl, HTMLFormElement, HTMLFormElementHelpers}; +use dom::htmlformelement::{SubmittedFrom, ResetFrom}; +use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeDamage, NodeTypeId}; use dom::node::{document_from_node, window_from_node}; use dom::virtualmethods::VirtualMethods; -use textinput::{Single, TextInput, TriggerDefaultAction, DispatchInput, Nothing}; +use textinput::TextInput; +use textinput::KeyReaction::{TriggerDefaultAction, DispatchInput, Nothing}; +use textinput::Lines::Single; use servo_util::str::DOMString; use string_cache::Atom; @@ -91,14 +93,14 @@ impl InputActivationState { checked_changed: false, checked_radio: Default::default(), was_mutable: false, - old_type: InputText + old_type: InputType::InputText } } } impl HTMLInputElementDerived for EventTarget { fn is_htmlinputelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLInputElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLInputElement)) } } @@ -107,8 +109,8 @@ static DEFAULT_INPUT_SIZE: u32 = 20; impl HTMLInputElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLInputElement { HTMLInputElement { - htmlelement: HTMLElement::new_inherited(HTMLInputElementTypeId, localName, prefix, document), - input_type: Cell::new(InputText), + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLInputElement, localName, prefix, document), + input_type: Cell::new(InputType::InputText), checked: Cell::new(false), indeterminate: Cell::new(false), checked_changed: Cell::new(false), @@ -151,12 +153,12 @@ impl LayoutHTMLInputElementHelpers for JS<HTMLInputElement> { } match (*self.unsafe_get()).input_type.get() { - InputCheckbox | InputRadio => "".to_string(), - InputFile | InputImage => "".to_string(), - InputButton => get_raw_attr_value(self).unwrap_or_else(|| "".to_string()), - InputSubmit => get_raw_attr_value(self).unwrap_or_else(|| DEFAULT_SUBMIT_VALUE.to_string()), - InputReset => get_raw_attr_value(self).unwrap_or_else(|| DEFAULT_RESET_VALUE.to_string()), - InputPassword => { + InputType::InputCheckbox | InputType::InputRadio => "".to_string(), + InputType::InputFile | InputType::InputImage => "".to_string(), + InputType::InputButton => get_raw_attr_value(self).unwrap_or_else(|| "".to_string()), + InputType::InputSubmit => get_raw_attr_value(self).unwrap_or_else(|| DEFAULT_SUBMIT_VALUE.to_string()), + InputType::InputReset => get_raw_attr_value(self).unwrap_or_else(|| DEFAULT_RESET_VALUE.to_string()), + InputType::InputPassword => { let raw = get_raw_textinput_value(self); String::from_char(raw.char_len(), '●') } @@ -326,7 +328,7 @@ fn in_same_group<'a,'b>(other: JSRef<'a, HTMLInputElement>, group: Option<&str>) -> bool { let other_owner = other.form_owner().root(); let other_owner = other_owner.root_ref(); - other.input_type.get() == InputRadio && + other.input_type.get() == InputType::InputRadio && // TODO Both a and b are in the same home subtree. other_owner.equals(owner) && // TODO should be a unicode compatibility caseless match @@ -341,7 +343,7 @@ impl<'a> HTMLInputElementHelpers for JSRef<'a, HTMLInputElement> { fn force_relayout(self) { let doc = document_from_node(self).root(); let node: JSRef<Node> = NodeCast::from_ref(self); - doc.content_changed(node, OtherNodeDamage) + doc.content_changed(node, NodeDamage::OtherNodeDamage) } fn radio_group_updated(self, group: Option<&str>) { @@ -365,7 +367,7 @@ impl<'a> HTMLInputElementHelpers for JSRef<'a, HTMLInputElement> { self.checked_changed.set(true); } - if self.input_type.get() == InputRadio && checked { + if self.input_type.get() == InputType::InputRadio && checked { broadcast_radio_checked(self, self.get_radio_group_name() .as_ref() @@ -410,24 +412,24 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLInputElement> { } &atom!("size") => { match *attr.value() { - UIntAttrValue(_, value) => self.size.set(value), - _ => panic!("Expected a UIntAttrValue"), + AttrValue::UInt(_, value) => self.size.set(value), + _ => panic!("Expected an AttrValue::UInt"), } self.force_relayout(); } &atom!("type") => { let value = attr.value(); self.input_type.set(match value.as_slice() { - "button" => InputButton, - "submit" => InputSubmit, - "reset" => InputReset, - "file" => InputFile, - "radio" => InputRadio, - "checkbox" => InputCheckbox, - "password" => InputPassword, - _ => InputText, + "button" => InputType::InputButton, + "submit" => InputType::InputSubmit, + "reset" => InputType::InputReset, + "file" => InputType::InputFile, + "radio" => InputType::InputRadio, + "checkbox" => InputType::InputCheckbox, + "password" => InputType::InputPassword, + _ => InputType::InputText, }); - if self.input_type.get() == InputRadio { + if self.input_type.get() == InputType::InputRadio { self.radio_group_updated(self.get_radio_group_name() .as_ref() .map(|group| group.as_slice())); @@ -441,7 +443,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLInputElement> { } } &atom!("name") => { - if self.input_type.get() == InputRadio { + if self.input_type.get() == InputType::InputRadio { let value = attr.value(); self.radio_group_updated(Some(value.as_slice())); } @@ -474,13 +476,13 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLInputElement> { self.force_relayout(); } &atom!("type") => { - if self.input_type.get() == InputRadio { + if self.input_type.get() == InputType::InputRadio { broadcast_radio_checked(*self, self.get_radio_group_name() .as_ref() .map(|group| group.as_slice())); } - self.input_type.set(InputText); + self.input_type.set(InputType::InputText); self.force_relayout(); } &atom!("value") => { @@ -490,7 +492,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLInputElement> { } } &atom!("name") => { - if self.input_type.get() == InputRadio { + if self.input_type.get() == InputType::InputRadio { self.radio_group_updated(None); } } @@ -539,7 +541,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLInputElement> { if "click" == event.Type().as_slice() && !event.DefaultPrevented() { match self.input_type.get() { - InputRadio => self.update_checked_state(true, true), + InputType::InputRadio => self.update_checked_state(true, true), _ => {} } @@ -551,7 +553,8 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLInputElement> { let doc = document_from_node(*self).root(); doc.request_focus(ElementCast::from_ref(*self)); } else if "keydown" == event.Type().as_slice() && !event.DefaultPrevented() && - (self.input_type.get() == InputText || self.input_type.get() == InputPassword) { + (self.input_type.get() == InputType::InputText || + self.input_type.get() == InputType::InputPassword) { let keyevent: Option<JSRef<KeyboardEvent>> = KeyboardEventCast::to_ref(event); keyevent.map(|keyevent| { match self.textinput.borrow_mut().handle_keydown(keyevent) { @@ -589,11 +592,11 @@ impl<'a> FormControl<'a> for JSRef<'a, HTMLInputElement> { // https://html.spec.whatwg.org/multipage/forms.html#the-input-element:concept-form-reset-control fn reset(self) { match self.input_type.get() { - InputRadio | InputCheckbox => { + InputType::InputRadio | InputType::InputCheckbox => { self.update_checked_state(self.DefaultChecked(), false); self.checked_changed.set(false); }, - InputImage => (), + InputType::InputImage => (), _ => () } @@ -617,10 +620,10 @@ impl<'a> Activatable for JSRef<'a, HTMLInputElement> { if cache.was_mutable { match ty { // https://html.spec.whatwg.org/multipage/forms.html#submit-button-state-(type=submit):activation-behavior - // InputSubmit => (), // No behavior defined + // InputType::InputSubmit => (), // No behavior defined // https://html.spec.whatwg.org/multipage/forms.html#reset-button-state-(type=reset):activation-behavior - // InputSubmit => (), // No behavior defined - InputCheckbox => { + // InputType::InputSubmit => (), // No behavior defined + InputType::InputCheckbox => { // https://html.spec.whatwg.org/multipage/forms.html#checkbox-state-(type=checkbox):pre-click-activation-steps // cache current values of `checked` and `indeterminate` // we may need to restore them later @@ -631,7 +634,7 @@ impl<'a> Activatable for JSRef<'a, HTMLInputElement> { self.SetChecked(!cache.checked); }, // https://html.spec.whatwg.org/multipage/forms.html#radio-button-state-(type=radio):pre-click-activation-steps - InputRadio => { + InputType::InputRadio => { //TODO: if not in document, use root ancestor instead of document let owner = self.form_owner().root(); let doc = document_from_node(*self).root(); @@ -666,11 +669,11 @@ impl<'a> Activatable for JSRef<'a, HTMLInputElement> { } match ty { // https://html.spec.whatwg.org/multipage/forms.html#submit-button-state-(type=submit):activation-behavior - // InputSubmit => (), // No behavior defined + // InputType::InputSubmit => (), // No behavior defined // https://html.spec.whatwg.org/multipage/forms.html#reset-button-state-(type=reset):activation-behavior - // InputReset => (), // No behavior defined + // InputType::InputReset => (), // No behavior defined // https://html.spec.whatwg.org/multipage/forms.html#checkbox-state-(type=checkbox):canceled-activation-steps - InputCheckbox => { + InputType::InputCheckbox => { // We want to restore state only if the element had been changed in the first place if cache.was_mutable { self.SetIndeterminate(cache.indeterminate); @@ -679,7 +682,7 @@ impl<'a> Activatable for JSRef<'a, HTMLInputElement> { } }, // https://html.spec.whatwg.org/multipage/forms.html#radio-button-state-(type=radio):canceled-activation-steps - InputRadio => { + InputType::InputRadio => { // We want to restore state only if the element had been changed in the first place if cache.was_mutable { let old_checked: Option<Root<HTMLInputElement>> = cache.checked_radio.get().root(); @@ -691,7 +694,7 @@ impl<'a> Activatable for JSRef<'a, HTMLInputElement> { if name == o.get_radio_group_name() && // TODO should be compatibility caseless self.form_owner() == o.form_owner() && // TODO Both a and b are in the same home subtree - o.input_type.get() == InputRadio { + o.input_type.get() == InputType::InputRadio { o.SetChecked(true); } else { self.SetChecked(false); @@ -715,39 +718,42 @@ impl<'a> Activatable for JSRef<'a, HTMLInputElement> { return; } match ty { - InputSubmit => { + InputType::InputSubmit => { // https://html.spec.whatwg.org/multipage/forms.html#submit-button-state-(type=submit):activation-behavior // FIXME (Manishearth): support document owners (needs ability to get parent browsing context) if self.mutable() /* and document owner is fully active */ { self.form_owner().map(|o| { - o.root().submit(NotFromFormSubmitMethod, InputElement(self.clone())) + o.root().submit(SubmittedFrom::NotFromFormSubmitMethod, + FormSubmitter::InputElement(self.clone())) }); } }, - InputReset => { + InputType::InputReset => { // https://html.spec.whatwg.org/multipage/forms.html#reset-button-state-(type=reset):activation-behavior // FIXME (Manishearth): support document owners (needs ability to get parent browsing context) if self.mutable() /* and document owner is fully active */ { self.form_owner().map(|o| { - o.root().reset(NotFromFormResetMethod) + o.root().reset(ResetFrom::NotFromFormResetMethod) }); } }, - InputCheckbox | InputRadio => { + InputType::InputCheckbox | InputType::InputRadio => { // https://html.spec.whatwg.org/multipage/forms.html#checkbox-state-(type=checkbox):activation-behavior // https://html.spec.whatwg.org/multipage/forms.html#radio-button-state-(type=radio):activation-behavior if self.mutable() { let win = window_from_node(*self).root(); let event = Event::new(Window(*win), "input".to_string(), - Bubbles, NotCancelable).root(); + EventBubbles::Bubbles, + EventCancelable::NotCancelable).root(); event.set_trusted(true); let target: JSRef<EventTarget> = EventTargetCast::from_ref(*self); target.DispatchEvent(*event).ok(); let event = Event::new(Window(*win), "change".to_string(), - Bubbles, NotCancelable).root(); + EventBubbles::Bubbles, + EventCancelable::NotCancelable).root(); event.set_trusted(true); let target: JSRef<EventTarget> = EventTargetCast::from_ref(*self); target.DispatchEvent(*event).ok(); diff --git a/components/script/dom/htmllabelelement.rs b/components/script/dom/htmllabelelement.rs index f1932dc3ad3..f7b1fa9f08e 100644 --- a/components/script/dom/htmllabelelement.rs +++ b/components/script/dom/htmllabelelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLLabelElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLLabelElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLLabelElement { impl HTMLLabelElementDerived for EventTarget { fn is_htmllabelelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLLabelElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLLabelElement)) } } impl HTMLLabelElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLLabelElement { HTMLLabelElement { - htmlelement: HTMLElement::new_inherited(HTMLLabelElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLLabelElement, localName, prefix, document) } } diff --git a/components/script/dom/htmllegendelement.rs b/components/script/dom/htmllegendelement.rs index 5e98fa5b986..5d888bf440c 100644 --- a/components/script/dom/htmllegendelement.rs +++ b/components/script/dom/htmllegendelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLLegendElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLLegendElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLLegendElement { impl HTMLLegendElementDerived for EventTarget { fn is_htmllegendelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLLegendElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLLegendElement)) } } impl HTMLLegendElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLLegendElement { HTMLLegendElement { - htmlelement: HTMLElement::new_inherited(HTMLLegendElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLLegendElement, localName, prefix, document) } } diff --git a/components/script/dom/htmllielement.rs b/components/script/dom/htmllielement.rs index 16bbd46833f..022684c5317 100644 --- a/components/script/dom/htmllielement.rs +++ b/components/script/dom/htmllielement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLLIElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLLIElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLLIElement { impl HTMLLIElementDerived for EventTarget { fn is_htmllielement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLLIElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLLIElement)) } } impl HTMLLIElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLLIElement { HTMLLIElement { - htmlelement: HTMLElement::new_inherited(HTMLLIElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLLIElement, localName, prefix, document) } } diff --git a/components/script/dom/htmllinkelement.rs b/components/script/dom/htmllinkelement.rs index 2f0a3993815..575c9a459d4 100644 --- a/components/script/dom/htmllinkelement.rs +++ b/components/script/dom/htmllinkelement.rs @@ -12,10 +12,10 @@ use dom::bindings::js::{MutNullableJS, JSRef, Temporary, OptionalRootable}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::domtokenlist::DOMTokenList; -use dom::element::{AttributeHandlers, Element, HTMLLinkElementTypeId}; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::{AttributeHandlers, Element, ElementTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, NodeHelpers, ElementNodeTypeId, window_from_node}; +use dom::node::{Node, NodeHelpers, NodeTypeId, window_from_node}; use dom::virtualmethods::VirtualMethods; use layout_interface::{LayoutChan, LoadStylesheetMsg}; use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS}; @@ -33,14 +33,14 @@ pub struct HTMLLinkElement { impl HTMLLinkElementDerived for EventTarget { fn is_htmllinkelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLLinkElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLLinkElement)) } } impl HTMLLinkElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLLinkElement { HTMLLinkElement { - htmlelement: HTMLElement::new_inherited(HTMLLinkElementTypeId, localName, prefix, document), + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLLinkElement, localName, prefix, document), rel_list: Default::default(), } } diff --git a/components/script/dom/htmlmapelement.rs b/components/script/dom/htmlmapelement.rs index e11c6bdf5c0..8fd64b949e3 100644 --- a/components/script/dom/htmlmapelement.rs +++ b/components/script/dom/htmlmapelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLMapElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLMapElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLMapElement { impl HTMLMapElementDerived for EventTarget { fn is_htmlmapelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLMapElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLMapElement)) } } impl HTMLMapElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLMapElement { HTMLMapElement { - htmlelement: HTMLElement::new_inherited(HTMLMapElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLMapElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlmediaelement.rs b/components/script/dom/htmlmediaelement.rs index 3cc03a64d1c..09473d017b5 100644 --- a/components/script/dom/htmlmediaelement.rs +++ b/components/script/dom/htmlmediaelement.rs @@ -6,10 +6,10 @@ use dom::bindings::js::{JSRef}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::bindings::codegen::InheritTypes::HTMLMediaElementDerived; use dom::document::Document; -use dom::element::{ElementTypeId, HTMLAudioElementTypeId, HTMLVideoElementTypeId}; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::ElementNodeTypeId; +use dom::node::NodeTypeId; use servo_util::str::DOMString; #[dom_struct] @@ -20,8 +20,8 @@ pub struct HTMLMediaElement { impl HTMLMediaElementDerived for EventTarget { fn is_htmlmediaelement(&self) -> bool { match *self.type_id() { - NodeTargetTypeId(ElementNodeTypeId(HTMLVideoElementTypeId)) | - NodeTargetTypeId(ElementNodeTypeId(HTMLAudioElementTypeId)) => true, + EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLVideoElement)) | + EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLAudioElement)) => true, _ => false } } diff --git a/components/script/dom/htmlmetaelement.rs b/components/script/dom/htmlmetaelement.rs index fda51c6d277..a32a738dd1b 100644 --- a/components/script/dom/htmlmetaelement.rs +++ b/components/script/dom/htmlmetaelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLMetaElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLMetaElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLMetaElement { impl HTMLMetaElementDerived for EventTarget { fn is_htmlmetaelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLMetaElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLMetaElement)) } } impl HTMLMetaElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLMetaElement { HTMLMetaElement { - htmlelement: HTMLElement::new_inherited(HTMLMetaElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLMetaElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlmeterelement.rs b/components/script/dom/htmlmeterelement.rs index bb88e499444..622d753ee4a 100644 --- a/components/script/dom/htmlmeterelement.rs +++ b/components/script/dom/htmlmeterelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLMeterElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLMeterElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLMeterElement { impl HTMLMeterElementDerived for EventTarget { fn is_htmlmeterelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLMeterElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLMeterElement)) } } impl HTMLMeterElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLMeterElement { HTMLMeterElement { - htmlelement: HTMLElement::new_inherited(HTMLMeterElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLMeterElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlmodelement.rs b/components/script/dom/htmlmodelement.rs index e1cc1af706e..746b952d551 100644 --- a/components/script/dom/htmlmodelement.rs +++ b/components/script/dom/htmlmodelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLModElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLModElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLModElement { impl HTMLModElementDerived for EventTarget { fn is_htmlmodelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLModElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLModElement)) } } impl HTMLModElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLModElement { HTMLModElement { - htmlelement: HTMLElement::new_inherited(HTMLModElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLModElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlobjectelement.rs b/components/script/dom/htmlobjectelement.rs index 009c67ea42e..411ecfd7b6e 100644 --- a/components/script/dom/htmlobjectelement.rs +++ b/components/script/dom/htmlobjectelement.rs @@ -12,11 +12,11 @@ use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::{Element, HTMLObjectElementTypeId}; +use dom::element::{Element, ElementTypeId}; use dom::element::AttributeHandlers; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId, NodeHelpers, window_from_node}; +use dom::node::{Node, NodeTypeId, NodeHelpers, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; @@ -34,14 +34,14 @@ pub struct HTMLObjectElement { impl HTMLObjectElementDerived for EventTarget { fn is_htmlobjectelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLObjectElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLObjectElement)) } } impl HTMLObjectElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLObjectElement { HTMLObjectElement { - htmlelement: HTMLElement::new_inherited(HTMLObjectElementTypeId, localName, prefix, document), + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLObjectElement, localName, prefix, document), } } diff --git a/components/script/dom/htmlolistelement.rs b/components/script/dom/htmlolistelement.rs index 8b1fdbe01d1..a450800b442 100644 --- a/components/script/dom/htmlolistelement.rs +++ b/components/script/dom/htmlolistelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLOListElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLOListElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLOListElement { impl HTMLOListElementDerived for EventTarget { fn is_htmlolistelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLOListElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLOListElement)) } } impl HTMLOListElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLOListElement { HTMLOListElement { - htmlelement: HTMLElement::new_inherited(HTMLOListElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLOListElement, localName, prefix, document) } } diff --git a/components/script/dom/htmloptgroupelement.rs b/components/script/dom/htmloptgroupelement.rs index e464fccfaf6..ba954cc035f 100644 --- a/components/script/dom/htmloptgroupelement.rs +++ b/components/script/dom/htmloptgroupelement.rs @@ -11,10 +11,10 @@ use dom::bindings::codegen::InheritTypes::{HTMLOptGroupElementDerived, HTMLOptio use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::{AttributeHandlers, HTMLOptGroupElementTypeId}; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::{AttributeHandlers, ElementTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId}; +use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId}; use dom::virtualmethods::VirtualMethods; use servo_util::str::DOMString; @@ -27,14 +27,14 @@ pub struct HTMLOptGroupElement { impl HTMLOptGroupElementDerived for EventTarget { fn is_htmloptgroupelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLOptGroupElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLOptGroupElement)) } } impl HTMLOptGroupElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLOptGroupElement { HTMLOptGroupElement { - htmlelement: HTMLElement::new_inherited(HTMLOptGroupElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLOptGroupElement, localName, prefix, document) } } diff --git a/components/script/dom/htmloptionelement.rs b/components/script/dom/htmloptionelement.rs index c97b32c906e..0610ed8c558 100644 --- a/components/script/dom/htmloptionelement.rs +++ b/components/script/dom/htmloptionelement.rs @@ -15,10 +15,10 @@ use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::characterdata::CharacterData; use dom::document::Document; -use dom::element::{AttributeHandlers, Element, ElementHelpers, HTMLOptionElementTypeId}; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::{AttributeHandlers, Element, ElementHelpers, ElementTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId}; +use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId}; use dom::virtualmethods::VirtualMethods; use servo_util::str::{DOMString, split_html_space_chars}; @@ -31,14 +31,14 @@ pub struct HTMLOptionElement { impl HTMLOptionElementDerived for EventTarget { fn is_htmloptionelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLOptionElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLOptionElement)) } } impl HTMLOptionElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLOptionElement { HTMLOptionElement { - htmlelement: HTMLElement::new_inherited(HTMLOptionElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLOptionElement, localName, prefix, document) } } diff --git a/components/script/dom/htmloutputelement.rs b/components/script/dom/htmloutputelement.rs index 4622fe02f98..73e58f31906 100644 --- a/components/script/dom/htmloutputelement.rs +++ b/components/script/dom/htmloutputelement.rs @@ -8,10 +8,10 @@ use dom::bindings::codegen::InheritTypes::HTMLOutputElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLOutputElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId, window_from_node}; +use dom::node::{Node, NodeTypeId, window_from_node}; use dom::validitystate::ValidityState; use servo_util::str::DOMString; @@ -22,14 +22,14 @@ pub struct HTMLOutputElement { impl HTMLOutputElementDerived for EventTarget { fn is_htmloutputelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLOutputElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLOutputElement)) } } impl HTMLOutputElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLOutputElement { HTMLOutputElement { - htmlelement: HTMLElement::new_inherited(HTMLOutputElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLOutputElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlparagraphelement.rs b/components/script/dom/htmlparagraphelement.rs index a6d7b346b3a..5cd07ac1929 100644 --- a/components/script/dom/htmlparagraphelement.rs +++ b/components/script/dom/htmlparagraphelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLParagraphElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLParagraphElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLParagraphElement { impl HTMLParagraphElementDerived for EventTarget { fn is_htmlparagraphelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLParagraphElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLParagraphElement)) } } impl HTMLParagraphElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLParagraphElement { HTMLParagraphElement { - htmlelement: HTMLElement::new_inherited(HTMLParagraphElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLParagraphElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlparamelement.rs b/components/script/dom/htmlparamelement.rs index a7ceff0b1b3..9aa5ec02499 100644 --- a/components/script/dom/htmlparamelement.rs +++ b/components/script/dom/htmlparamelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLParamElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLParamElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLParamElement { impl HTMLParamElementDerived for EventTarget { fn is_htmlparamelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLParamElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLParamElement)) } } impl HTMLParamElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLParamElement { HTMLParamElement { - htmlelement: HTMLElement::new_inherited(HTMLParamElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLParamElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlpreelement.rs b/components/script/dom/htmlpreelement.rs index 7a25822a569..bc4e840bee3 100644 --- a/components/script/dom/htmlpreelement.rs +++ b/components/script/dom/htmlpreelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLPreElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLPreElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLPreElement { impl HTMLPreElementDerived for EventTarget { fn is_htmlpreelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLPreElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLPreElement)) } } impl HTMLPreElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLPreElement { HTMLPreElement { - htmlelement: HTMLElement::new_inherited(HTMLPreElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLPreElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlprogresselement.rs b/components/script/dom/htmlprogresselement.rs index 18bd90869b6..648a9bf2fbb 100644 --- a/components/script/dom/htmlprogresselement.rs +++ b/components/script/dom/htmlprogresselement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLProgressElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLProgressElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLProgressElement { impl HTMLProgressElementDerived for EventTarget { fn is_htmlprogresselement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLProgressElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLProgressElement)) } } impl HTMLProgressElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLProgressElement { HTMLProgressElement { - htmlelement: HTMLElement::new_inherited(HTMLProgressElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLProgressElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlquoteelement.rs b/components/script/dom/htmlquoteelement.rs index 5dcdd92250a..3160b705b4f 100644 --- a/components/script/dom/htmlquoteelement.rs +++ b/components/script/dom/htmlquoteelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLQuoteElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLQuoteElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLQuoteElement { impl HTMLQuoteElementDerived for EventTarget { fn is_htmlquoteelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLQuoteElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLQuoteElement)) } } impl HTMLQuoteElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLQuoteElement { HTMLQuoteElement { - htmlelement: HTMLElement::new_inherited(HTMLQuoteElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLQuoteElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlscriptelement.rs b/components/script/dom/htmlscriptelement.rs index 48a85f9b022..9432768e816 100644 --- a/components/script/dom/htmlscriptelement.rs +++ b/components/script/dom/htmlscriptelement.rs @@ -15,16 +15,15 @@ use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast, NodeCas use dom::bindings::js::{JSRef, Temporary, OptionalRootable}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::{HTMLScriptElementTypeId, Element, AttributeHandlers}; -use dom::element::{ElementCreator, ParserCreated}; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::{ElementTypeId, Element, AttributeHandlers, ElementCreator}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, NodeHelpers, ElementNodeTypeId, window_from_node, CloneChildrenFlag}; +use dom::node::{Node, NodeHelpers, NodeTypeId, window_from_node, CloneChildrenFlag}; use dom::virtualmethods::VirtualMethods; use dom::window::WindowHelpers; use encoding::all::UTF_8; -use encoding::types::{Encoding, DecodeReplace}; +use encoding::types::{Encoding, DecoderTrap}; use servo_net::resource_task::load_whole_resource; use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS, StaticStringVec}; use std::cell::Cell; @@ -54,7 +53,7 @@ pub struct HTMLScriptElement { impl HTMLScriptElementDerived for EventTarget { fn is_htmlscriptelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLScriptElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLScriptElement)) } } @@ -62,10 +61,10 @@ impl HTMLScriptElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>, creator: ElementCreator) -> HTMLScriptElement { HTMLScriptElement { - htmlelement: HTMLElement::new_inherited(HTMLScriptElementTypeId, localName, prefix, document), + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLScriptElement, localName, prefix, document), already_started: Cell::new(false), - parser_inserted: Cell::new(creator == ParserCreated), - non_blocking: Cell::new(creator != ParserCreated), + parser_inserted: Cell::new(creator == ElementCreator::ParserCreated), + non_blocking: Cell::new(creator != ElementCreator::ParserCreated), ready_to_be_parser_executed: Cell::new(false), } } @@ -187,7 +186,7 @@ impl<'a> HTMLScriptElementHelpers for JSRef<'a, HTMLScriptElement> { match load_whole_resource(&page.resource_task, url) { Ok((metadata, bytes)) => { // TODO: use the charset from step 13. - let source = UTF_8.decode(bytes.as_slice(), DecodeReplace).unwrap(); + let source = UTF_8.decode(bytes.as_slice(), DecoderTrap::Replace).unwrap(); (source, metadata.final_url) } Err(_) => { diff --git a/components/script/dom/htmlselectelement.rs b/components/script/dom/htmlselectelement.rs index cc11d0805a7..a249cb8bc26 100644 --- a/components/script/dom/htmlselectelement.rs +++ b/components/script/dom/htmlselectelement.rs @@ -8,15 +8,15 @@ use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLSelectElementDerived, HTMLFieldSetElementDerived}; -use dom::bindings::codegen::UnionTypes::HTMLElementOrLong::HTMLElementOrLong; -use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement::HTMLOptionElementOrHTMLOptGroupElement; +use dom::bindings::codegen::UnionTypes::HTMLElementOrLong; +use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::{AttributeHandlers, Element, HTMLSelectElementTypeId}; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::{AttributeHandlers, Element, ElementTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId, window_from_node}; +use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; @@ -30,14 +30,14 @@ pub struct HTMLSelectElement { impl HTMLSelectElementDerived for EventTarget { fn is_htmlselectelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLSelectElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLSelectElement)) } } impl HTMLSelectElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLSelectElement { HTMLSelectElement { - htmlelement: HTMLElement::new_inherited(HTMLSelectElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLSelectElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlserializer.rs b/components/script/dom/htmlserializer.rs index 8a04fa717a1..bc6740658b0 100644 --- a/components/script/dom/htmlserializer.rs +++ b/components/script/dom/htmlserializer.rs @@ -11,10 +11,7 @@ use dom::characterdata::CharacterData; use dom::comment::Comment; use dom::documenttype::DocumentType; use dom::element::{Element, ElementHelpers}; -use dom::node::{Node, NodeIterator}; -use dom::node::{DoctypeNodeTypeId, DocumentFragmentNodeTypeId, CommentNodeTypeId}; -use dom::node::{DocumentNodeTypeId, ElementNodeTypeId, ProcessingInstructionNodeTypeId}; -use dom::node::{TextNodeTypeId, NodeHelpers}; +use dom::node::{Node, NodeHelpers, NodeTypeId, NodeIterator}; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; @@ -30,29 +27,29 @@ pub fn serialize(iterator: &mut NodeIterator) -> String { html.push_str(">"); } match node.type_id() { - ElementNodeTypeId(..) => { + NodeTypeId::Element(..) => { let elem: JSRef<Element> = ElementCast::to_ref(node).unwrap(); serialize_elem(elem, &mut open_elements, &mut html) } - CommentNodeTypeId => { + NodeTypeId::Comment => { let comment: JSRef<Comment> = CommentCast::to_ref(node).unwrap(); serialize_comment(comment, &mut html) } - TextNodeTypeId => { + NodeTypeId::Text => { let text: JSRef<Text> = TextCast::to_ref(node).unwrap(); serialize_text(text, &mut html) } - DoctypeNodeTypeId => { + NodeTypeId::DocumentType => { let doctype: JSRef<DocumentType> = DocumentTypeCast::to_ref(node).unwrap(); serialize_doctype(doctype, &mut html) } - ProcessingInstructionNodeTypeId => { + NodeTypeId::ProcessingInstruction => { let processing_instruction: JSRef<ProcessingInstruction> = ProcessingInstructionCast::to_ref(node).unwrap(); serialize_processing_instruction(processing_instruction, &mut html) } - DocumentFragmentNodeTypeId => {} - DocumentNodeTypeId => { + NodeTypeId::DocumentFragment => {} + NodeTypeId::Document => { panic!("It shouldn't be possible to serialize a document node") } } diff --git a/components/script/dom/htmlsourceelement.rs b/components/script/dom/htmlsourceelement.rs index 900b581f358..b53aa3bac45 100644 --- a/components/script/dom/htmlsourceelement.rs +++ b/components/script/dom/htmlsourceelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLSourceElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLSourceElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLSourceElement { impl HTMLSourceElementDerived for EventTarget { fn is_htmlsourceelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLSourceElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLSourceElement)) } } impl HTMLSourceElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLSourceElement { HTMLSourceElement { - htmlelement: HTMLElement::new_inherited(HTMLSourceElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLSourceElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlspanelement.rs b/components/script/dom/htmlspanelement.rs index 2a5ff463513..7ca9b960c55 100644 --- a/components/script/dom/htmlspanelement.rs +++ b/components/script/dom/htmlspanelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLSpanElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLSpanElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLSpanElement { impl HTMLSpanElementDerived for EventTarget { fn is_htmlspanelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLSpanElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLSpanElement)) } } impl HTMLSpanElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLSpanElement { HTMLSpanElement { - htmlelement: HTMLElement::new_inherited(HTMLSpanElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLSpanElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlstyleelement.rs b/components/script/dom/htmlstyleelement.rs index a989699e7e4..c662d39c8e3 100644 --- a/components/script/dom/htmlstyleelement.rs +++ b/components/script/dom/htmlstyleelement.rs @@ -8,14 +8,14 @@ use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLStyleElementDeri use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLStyleElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, NodeHelpers, ElementNodeTypeId, window_from_node}; +use dom::node::{Node, NodeHelpers, NodeTypeId, window_from_node}; use dom::virtualmethods::VirtualMethods; use layout_interface::{AddStylesheetMsg, LayoutChan}; use servo_util::str::DOMString; -use style::{AuthorOrigin, Stylesheet}; +use style::{StylesheetOrigin, Stylesheet}; #[dom_struct] pub struct HTMLStyleElement { @@ -24,14 +24,14 @@ pub struct HTMLStyleElement { impl HTMLStyleElementDerived for EventTarget { fn is_htmlstyleelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLStyleElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLStyleElement)) } } impl HTMLStyleElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLStyleElement { HTMLStyleElement { - htmlelement: HTMLElement::new_inherited(HTMLStyleElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLStyleElement, localName, prefix, document) } } @@ -55,7 +55,8 @@ impl<'a> StyleElementHelpers for JSRef<'a, HTMLStyleElement> { let url = win.page().get_url(); let data = node.GetTextContent().expect("Element.textContent must be a string"); - let sheet = Stylesheet::from_str(data.as_slice(), url, AuthorOrigin); + let sheet = Stylesheet::from_str(data.as_slice(), url, + StylesheetOrigin::Author); let LayoutChan(ref layout_chan) = win.page().layout_chan; layout_chan.send(AddStylesheetMsg(sheet)); } diff --git a/components/script/dom/htmltablecaptionelement.rs b/components/script/dom/htmltablecaptionelement.rs index 90380f37eb9..2a12f2fd01a 100644 --- a/components/script/dom/htmltablecaptionelement.rs +++ b/components/script/dom/htmltablecaptionelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLTableCaptionElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLTableCaptionElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLTableCaptionElement { impl HTMLTableCaptionElementDerived for EventTarget { fn is_htmltablecaptionelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLTableCaptionElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLTableCaptionElement)) } } impl HTMLTableCaptionElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTableCaptionElement { HTMLTableCaptionElement { - htmlelement: HTMLElement::new_inherited(HTMLTableCaptionElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLTableCaptionElement, localName, prefix, document) } } diff --git a/components/script/dom/htmltablecellelement.rs b/components/script/dom/htmltablecellelement.rs index 9ca84b0e70f..346da6560d5 100644 --- a/components/script/dom/htmltablecellelement.rs +++ b/components/script/dom/htmltablecellelement.rs @@ -7,15 +7,14 @@ use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLTableCellElement use dom::bindings::js::JSRef; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::{ElementTypeId, HTMLTableDataCellElementTypeId}; -use dom::element::{HTMLTableHeaderCellElementTypeId}; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::ElementNodeTypeId; +use dom::node::NodeTypeId; use dom::virtualmethods::VirtualMethods; use cssparser::RGBA; -use servo_util::str::{mod, AutoLpa, DOMString, LengthOrPercentageOrAuto}; +use servo_util::str::{mod, DOMString, LengthOrPercentageOrAuto}; use std::cell::Cell; #[dom_struct] @@ -29,8 +28,8 @@ pub struct HTMLTableCellElement { impl HTMLTableCellElementDerived for EventTarget { fn is_htmltablecellelement(&self) -> bool { match *self.type_id() { - NodeTargetTypeId(ElementNodeTypeId(HTMLTableDataCellElementTypeId)) | - NodeTargetTypeId(ElementNodeTypeId(HTMLTableHeaderCellElementTypeId)) => true, + EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLTableDataCellElement)) | + EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLTableHeaderCellElement)) => true, _ => false } } @@ -46,7 +45,7 @@ impl HTMLTableCellElement { htmlelement: HTMLElement::new_inherited(type_id, tag_name, prefix, document), background_color: Cell::new(None), colspan: Cell::new(None), - width: Cell::new(AutoLpa), + width: Cell::new(LengthOrPercentageOrAuto::Auto), } } @@ -109,7 +108,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLTableCellElement> { match attr.local_name() { &atom!("bgcolor") => self.background_color.set(None), &atom!("colspan") => self.colspan.set(None), - &atom!("width") => self.width.set(AutoLpa), + &atom!("width") => self.width.set(LengthOrPercentageOrAuto::Auto), _ => () } } diff --git a/components/script/dom/htmltablecolelement.rs b/components/script/dom/htmltablecolelement.rs index f9761151dc1..99771d70918 100644 --- a/components/script/dom/htmltablecolelement.rs +++ b/components/script/dom/htmltablecolelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLTableColElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLTableColElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLTableColElement { impl HTMLTableColElementDerived for EventTarget { fn is_htmltablecolelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLTableColElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLTableColElement)) } } impl HTMLTableColElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTableColElement { HTMLTableColElement { - htmlelement: HTMLElement::new_inherited(HTMLTableColElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLTableColElement, localName, prefix, document) } } diff --git a/components/script/dom/htmltabledatacellelement.rs b/components/script/dom/htmltabledatacellelement.rs index a2a73bd86f8..db4a7248b10 100644 --- a/components/script/dom/htmltabledatacellelement.rs +++ b/components/script/dom/htmltabledatacellelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLTableDataCellElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLTableDataCellElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmltablecellelement::HTMLTableCellElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLTableDataCellElement { impl HTMLTableDataCellElementDerived for EventTarget { fn is_htmltabledatacellelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLTableDataCellElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLTableDataCellElement)) } } impl HTMLTableDataCellElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTableDataCellElement { HTMLTableDataCellElement { - htmltablecellelement: HTMLTableCellElement::new_inherited(HTMLTableDataCellElementTypeId, localName, prefix, document) + htmltablecellelement: HTMLTableCellElement::new_inherited(ElementTypeId::HTMLTableDataCellElement, localName, prefix, document) } } diff --git a/components/script/dom/htmltableelement.rs b/components/script/dom/htmltableelement.rs index d2c9e723b78..b73f0995b8f 100644 --- a/components/script/dom/htmltableelement.rs +++ b/components/script/dom/htmltableelement.rs @@ -11,15 +11,15 @@ use dom::bindings::codegen::InheritTypes::{HTMLTableElementDerived, NodeCast}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLTableElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::htmltablecaptionelement::HTMLTableCaptionElement; -use dom::node::{Node, NodeHelpers, ElementNodeTypeId}; +use dom::node::{Node, NodeHelpers, NodeTypeId}; use dom::virtualmethods::VirtualMethods; use cssparser::RGBA; -use servo_util::str::{mod, AutoLpa, DOMString, LengthOrPercentageOrAuto}; +use servo_util::str::{mod, DOMString, LengthOrPercentageOrAuto}; use std::cell::Cell; #[dom_struct] @@ -32,7 +32,7 @@ pub struct HTMLTableElement { impl HTMLTableElementDerived for EventTarget { fn is_htmltableelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLTableElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLTableElement)) } } @@ -40,13 +40,13 @@ impl HTMLTableElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTableElement { HTMLTableElement { - htmlelement: HTMLElement::new_inherited(HTMLTableElementTypeId, + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLTableElement, localName, prefix, document), background_color: Cell::new(None), border: Cell::new(None), - width: Cell::new(AutoLpa), + width: Cell::new(LengthOrPercentageOrAuto::Auto), } } @@ -151,7 +151,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLTableElement> { match attr.local_name() { &atom!("bgcolor") => self.background_color.set(None), &atom!("border") => self.border.set(None), - &atom!("width") => self.width.set(AutoLpa), + &atom!("width") => self.width.set(LengthOrPercentageOrAuto::Auto), _ => () } } diff --git a/components/script/dom/htmltableheadercellelement.rs b/components/script/dom/htmltableheadercellelement.rs index 03ae8a83d7e..f20647069d5 100644 --- a/components/script/dom/htmltableheadercellelement.rs +++ b/components/script/dom/htmltableheadercellelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLTableHeaderCellElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLTableHeaderCellElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmltablecellelement::HTMLTableCellElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLTableHeaderCellElement { impl HTMLTableHeaderCellElementDerived for EventTarget { fn is_htmltableheadercellelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLTableHeaderCellElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLTableHeaderCellElement)) } } impl HTMLTableHeaderCellElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTableHeaderCellElement { HTMLTableHeaderCellElement { - htmltablecellelement: HTMLTableCellElement::new_inherited(HTMLTableHeaderCellElementTypeId, localName, prefix, document) + htmltablecellelement: HTMLTableCellElement::new_inherited(ElementTypeId::HTMLTableHeaderCellElement, localName, prefix, document) } } diff --git a/components/script/dom/htmltablerowelement.rs b/components/script/dom/htmltablerowelement.rs index 500c7d74472..6f34f290a5d 100644 --- a/components/script/dom/htmltablerowelement.rs +++ b/components/script/dom/htmltablerowelement.rs @@ -8,10 +8,10 @@ use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLTableRowElementD use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLTableRowElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use dom::virtualmethods::VirtualMethods; use cssparser::RGBA; @@ -26,7 +26,7 @@ pub struct HTMLTableRowElement { impl HTMLTableRowElementDerived for EventTarget { fn is_htmltablerowelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLTableRowElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLTableRowElement)) } } @@ -34,7 +34,7 @@ impl HTMLTableRowElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTableRowElement { HTMLTableRowElement { - htmlelement: HTMLElement::new_inherited(HTMLTableRowElementTypeId, + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLTableRowElement, localName, prefix, document), diff --git a/components/script/dom/htmltablesectionelement.rs b/components/script/dom/htmltablesectionelement.rs index b191e21bde0..d27fabd2153 100644 --- a/components/script/dom/htmltablesectionelement.rs +++ b/components/script/dom/htmltablesectionelement.rs @@ -8,10 +8,10 @@ use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLTableSectionElem use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLTableSectionElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use dom::virtualmethods::VirtualMethods; use cssparser::RGBA; @@ -26,7 +26,7 @@ pub struct HTMLTableSectionElement { impl HTMLTableSectionElementDerived for EventTarget { fn is_htmltablesectionelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLTableSectionElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLTableSectionElement)) } } @@ -34,7 +34,7 @@ impl HTMLTableSectionElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTableSectionElement { HTMLTableSectionElement { - htmlelement: HTMLElement::new_inherited(HTMLTableSectionElementTypeId, + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLTableSectionElement, localName, prefix, document), diff --git a/components/script/dom/htmltemplateelement.rs b/components/script/dom/htmltemplateelement.rs index c0a125109dc..86b2fb3bc4a 100644 --- a/components/script/dom/htmltemplateelement.rs +++ b/components/script/dom/htmltemplateelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLTemplateElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLTemplateElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLTemplateElement { impl HTMLTemplateElementDerived for EventTarget { fn is_htmltemplateelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLTemplateElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLTemplateElement)) } } impl HTMLTemplateElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTemplateElement { HTMLTemplateElement { - htmlelement: HTMLElement::new_inherited(HTMLTemplateElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLTemplateElement, localName, prefix, document) } } diff --git a/components/script/dom/htmltextareaelement.rs b/components/script/dom/htmltextareaelement.rs index 969454afc86..8789fcf9fb1 100644 --- a/components/script/dom/htmltextareaelement.rs +++ b/components/script/dom/htmltextareaelement.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, AttrValue, UIntAttrValue}; +use dom::attr::{Attr, AttrValue}; use dom::attr::AttrHelpers; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventBinding::EventMethods; @@ -15,15 +15,15 @@ use dom::bindings::codegen::InheritTypes::{KeyboardEventCast, TextDerived}; use dom::bindings::js::{JS, JSRef, Temporary, OptionalRootable}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::{Document, DocumentHelpers}; -use dom::element::{AttributeHandlers, HTMLTextAreaElementTypeId, Element}; +use dom::element::{Element, AttributeHandlers, ElementTypeId}; use dom::event::Event; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::htmlformelement::FormControl; use dom::keyboardevent::KeyboardEvent; -use dom::node::{DisabledStateHelpers, Node, NodeHelpers, OtherNodeDamage, ElementNodeTypeId}; +use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeDamage, NodeTypeId}; use dom::node::{document_from_node}; -use textinput::{Multiple, TextInput, TriggerDefaultAction, DispatchInput, Nothing}; +use textinput::{TextInput, Lines, KeyReaction}; use dom::virtualmethods::VirtualMethods; use servo_util::str::DOMString; @@ -44,7 +44,7 @@ pub struct HTMLTextAreaElement { impl HTMLTextAreaElementDerived for EventTarget { fn is_htmltextareaelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLTextAreaElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLTextAreaElement)) } } @@ -82,8 +82,8 @@ static DEFAULT_ROWS: u32 = 2; impl HTMLTextAreaElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTextAreaElement { HTMLTextAreaElement { - htmlelement: HTMLElement::new_inherited(HTMLTextAreaElementTypeId, localName, prefix, document), - textinput: DOMRefCell::new(TextInput::new(Multiple, "".to_string())), + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLTextAreaElement, localName, prefix, document), + textinput: DOMRefCell::new(TextInput::new(Lines::Multiple, "".to_string())), cols: Cell::new(DEFAULT_COLS), rows: Cell::new(DEFAULT_ROWS), value_changed: Cell::new(false), @@ -194,7 +194,7 @@ impl<'a> PrivateHTMLTextAreaElementHelpers for JSRef<'a, HTMLTextAreaElement> { fn force_relayout(self) { let doc = document_from_node(self).root(); let node: JSRef<Node> = NodeCast::from_ref(self); - doc.content_changed(node, OtherNodeDamage) + doc.content_changed(node, NodeDamage::OtherNodeDamage) } } @@ -218,14 +218,14 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLTextAreaElement> { }, &atom!("cols") => { match *attr.value() { - UIntAttrValue(_, value) => self.cols.set(value), - _ => panic!("Expected a UIntAttrValue"), + AttrValue::UInt(_, value) => self.cols.set(value), + _ => panic!("Expected an AttrValue::UInt"), } }, &atom!("rows") => { match *attr.value() { - UIntAttrValue(_, value) => self.rows.set(value), - _ => panic!("Expected a UIntAttrValue"), + AttrValue::UInt(_, value) => self.rows.set(value), + _ => panic!("Expected an AttrValue::UInt"), } }, _ => () @@ -318,12 +318,12 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLTextAreaElement> { let keyevent: Option<JSRef<KeyboardEvent>> = KeyboardEventCast::to_ref(event); keyevent.map(|event| { match self.textinput.borrow_mut().handle_keydown(event) { - TriggerDefaultAction => (), - DispatchInput => { + KeyReaction::TriggerDefaultAction => (), + KeyReaction::DispatchInput => { self.force_relayout(); self.value_changed.set(true); } - Nothing => (), + KeyReaction::Nothing => (), } }); } diff --git a/components/script/dom/htmltimeelement.rs b/components/script/dom/htmltimeelement.rs index 3f21071fd2b..bb31f5021a9 100644 --- a/components/script/dom/htmltimeelement.rs +++ b/components/script/dom/htmltimeelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLTimeElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLTimeElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLTimeElement { impl HTMLTimeElementDerived for EventTarget { fn is_htmltimeelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLTimeElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLTimeElement)) } } impl HTMLTimeElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTimeElement { HTMLTimeElement { - htmlelement: HTMLElement::new_inherited(HTMLTimeElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLTimeElement, localName, prefix, document) } } diff --git a/components/script/dom/htmltitleelement.rs b/components/script/dom/htmltitleelement.rs index 4e6e9f7e9bb..ba54a1790ec 100644 --- a/components/script/dom/htmltitleelement.rs +++ b/components/script/dom/htmltitleelement.rs @@ -10,10 +10,10 @@ use dom::bindings::codegen::InheritTypes::{TextCast}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::{Document, DocumentHelpers}; -use dom::element::HTMLTitleElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, NodeHelpers, ElementNodeTypeId}; +use dom::node::{Node, NodeHelpers, NodeTypeId}; use dom::text::Text; use dom::virtualmethods::VirtualMethods; use servo_util::str::DOMString; @@ -25,14 +25,14 @@ pub struct HTMLTitleElement { impl HTMLTitleElementDerived for EventTarget { fn is_htmltitleelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLTitleElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLTitleElement)) } } impl HTMLTitleElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTitleElement { HTMLTitleElement { - htmlelement: HTMLElement::new_inherited(HTMLTitleElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLTitleElement, localName, prefix, document) } } diff --git a/components/script/dom/htmltrackelement.rs b/components/script/dom/htmltrackelement.rs index ae1a164ad05..6dab96b0ec1 100644 --- a/components/script/dom/htmltrackelement.rs +++ b/components/script/dom/htmltrackelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLTrackElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLTrackElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLTrackElement { impl HTMLTrackElementDerived for EventTarget { fn is_htmltrackelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLTrackElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLTrackElement)) } } impl HTMLTrackElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTrackElement { HTMLTrackElement { - htmlelement: HTMLElement::new_inherited(HTMLTrackElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLTrackElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlulistelement.rs b/components/script/dom/htmlulistelement.rs index 5909dbfc3ae..ecf206d89ce 100644 --- a/components/script/dom/htmlulistelement.rs +++ b/components/script/dom/htmlulistelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLUListElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLUListElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLUListElement { impl HTMLUListElementDerived for EventTarget { fn is_htmlulistelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLUListElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLUListElement)) } } impl HTMLUListElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLUListElement { HTMLUListElement { - htmlelement: HTMLElement::new_inherited(HTMLUListElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLUListElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlunknownelement.rs b/components/script/dom/htmlunknownelement.rs index d8a338afb82..cc538c2c983 100644 --- a/components/script/dom/htmlunknownelement.rs +++ b/components/script/dom/htmlunknownelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLUnknownElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLUnknownElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLUnknownElement { impl HTMLUnknownElementDerived for EventTarget { fn is_htmlunknownelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLUnknownElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLUnknownElement)) } } impl HTMLUnknownElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLUnknownElement { HTMLUnknownElement { - htmlelement: HTMLElement::new_inherited(HTMLUnknownElementTypeId, localName, prefix, document) + htmlelement: HTMLElement::new_inherited(ElementTypeId::HTMLUnknownElement, localName, prefix, document) } } diff --git a/components/script/dom/htmlvideoelement.rs b/components/script/dom/htmlvideoelement.rs index 4bec140ecf1..28e9f0c945c 100644 --- a/components/script/dom/htmlvideoelement.rs +++ b/components/script/dom/htmlvideoelement.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::InheritTypes::HTMLVideoElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::HTMLVideoElementTypeId; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::ElementTypeId; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlmediaelement::HTMLMediaElement; -use dom::node::{Node, ElementNodeTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,14 +20,14 @@ pub struct HTMLVideoElement { impl HTMLVideoElementDerived for EventTarget { fn is_htmlvideoelement(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLVideoElementTypeId)) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLVideoElement)) } } impl HTMLVideoElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLVideoElement { HTMLVideoElement { - htmlmediaelement: HTMLMediaElement::new_inherited(HTMLVideoElementTypeId, localName, prefix, document) + htmlmediaelement: HTMLMediaElement::new_inherited(ElementTypeId::HTMLVideoElement, localName, prefix, document) } } diff --git a/components/script/dom/keyboardevent.rs b/components/script/dom/keyboardevent.rs index 57fc3fb413f..20f7b1e518e 100644 --- a/components/script/dom/keyboardevent.rs +++ b/components/script/dom/keyboardevent.rs @@ -11,7 +11,7 @@ use dom::bindings::global::GlobalRef; use dom::bindings::global; use dom::bindings::js::{JSRef, Temporary, RootedReference}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; -use dom::event::{Event, KeyboardEventTypeId}; +use dom::event::{Event, EventTypeId}; use dom::uievent::UIEvent; use dom::window::Window; use servo_msg::constellation_msg; @@ -37,14 +37,14 @@ pub struct KeyboardEvent { impl KeyboardEventDerived for Event { fn is_keyboardevent(&self) -> bool { - *self.type_id() == KeyboardEventTypeId + *self.type_id() == EventTypeId::KeyboardEvent } } impl KeyboardEvent { fn new_inherited() -> KeyboardEvent { KeyboardEvent { - uievent: UIEvent::new_inherited(KeyboardEventTypeId), + uievent: UIEvent::new_inherited(EventTypeId::KeyboardEvent), key: RefCell::new("".to_string()), code: RefCell::new("".to_string()), location: Cell::new(0), @@ -127,316 +127,316 @@ impl KeyboardEvent { fn key_value(key: constellation_msg::Key, mods: constellation_msg::KeyModifiers) -> &'static str { let shift = mods.contains(constellation_msg::SHIFT); match key { - constellation_msg::KeySpace => " ", - constellation_msg::KeyApostrophe if shift => "\"", - constellation_msg::KeyApostrophe => "'", - constellation_msg::KeyComma if shift => "<", - constellation_msg::KeyComma => ",", - constellation_msg::KeyMinus if shift => "_", - constellation_msg::KeyMinus => "-", - constellation_msg::KeyPeriod if shift => ">", - constellation_msg::KeyPeriod => ".", - constellation_msg::KeySlash if shift => "?", - constellation_msg::KeySlash => "/", - constellation_msg::Key0 if shift => ")", - constellation_msg::Key0 => "0", - constellation_msg::Key1 if shift => "!", - constellation_msg::Key1 => "1", - constellation_msg::Key2 if shift => "@", - constellation_msg::Key2 => "2", - constellation_msg::Key3 if shift => "#", - constellation_msg::Key3 => "3", - constellation_msg::Key4 if shift => "$", - constellation_msg::Key4 => "4", - constellation_msg::Key5 if shift => "%", - constellation_msg::Key5 => "5", - constellation_msg::Key6 if shift => "^", - constellation_msg::Key6 => "6", - constellation_msg::Key7 if shift => "&", - constellation_msg::Key7 => "7", - constellation_msg::Key8 if shift => "*", - constellation_msg::Key8 => "8", - constellation_msg::Key9 if shift => "(", - constellation_msg::Key9 => "9", - constellation_msg::KeySemicolon if shift => ":", - constellation_msg::KeySemicolon => ";", - constellation_msg::KeyEqual if shift => "+", - constellation_msg::KeyEqual => "=", - constellation_msg::KeyA if shift => "A", - constellation_msg::KeyA => "a", - constellation_msg::KeyB if shift => "B", - constellation_msg::KeyB => "b", - constellation_msg::KeyC if shift => "C", - constellation_msg::KeyC => "c", - constellation_msg::KeyD if shift => "D", - constellation_msg::KeyD => "d", - constellation_msg::KeyE if shift => "E", - constellation_msg::KeyE => "e", - constellation_msg::KeyF if shift => "F", - constellation_msg::KeyF => "f", - constellation_msg::KeyG if shift => "G", - constellation_msg::KeyG => "g", - constellation_msg::KeyH if shift => "H", - constellation_msg::KeyH => "h", - constellation_msg::KeyI if shift => "I", - constellation_msg::KeyI => "i", - constellation_msg::KeyJ if shift => "J", - constellation_msg::KeyJ => "j", - constellation_msg::KeyK if shift => "K", - constellation_msg::KeyK => "k", - constellation_msg::KeyL if shift => "L", - constellation_msg::KeyL => "l", - constellation_msg::KeyM if shift => "M", - constellation_msg::KeyM => "m", - constellation_msg::KeyN if shift => "N", - constellation_msg::KeyN => "n", - constellation_msg::KeyO if shift => "O", - constellation_msg::KeyO => "o", - constellation_msg::KeyP if shift => "P", - constellation_msg::KeyP => "p", - constellation_msg::KeyQ if shift => "Q", - constellation_msg::KeyQ => "q", - constellation_msg::KeyR if shift => "R", - constellation_msg::KeyR => "r", - constellation_msg::KeyS if shift => "S", - constellation_msg::KeyS => "s", - constellation_msg::KeyT if shift => "T", - constellation_msg::KeyT => "t", - constellation_msg::KeyU if shift => "U", - constellation_msg::KeyU => "u", - constellation_msg::KeyV if shift => "V", - constellation_msg::KeyV => "v", - constellation_msg::KeyW if shift => "W", - constellation_msg::KeyW => "w", - constellation_msg::KeyX if shift => "X", - constellation_msg::KeyX => "x", - constellation_msg::KeyY if shift => "Y", - constellation_msg::KeyY => "y", - constellation_msg::KeyZ if shift => "Z", - constellation_msg::KeyZ => "z", - constellation_msg::KeyLeftBracket if shift => "{", - constellation_msg::KeyLeftBracket => "[", - constellation_msg::KeyBackslash if shift => "|", - constellation_msg::KeyBackslash => "\\", - constellation_msg::KeyRightBracket if shift => "}", - constellation_msg::KeyRightBracket => "]", - constellation_msg::KeyGraveAccent => "Dead", - constellation_msg::KeyWorld1 => "Unidentified", - constellation_msg::KeyWorld2 => "Unidentified", - constellation_msg::KeyEscape => "Escape", - constellation_msg::KeyEnter => "Enter", - constellation_msg::KeyTab => "Tab", - constellation_msg::KeyBackspace => "Backspace", - constellation_msg::KeyInsert => "Insert", - constellation_msg::KeyDelete => "Delete", - constellation_msg::KeyRight => "ArrowRight", - constellation_msg::KeyLeft => "ArrowLeft", - constellation_msg::KeyDown => "ArrowDown", - constellation_msg::KeyUp => "ArrowUp", - constellation_msg::KeyPageUp => "PageUp", - constellation_msg::KeyPageDown => "PageDown", - constellation_msg::KeyHome => "Home", - constellation_msg::KeyEnd => "End", - constellation_msg::KeyCapsLock => "CapsLock", - constellation_msg::KeyScrollLock => "ScrollLock", - constellation_msg::KeyNumLock => "NumLock", - constellation_msg::KeyPrintScreen => "PrintScreen", - constellation_msg::KeyPause => "Pause", - constellation_msg::KeyF1 => "F1", - constellation_msg::KeyF2 => "F2", - constellation_msg::KeyF3 => "F3", - constellation_msg::KeyF4 => "F4", - constellation_msg::KeyF5 => "F5", - constellation_msg::KeyF6 => "F6", - constellation_msg::KeyF7 => "F7", - constellation_msg::KeyF8 => "F8", - constellation_msg::KeyF9 => "F9", - constellation_msg::KeyF10 => "F10", - constellation_msg::KeyF11 => "F11", - constellation_msg::KeyF12 => "F12", - constellation_msg::KeyF13 => "F13", - constellation_msg::KeyF14 => "F14", - constellation_msg::KeyF15 => "F15", - constellation_msg::KeyF16 => "F16", - constellation_msg::KeyF17 => "F17", - constellation_msg::KeyF18 => "F18", - constellation_msg::KeyF19 => "F19", - constellation_msg::KeyF20 => "F20", - constellation_msg::KeyF21 => "F21", - constellation_msg::KeyF22 => "F22", - constellation_msg::KeyF23 => "F23", - constellation_msg::KeyF24 => "F24", - constellation_msg::KeyF25 => "F25", - constellation_msg::KeyKp0 => "0", - constellation_msg::KeyKp1 => "1", - constellation_msg::KeyKp2 => "2", - constellation_msg::KeyKp3 => "3", - constellation_msg::KeyKp4 => "4", - constellation_msg::KeyKp5 => "5", - constellation_msg::KeyKp6 => "6", - constellation_msg::KeyKp7 => "7", - constellation_msg::KeyKp8 => "8", - constellation_msg::KeyKp9 => "9", - constellation_msg::KeyKpDecimal => ".", - constellation_msg::KeyKpDivide => "/", - constellation_msg::KeyKpMultiply => "*", - constellation_msg::KeyKpSubtract => "-", - constellation_msg::KeyKpAdd => "+", - constellation_msg::KeyKpEnter => "Enter", - constellation_msg::KeyKpEqual => "=", - constellation_msg::KeyLeftShift => "Shift", - constellation_msg::KeyLeftControl => "Control", - constellation_msg::KeyLeftAlt => "Alt", - constellation_msg::KeyLeftSuper => "Super", - constellation_msg::KeyRightShift => "Shift", - constellation_msg::KeyRightControl => "Control", - constellation_msg::KeyRightAlt => "Alt", - constellation_msg::KeyRightSuper => "Super", - constellation_msg::KeyMenu => "ContextMenu", + constellation_msg::Key::Space => " ", + constellation_msg::Key::Apostrophe if shift => "\"", + constellation_msg::Key::Apostrophe => "'", + constellation_msg::Key::Comma if shift => "<", + constellation_msg::Key::Comma => ",", + constellation_msg::Key::Minus if shift => "_", + constellation_msg::Key::Minus => "-", + constellation_msg::Key::Period if shift => ">", + constellation_msg::Key::Period => ".", + constellation_msg::Key::Slash if shift => "?", + constellation_msg::Key::Slash => "/", + constellation_msg::Key::Num0 if shift => ")", + constellation_msg::Key::Num0 => "0", + constellation_msg::Key::Num1 if shift => "!", + constellation_msg::Key::Num1 => "1", + constellation_msg::Key::Num2 if shift => "@", + constellation_msg::Key::Num2 => "2", + constellation_msg::Key::Num3 if shift => "#", + constellation_msg::Key::Num3 => "3", + constellation_msg::Key::Num4 if shift => "$", + constellation_msg::Key::Num4 => "4", + constellation_msg::Key::Num5 if shift => "%", + constellation_msg::Key::Num5 => "5", + constellation_msg::Key::Num6 if shift => "^", + constellation_msg::Key::Num6 => "6", + constellation_msg::Key::Num7 if shift => "&", + constellation_msg::Key::Num7 => "7", + constellation_msg::Key::Num8 if shift => "*", + constellation_msg::Key::Num8 => "8", + constellation_msg::Key::Num9 if shift => "(", + constellation_msg::Key::Num9 => "9", + constellation_msg::Key::Semicolon if shift => ":", + constellation_msg::Key::Semicolon => ";", + constellation_msg::Key::Equal if shift => "+", + constellation_msg::Key::Equal => "=", + constellation_msg::Key::A if shift => "A", + constellation_msg::Key::A => "a", + constellation_msg::Key::B if shift => "B", + constellation_msg::Key::B => "b", + constellation_msg::Key::C if shift => "C", + constellation_msg::Key::C => "c", + constellation_msg::Key::D if shift => "D", + constellation_msg::Key::D => "d", + constellation_msg::Key::E if shift => "E", + constellation_msg::Key::E => "e", + constellation_msg::Key::F if shift => "F", + constellation_msg::Key::F => "f", + constellation_msg::Key::G if shift => "G", + constellation_msg::Key::G => "g", + constellation_msg::Key::H if shift => "H", + constellation_msg::Key::H => "h", + constellation_msg::Key::I if shift => "I", + constellation_msg::Key::I => "i", + constellation_msg::Key::J if shift => "J", + constellation_msg::Key::J => "j", + constellation_msg::Key::K if shift => "K", + constellation_msg::Key::K => "k", + constellation_msg::Key::L if shift => "L", + constellation_msg::Key::L => "l", + constellation_msg::Key::M if shift => "M", + constellation_msg::Key::M => "m", + constellation_msg::Key::N if shift => "N", + constellation_msg::Key::N => "n", + constellation_msg::Key::O if shift => "O", + constellation_msg::Key::O => "o", + constellation_msg::Key::P if shift => "P", + constellation_msg::Key::P => "p", + constellation_msg::Key::Q if shift => "Q", + constellation_msg::Key::Q => "q", + constellation_msg::Key::R if shift => "R", + constellation_msg::Key::R => "r", + constellation_msg::Key::S if shift => "S", + constellation_msg::Key::S => "s", + constellation_msg::Key::T if shift => "T", + constellation_msg::Key::T => "t", + constellation_msg::Key::U if shift => "U", + constellation_msg::Key::U => "u", + constellation_msg::Key::V if shift => "V", + constellation_msg::Key::V => "v", + constellation_msg::Key::W if shift => "W", + constellation_msg::Key::W => "w", + constellation_msg::Key::X if shift => "X", + constellation_msg::Key::X => "x", + constellation_msg::Key::Y if shift => "Y", + constellation_msg::Key::Y => "y", + constellation_msg::Key::Z if shift => "Z", + constellation_msg::Key::Z => "z", + constellation_msg::Key::LeftBracket if shift => "{", + constellation_msg::Key::LeftBracket => "[", + constellation_msg::Key::Backslash if shift => "|", + constellation_msg::Key::Backslash => "\\", + constellation_msg::Key::RightBracket if shift => "}", + constellation_msg::Key::RightBracket => "]", + constellation_msg::Key::GraveAccent => "Dead", + constellation_msg::Key::World1 => "Unidentified", + constellation_msg::Key::World2 => "Unidentified", + constellation_msg::Key::Escape => "Escape", + constellation_msg::Key::Enter => "Enter", + constellation_msg::Key::Tab => "Tab", + constellation_msg::Key::Backspace => "Backspace", + constellation_msg::Key::Insert => "Insert", + constellation_msg::Key::Delete => "Delete", + constellation_msg::Key::Right => "ArrowRight", + constellation_msg::Key::Left => "ArrowLeft", + constellation_msg::Key::Down => "ArrowDown", + constellation_msg::Key::Up => "ArrowUp", + constellation_msg::Key::PageUp => "PageUp", + constellation_msg::Key::PageDown => "PageDown", + constellation_msg::Key::Home => "Home", + constellation_msg::Key::End => "End", + constellation_msg::Key::CapsLock => "CapsLock", + constellation_msg::Key::ScrollLock => "ScrollLock", + constellation_msg::Key::NumLock => "NumLock", + constellation_msg::Key::PrintScreen => "PrintScreen", + constellation_msg::Key::Pause => "Pause", + constellation_msg::Key::F1 => "F1", + constellation_msg::Key::F2 => "F2", + constellation_msg::Key::F3 => "F3", + constellation_msg::Key::F4 => "F4", + constellation_msg::Key::F5 => "F5", + constellation_msg::Key::F6 => "F6", + constellation_msg::Key::F7 => "F7", + constellation_msg::Key::F8 => "F8", + constellation_msg::Key::F9 => "F9", + constellation_msg::Key::F10 => "F10", + constellation_msg::Key::F11 => "F11", + constellation_msg::Key::F12 => "F12", + constellation_msg::Key::F13 => "F13", + constellation_msg::Key::F14 => "F14", + constellation_msg::Key::F15 => "F15", + constellation_msg::Key::F16 => "F16", + constellation_msg::Key::F17 => "F17", + constellation_msg::Key::F18 => "F18", + constellation_msg::Key::F19 => "F19", + constellation_msg::Key::F20 => "F20", + constellation_msg::Key::F21 => "F21", + constellation_msg::Key::F22 => "F22", + constellation_msg::Key::F23 => "F23", + constellation_msg::Key::F24 => "F24", + constellation_msg::Key::F25 => "F25", + constellation_msg::Key::Kp0 => "0", + constellation_msg::Key::Kp1 => "1", + constellation_msg::Key::Kp2 => "2", + constellation_msg::Key::Kp3 => "3", + constellation_msg::Key::Kp4 => "4", + constellation_msg::Key::Kp5 => "5", + constellation_msg::Key::Kp6 => "6", + constellation_msg::Key::Kp7 => "7", + constellation_msg::Key::Kp8 => "8", + constellation_msg::Key::Kp9 => "9", + constellation_msg::Key::KpDecimal => ".", + constellation_msg::Key::KpDivide => "/", + constellation_msg::Key::KpMultiply => "*", + constellation_msg::Key::KpSubtract => "-", + constellation_msg::Key::KpAdd => "+", + constellation_msg::Key::KpEnter => "Enter", + constellation_msg::Key::KpEqual => "=", + constellation_msg::Key::LeftShift => "Shift", + constellation_msg::Key::LeftControl => "Control", + constellation_msg::Key::LeftAlt => "Alt", + constellation_msg::Key::LeftSuper => "Super", + constellation_msg::Key::RightShift => "Shift", + constellation_msg::Key::RightControl => "Control", + constellation_msg::Key::RightAlt => "Alt", + constellation_msg::Key::RightSuper => "Super", + constellation_msg::Key::Menu => "ContextMenu", } } // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3Events-code.html fn code_value(key: constellation_msg::Key) -> &'static str { match key { - constellation_msg::KeySpace => "Space", - constellation_msg::KeyApostrophe => "Quote", - constellation_msg::KeyComma => "Comma", - constellation_msg::KeyMinus => "Minus", - constellation_msg::KeyPeriod => "Period", - constellation_msg::KeySlash => "Slash", - constellation_msg::Key0 => "Digit0", - constellation_msg::Key1 => "Digit1", - constellation_msg::Key2 => "Digit2", - constellation_msg::Key3 => "Digit3", - constellation_msg::Key4 => "Digit4", - constellation_msg::Key5 => "Digit5", - constellation_msg::Key6 => "Digit6", - constellation_msg::Key7 => "Digit7", - constellation_msg::Key8 => "Digit8", - constellation_msg::Key9 => "Digit9", - constellation_msg::KeySemicolon => "Semicolon", - constellation_msg::KeyEqual => "Equals", - constellation_msg::KeyA => "KeyA", - constellation_msg::KeyB => "KeyB", - constellation_msg::KeyC => "KeyC", - constellation_msg::KeyD => "KeyD", - constellation_msg::KeyE => "KeyE", - constellation_msg::KeyF => "KeyF", - constellation_msg::KeyG => "KeyG", - constellation_msg::KeyH => "KeyH", - constellation_msg::KeyI => "KeyI", - constellation_msg::KeyJ => "KeyJ", - constellation_msg::KeyK => "KeyK", - constellation_msg::KeyL => "KeyL", - constellation_msg::KeyM => "KeyM", - constellation_msg::KeyN => "KeyN", - constellation_msg::KeyO => "KeyO", - constellation_msg::KeyP => "KeyP", - constellation_msg::KeyQ => "KeyQ", - constellation_msg::KeyR => "KeyR", - constellation_msg::KeyS => "KeyS", - constellation_msg::KeyT => "KeyT", - constellation_msg::KeyU => "KeyU", - constellation_msg::KeyV => "KeyV", - constellation_msg::KeyW => "KeyW", - constellation_msg::KeyX => "KeyX", - constellation_msg::KeyY => "KeyY", - constellation_msg::KeyZ => "KeyZ", - constellation_msg::KeyLeftBracket => "BracketLeft", - constellation_msg::KeyBackslash => "Backslash", - constellation_msg::KeyRightBracket => "BracketRight", - - constellation_msg::KeyGraveAccent | - constellation_msg::KeyWorld1 | - constellation_msg::KeyWorld2 => panic!("unknown char code for {}", key), - - constellation_msg::KeyEscape => "Escape", - constellation_msg::KeyEnter => "Enter", - constellation_msg::KeyTab => "Tab", - constellation_msg::KeyBackspace => "Backspace", - constellation_msg::KeyInsert => "Insert", - constellation_msg::KeyDelete => "Delete", - constellation_msg::KeyRight => "ArrowRight", - constellation_msg::KeyLeft => "ArrowLeft", - constellation_msg::KeyDown => "ArrowDown", - constellation_msg::KeyUp => "ArrowUp", - constellation_msg::KeyPageUp => "PageUp", - constellation_msg::KeyPageDown => "PageDown", - constellation_msg::KeyHome => "Home", - constellation_msg::KeyEnd => "End", - constellation_msg::KeyCapsLock => "CapsLock", - constellation_msg::KeyScrollLock => "ScrollLock", - constellation_msg::KeyNumLock => "NumLock", - constellation_msg::KeyPrintScreen => "PrintScreen", - constellation_msg::KeyPause => "Pause", - constellation_msg::KeyF1 => "F1", - constellation_msg::KeyF2 => "F2", - constellation_msg::KeyF3 => "F3", - constellation_msg::KeyF4 => "F4", - constellation_msg::KeyF5 => "F5", - constellation_msg::KeyF6 => "F6", - constellation_msg::KeyF7 => "F7", - constellation_msg::KeyF8 => "F8", - constellation_msg::KeyF9 => "F9", - constellation_msg::KeyF10 => "F10", - constellation_msg::KeyF11 => "F11", - constellation_msg::KeyF12 => "F12", - constellation_msg::KeyF13 => "F13", - constellation_msg::KeyF14 => "F14", - constellation_msg::KeyF15 => "F15", - constellation_msg::KeyF16 => "F16", - constellation_msg::KeyF17 => "F17", - constellation_msg::KeyF18 => "F18", - constellation_msg::KeyF19 => "F19", - constellation_msg::KeyF20 => "F20", - constellation_msg::KeyF21 => "F21", - constellation_msg::KeyF22 => "F22", - constellation_msg::KeyF23 => "F23", - constellation_msg::KeyF24 => "F24", - constellation_msg::KeyF25 => "F25", - constellation_msg::KeyKp0 => "Numpad0", - constellation_msg::KeyKp1 => "Numpad1", - constellation_msg::KeyKp2 => "Numpad2", - constellation_msg::KeyKp3 => "Numpad3", - constellation_msg::KeyKp4 => "Numpad4", - constellation_msg::KeyKp5 => "Numpad5", - constellation_msg::KeyKp6 => "Numpad6", - constellation_msg::KeyKp7 => "Numpad7", - constellation_msg::KeyKp8 => "Numpad8", - constellation_msg::KeyKp9 => "Numpad9", - constellation_msg::KeyKpDecimal => "NumpadDecimal", - constellation_msg::KeyKpDivide => "NumpadDivide", - constellation_msg::KeyKpMultiply => "NumpadMultiply", - constellation_msg::KeyKpSubtract => "NumpadSubtract", - constellation_msg::KeyKpAdd => "NumpadAdd", - constellation_msg::KeyKpEnter => "NumpadEnter", - constellation_msg::KeyKpEqual => "NumpadEquals", - constellation_msg::KeyLeftShift | constellation_msg::KeyRightShift => "Shift", - constellation_msg::KeyLeftControl | constellation_msg::KeyRightControl => "Control", - constellation_msg::KeyLeftAlt | constellation_msg::KeyRightAlt => "Alt", - constellation_msg::KeyLeftSuper | constellation_msg::KeyRightSuper => "Super", - constellation_msg::KeyMenu => "Menu", + constellation_msg::Key::Space => "Space", + constellation_msg::Key::Apostrophe => "Quote", + constellation_msg::Key::Comma => "Comma", + constellation_msg::Key::Minus => "Minus", + constellation_msg::Key::Period => "Period", + constellation_msg::Key::Slash => "Slash", + constellation_msg::Key::Num0 => "Digit0", + constellation_msg::Key::Num1 => "Digit1", + constellation_msg::Key::Num2 => "Digit2", + constellation_msg::Key::Num3 => "Digit3", + constellation_msg::Key::Num4 => "Digit4", + constellation_msg::Key::Num5 => "Digit5", + constellation_msg::Key::Num6 => "Digit6", + constellation_msg::Key::Num7 => "Digit7", + constellation_msg::Key::Num8 => "Digit8", + constellation_msg::Key::Num9 => "Digit9", + constellation_msg::Key::Semicolon => "Semicolon", + constellation_msg::Key::Equal => "Equals", + constellation_msg::Key::A => "Key::A", + constellation_msg::Key::B => "Key::B", + constellation_msg::Key::C => "Key::C", + constellation_msg::Key::D => "Key::D", + constellation_msg::Key::E => "Key::E", + constellation_msg::Key::F => "Key::F", + constellation_msg::Key::G => "Key::G", + constellation_msg::Key::H => "Key::H", + constellation_msg::Key::I => "Key::I", + constellation_msg::Key::J => "Key::J", + constellation_msg::Key::K => "Key::K", + constellation_msg::Key::L => "Key::L", + constellation_msg::Key::M => "Key::M", + constellation_msg::Key::N => "Key::N", + constellation_msg::Key::O => "Key::O", + constellation_msg::Key::P => "Key::P", + constellation_msg::Key::Q => "Key::Q", + constellation_msg::Key::R => "Key::R", + constellation_msg::Key::S => "Key::S", + constellation_msg::Key::T => "Key::T", + constellation_msg::Key::U => "Key::U", + constellation_msg::Key::V => "Key::V", + constellation_msg::Key::W => "Key::W", + constellation_msg::Key::X => "Key::X", + constellation_msg::Key::Y => "Key::Y", + constellation_msg::Key::Z => "Key::Z", + constellation_msg::Key::LeftBracket => "BracketLeft", + constellation_msg::Key::Backslash => "Backslash", + constellation_msg::Key::RightBracket => "BracketRight", + + constellation_msg::Key::GraveAccent | + constellation_msg::Key::World1 | + constellation_msg::Key::World2 => panic!("unknown char code for {}", key), + + constellation_msg::Key::Escape => "Escape", + constellation_msg::Key::Enter => "Enter", + constellation_msg::Key::Tab => "Tab", + constellation_msg::Key::Backspace => "Backspace", + constellation_msg::Key::Insert => "Insert", + constellation_msg::Key::Delete => "Delete", + constellation_msg::Key::Right => "ArrowRight", + constellation_msg::Key::Left => "ArrowLeft", + constellation_msg::Key::Down => "ArrowDown", + constellation_msg::Key::Up => "ArrowUp", + constellation_msg::Key::PageUp => "PageUp", + constellation_msg::Key::PageDown => "PageDown", + constellation_msg::Key::Home => "Home", + constellation_msg::Key::End => "End", + constellation_msg::Key::CapsLock => "CapsLock", + constellation_msg::Key::ScrollLock => "ScrollLock", + constellation_msg::Key::NumLock => "NumLock", + constellation_msg::Key::PrintScreen => "PrintScreen", + constellation_msg::Key::Pause => "Pause", + constellation_msg::Key::F1 => "F1", + constellation_msg::Key::F2 => "F2", + constellation_msg::Key::F3 => "F3", + constellation_msg::Key::F4 => "F4", + constellation_msg::Key::F5 => "F5", + constellation_msg::Key::F6 => "F6", + constellation_msg::Key::F7 => "F7", + constellation_msg::Key::F8 => "F8", + constellation_msg::Key::F9 => "F9", + constellation_msg::Key::F10 => "F10", + constellation_msg::Key::F11 => "F11", + constellation_msg::Key::F12 => "F12", + constellation_msg::Key::F13 => "F13", + constellation_msg::Key::F14 => "F14", + constellation_msg::Key::F15 => "F15", + constellation_msg::Key::F16 => "F16", + constellation_msg::Key::F17 => "F17", + constellation_msg::Key::F18 => "F18", + constellation_msg::Key::F19 => "F19", + constellation_msg::Key::F20 => "F20", + constellation_msg::Key::F21 => "F21", + constellation_msg::Key::F22 => "F22", + constellation_msg::Key::F23 => "F23", + constellation_msg::Key::F24 => "F24", + constellation_msg::Key::F25 => "F25", + constellation_msg::Key::Kp0 => "Numpad0", + constellation_msg::Key::Kp1 => "Numpad1", + constellation_msg::Key::Kp2 => "Numpad2", + constellation_msg::Key::Kp3 => "Numpad3", + constellation_msg::Key::Kp4 => "Numpad4", + constellation_msg::Key::Kp5 => "Numpad5", + constellation_msg::Key::Kp6 => "Numpad6", + constellation_msg::Key::Kp7 => "Numpad7", + constellation_msg::Key::Kp8 => "Numpad8", + constellation_msg::Key::Kp9 => "Numpad9", + constellation_msg::Key::KpDecimal => "NumpadDecimal", + constellation_msg::Key::KpDivide => "NumpadDivide", + constellation_msg::Key::KpMultiply => "NumpadMultiply", + constellation_msg::Key::KpSubtract => "NumpadSubtract", + constellation_msg::Key::KpAdd => "NumpadAdd", + constellation_msg::Key::KpEnter => "NumpadEnter", + constellation_msg::Key::KpEqual => "NumpadEquals", + constellation_msg::Key::LeftShift | constellation_msg::Key::RightShift => "Shift", + constellation_msg::Key::LeftControl | constellation_msg::Key::RightControl => "Control", + constellation_msg::Key::LeftAlt | constellation_msg::Key::RightAlt => "Alt", + constellation_msg::Key::LeftSuper | constellation_msg::Key::RightSuper => "Super", + constellation_msg::Key::Menu => "Menu", } } fn key_location(key: constellation_msg::Key) -> u32 { match key { - constellation_msg::KeyKp0 | constellation_msg::KeyKp1 | constellation_msg::KeyKp2 | - constellation_msg::KeyKp3 | constellation_msg::KeyKp4 | constellation_msg::KeyKp5 | - constellation_msg::KeyKp6 | constellation_msg::KeyKp7 | constellation_msg::KeyKp8 | - constellation_msg::KeyKp9 | constellation_msg::KeyKpDecimal | - constellation_msg::KeyKpDivide | constellation_msg::KeyKpMultiply | - constellation_msg::KeyKpSubtract | constellation_msg::KeyKpAdd | - constellation_msg::KeyKpEnter | constellation_msg::KeyKpEqual => + constellation_msg::Key::Kp0 | constellation_msg::Key::Kp1 | constellation_msg::Key::Kp2 | + constellation_msg::Key::Kp3 | constellation_msg::Key::Kp4 | constellation_msg::Key::Kp5 | + constellation_msg::Key::Kp6 | constellation_msg::Key::Kp7 | constellation_msg::Key::Kp8 | + constellation_msg::Key::Kp9 | constellation_msg::Key::KpDecimal | + constellation_msg::Key::KpDivide | constellation_msg::Key::KpMultiply | + constellation_msg::Key::KpSubtract | constellation_msg::Key::KpAdd | + constellation_msg::Key::KpEnter | constellation_msg::Key::KpEqual => KeyboardEventConstants::DOM_KEY_LOCATION_NUMPAD, - constellation_msg::KeyLeftShift | constellation_msg::KeyLeftAlt | - constellation_msg::KeyLeftControl | constellation_msg::KeyLeftSuper => + constellation_msg::Key::LeftShift | constellation_msg::Key::LeftAlt | + constellation_msg::Key::LeftControl | constellation_msg::Key::LeftSuper => KeyboardEventConstants::DOM_KEY_LOCATION_LEFT, - constellation_msg::KeyRightShift | constellation_msg::KeyRightAlt | - constellation_msg::KeyRightControl | constellation_msg::KeyRightSuper => + constellation_msg::Key::RightShift | constellation_msg::Key::RightAlt | + constellation_msg::Key::RightControl | constellation_msg::Key::RightSuper => KeyboardEventConstants::DOM_KEY_LOCATION_RIGHT, _ => KeyboardEventConstants::DOM_KEY_LOCATION_STANDARD, @@ -457,76 +457,76 @@ fn key_charcode(key: constellation_msg::Key, mods: constellation_msg::KeyModifie fn key_keycode(key: constellation_msg::Key) -> u32 { match key { // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#legacy-key-models - constellation_msg::KeyBackspace => 8, - constellation_msg::KeyTab => 9, - constellation_msg::KeyEnter => 13, - constellation_msg::KeyLeftShift | constellation_msg::KeyRightShift => 16, - constellation_msg::KeyLeftControl | constellation_msg::KeyRightControl => 17, - constellation_msg::KeyLeftAlt | constellation_msg::KeyRightAlt => 18, - constellation_msg::KeyCapsLock => 20, - constellation_msg::KeyEscape => 27, - constellation_msg::KeySpace => 32, - constellation_msg::KeyPageUp => 33, - constellation_msg::KeyPageDown => 34, - constellation_msg::KeyEnd => 35, - constellation_msg::KeyHome => 36, - constellation_msg::KeyLeft => 37, - constellation_msg::KeyUp => 38, - constellation_msg::KeyRight => 39, - constellation_msg::KeyDown => 40, - constellation_msg::KeyDelete => 46, + constellation_msg::Key::Backspace => 8, + constellation_msg::Key::Tab => 9, + constellation_msg::Key::Enter => 13, + constellation_msg::Key::LeftShift | constellation_msg::Key::RightShift => 16, + constellation_msg::Key::LeftControl | constellation_msg::Key::RightControl => 17, + constellation_msg::Key::LeftAlt | constellation_msg::Key::RightAlt => 18, + constellation_msg::Key::CapsLock => 20, + constellation_msg::Key::Escape => 27, + constellation_msg::Key::Space => 32, + constellation_msg::Key::PageUp => 33, + constellation_msg::Key::PageDown => 34, + constellation_msg::Key::End => 35, + constellation_msg::Key::Home => 36, + constellation_msg::Key::Left => 37, + constellation_msg::Key::Up => 38, + constellation_msg::Key::Right => 39, + constellation_msg::Key::Down => 40, + constellation_msg::Key::Delete => 46, // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#optionally-fixed-virtual-key-codes - constellation_msg::KeySemicolon => 186, - constellation_msg::KeyEqual => 187, - constellation_msg::KeyComma => 188, - constellation_msg::KeyMinus => 189, - constellation_msg::KeyPeriod => 190, - constellation_msg::KeySlash => 191, - constellation_msg::KeyLeftBracket => 219, - constellation_msg::KeyBackslash => 220, - constellation_msg::KeyRightBracket => 221, - constellation_msg::KeyApostrophe => 222, + constellation_msg::Key::Semicolon => 186, + constellation_msg::Key::Equal => 187, + constellation_msg::Key::Comma => 188, + constellation_msg::Key::Minus => 189, + constellation_msg::Key::Period => 190, + constellation_msg::Key::Slash => 191, + constellation_msg::Key::LeftBracket => 219, + constellation_msg::Key::Backslash => 220, + constellation_msg::Key::RightBracket => 221, + constellation_msg::Key::Apostrophe => 222, //§ B.2.1.3 - constellation_msg::Key0 | - constellation_msg::Key1 | - constellation_msg::Key2 | - constellation_msg::Key3 | - constellation_msg::Key4 | - constellation_msg::Key5 | - constellation_msg::Key6 | - constellation_msg::Key7 | - constellation_msg::Key8 | - constellation_msg::Key9 => key as u32 - constellation_msg::Key0 as u32 + '0' as u32, + constellation_msg::Key::Num0 | + constellation_msg::Key::Num1 | + constellation_msg::Key::Num2 | + constellation_msg::Key::Num3 | + constellation_msg::Key::Num4 | + constellation_msg::Key::Num5 | + constellation_msg::Key::Num6 | + constellation_msg::Key::Num7 | + constellation_msg::Key::Num8 | + constellation_msg::Key::Num9 => key as u32 - constellation_msg::Key::Num0 as u32 + '0' as u32, //§ B.2.1.4 - constellation_msg::KeyA | - constellation_msg::KeyB | - constellation_msg::KeyC | - constellation_msg::KeyD | - constellation_msg::KeyE | - constellation_msg::KeyF | - constellation_msg::KeyG | - constellation_msg::KeyH | - constellation_msg::KeyI | - constellation_msg::KeyJ | - constellation_msg::KeyK | - constellation_msg::KeyL | - constellation_msg::KeyM | - constellation_msg::KeyN | - constellation_msg::KeyO | - constellation_msg::KeyP | - constellation_msg::KeyQ | - constellation_msg::KeyR | - constellation_msg::KeyS | - constellation_msg::KeyT | - constellation_msg::KeyU | - constellation_msg::KeyV | - constellation_msg::KeyW | - constellation_msg::KeyX | - constellation_msg::KeyY | - constellation_msg::KeyZ => key as u32 - constellation_msg::KeyA as u32 + 'A' as u32, + constellation_msg::Key::A | + constellation_msg::Key::B | + constellation_msg::Key::C | + constellation_msg::Key::D | + constellation_msg::Key::E | + constellation_msg::Key::F | + constellation_msg::Key::G | + constellation_msg::Key::H | + constellation_msg::Key::I | + constellation_msg::Key::J | + constellation_msg::Key::K | + constellation_msg::Key::L | + constellation_msg::Key::M | + constellation_msg::Key::N | + constellation_msg::Key::O | + constellation_msg::Key::P | + constellation_msg::Key::Q | + constellation_msg::Key::R | + constellation_msg::Key::S | + constellation_msg::Key::T | + constellation_msg::Key::U | + constellation_msg::Key::V | + constellation_msg::Key::W | + constellation_msg::Key::X | + constellation_msg::Key::Y | + constellation_msg::Key::Z => key as u32 - constellation_msg::Key::A as u32 + 'A' as u32, //§ B.2.1.8 _ => 0 diff --git a/components/script/dom/messageevent.rs b/components/script/dom/messageevent.rs index 9dda3ccc8cc..23ff7083ee8 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::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; -use dom::event::{Event, MessageEventTypeId}; +use dom::event::{Event, EventTypeId}; use dom::eventtarget::{EventTarget, EventTargetHelpers}; use servo_util::str::DOMString; @@ -28,7 +28,7 @@ pub struct MessageEvent { impl MessageEventDerived for Event { fn is_messageevent(&self) -> bool { - *self.type_id() == MessageEventTypeId + *self.type_id() == EventTypeId::MessageEvent } } @@ -36,7 +36,7 @@ impl MessageEvent { fn new_inherited(data: JSVal, origin: DOMString, lastEventId: DOMString) -> MessageEvent { MessageEvent { - event: Event::new_inherited(MessageEventTypeId), + event: Event::new_inherited(EventTypeId::MessageEvent), data: data, origin: origin, lastEventId: lastEventId, diff --git a/components/script/dom/mouseevent.rs b/components/script/dom/mouseevent.rs index 45957fecbf8..46cc0a6e706 100644 --- a/components/script/dom/mouseevent.rs +++ b/components/script/dom/mouseevent.rs @@ -11,7 +11,7 @@ use dom::bindings::global::GlobalRef; use dom::bindings::global; use dom::bindings::js::{MutNullableJS, JSRef, RootedReference, Temporary, OptionalSettable}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; -use dom::event::{Event, MouseEventTypeId}; +use dom::event::{Event, EventTypeId}; use dom::eventtarget::EventTarget; use dom::uievent::UIEvent; use dom::window::Window; @@ -36,14 +36,14 @@ pub struct MouseEvent { impl MouseEventDerived for Event { fn is_mouseevent(&self) -> bool { - *self.type_id() == MouseEventTypeId + *self.type_id() == EventTypeId::MouseEvent } } impl MouseEvent { fn new_inherited() -> MouseEvent { MouseEvent { - uievent: UIEvent::new_inherited(MouseEventTypeId), + uievent: UIEvent::new_inherited(EventTypeId::MouseEvent), screen_x: Cell::new(0), screen_y: Cell::new(0), client_x: Cell::new(0), diff --git a/components/script/dom/node.rs b/components/script/dom/node.rs index 0871a266df3..50647862007 100644 --- a/components/script/dom/node.rs +++ b/components/script/dom/node.rs @@ -19,7 +19,8 @@ use dom::bindings::codegen::InheritTypes::{CharacterDataCast, NodeBase, NodeDeri use dom::bindings::codegen::InheritTypes::{ProcessingInstructionCast, EventTargetCast}; use dom::bindings::codegen::InheritTypes::{HTMLLegendElementDerived, HTMLFieldSetElementDerived}; use dom::bindings::codegen::InheritTypes::HTMLOptGroupElementDerived; -use dom::bindings::error::{Fallible, NotFound, HierarchyRequest, Syntax}; +use dom::bindings::error::Fallible; +use dom::bindings::error::Error::{NotFound, HierarchyRequest, Syntax}; use dom::bindings::global::GlobalRef; use dom::bindings::global; use dom::bindings::js::{JS, JSRef, RootedReference, Temporary, Root}; @@ -30,15 +31,12 @@ use dom::bindings::utils; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::characterdata::CharacterData; use dom::comment::Comment; -use dom::document::{Document, DocumentHelpers, HTMLDocument, NonHTMLDocument, NotFromParser}; +use dom::document::{Document, DocumentHelpers, IsHTMLDocument, DocumentSource}; use dom::documentfragment::DocumentFragment; use dom::documenttype::DocumentType; -use dom::element::{AttributeHandlers, Element, ScriptCreated, ElementTypeId}; -use dom::element::{HTMLAnchorElementTypeId, HTMLButtonElementTypeId, ElementHelpers}; -use dom::element::{HTMLInputElementTypeId, HTMLSelectElementTypeId}; -use dom::element::{HTMLTextAreaElementTypeId, HTMLOptGroupElementTypeId}; -use dom::element::{HTMLOptionElementTypeId, HTMLFieldSetElementTypeId}; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::element::{AttributeHandlers, Element, ElementCreator, ElementTypeId}; +use dom::element::ElementHelpers; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::nodelist::NodeList; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; @@ -50,7 +48,7 @@ use devtools_traits::NodeInfo; use script_traits::UntrustedNodeAddress; use servo_util::geometry::Au; use servo_util::str::{DOMString, null_str_as_empty}; -use style::{matches, AuthorOrigin, ParserContext, SelectorList}; +use style::{matches, StylesheetOrigin, ParserContext, SelectorList}; use js::jsapi::{JSContext, JSObject, JSTracer, JSRuntime}; use js::jsfriendapi; @@ -114,7 +112,7 @@ pub struct Node { impl NodeDerived for EventTarget { fn is_node(&self) -> bool { match *self.type_id() { - NodeTargetTypeId(_) => true, + EventTargetTypeId::Node(_) => true, _ => false } } @@ -155,16 +153,16 @@ impl NodeFlags { pub fn new(type_id: NodeTypeId) -> NodeFlags { let dirty = HAS_CHANGED | IS_DIRTY | HAS_DIRTY_SIBLINGS | HAS_DIRTY_DESCENDANTS; match type_id { - DocumentNodeTypeId => IS_IN_DOC | dirty, + NodeTypeId::Document => IS_IN_DOC | dirty, // The following elements are enabled by default. - ElementNodeTypeId(HTMLButtonElementTypeId) | - ElementNodeTypeId(HTMLInputElementTypeId) | - ElementNodeTypeId(HTMLSelectElementTypeId) | - ElementNodeTypeId(HTMLTextAreaElementTypeId) | - ElementNodeTypeId(HTMLOptGroupElementTypeId) | - ElementNodeTypeId(HTMLOptionElementTypeId) | - //ElementNodeTypeId(HTMLMenuItemElementTypeId) | - ElementNodeTypeId(HTMLFieldSetElementTypeId) => IN_ENABLED_STATE | dirty, + NodeTypeId::Element(ElementTypeId::HTMLButtonElement) | + NodeTypeId::Element(ElementTypeId::HTMLInputElement) | + NodeTypeId::Element(ElementTypeId::HTMLSelectElement) | + NodeTypeId::Element(ElementTypeId::HTMLTextAreaElement) | + NodeTypeId::Element(ElementTypeId::HTMLOptGroupElement) | + NodeTypeId::Element(ElementTypeId::HTMLOptionElement) | + //NodeTypeId::Element(ElementTypeId::HTMLMenuItemElement) | + NodeTypeId::Element(ElementTypeId::HTMLFieldSetElement) => IN_ENABLED_STATE | dirty, _ => dirty, } } @@ -257,13 +255,13 @@ impl LayoutDataRef { #[deriving(PartialEq, Show)] #[jstraceable] pub enum NodeTypeId { - DoctypeNodeTypeId, - DocumentFragmentNodeTypeId, - CommentNodeTypeId, - DocumentNodeTypeId, - ElementNodeTypeId(ElementTypeId), - TextNodeTypeId, - ProcessingInstructionNodeTypeId, + DocumentType, + DocumentFragment, + Comment, + Document, + Element(ElementTypeId), + Text, + ProcessingInstruction, } trait PrivateNodeHelpers { @@ -286,7 +284,7 @@ impl<'a> PrivateNodeHelpers for JSRef<'a, Node> { let parent = self.parent_node().root(); parent.map(|parent| vtable_for(&*parent).child_inserted(self)); - document.content_and_heritage_changed(self, OtherNodeDamage); + document.content_and_heritage_changed(self, NodeDamage::OtherNodeDamage); } // http://dom.spec.whatwg.org/#node-is-removed @@ -546,29 +544,29 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> { #[inline] fn is_element(self) -> bool { match self.type_id { - ElementNodeTypeId(..) => true, + NodeTypeId::Element(..) => true, _ => false } } #[inline] fn is_document(self) -> bool { - self.type_id == DocumentNodeTypeId + self.type_id == NodeTypeId::Document } #[inline] fn is_anchor_element(self) -> bool { - self.type_id == ElementNodeTypeId(HTMLAnchorElementTypeId) + self.type_id == NodeTypeId::Element(ElementTypeId::HTMLAnchorElement) } #[inline] fn is_doctype(self) -> bool { - self.type_id == DoctypeNodeTypeId + self.type_id == NodeTypeId::DocumentType } #[inline] fn is_text(self) -> bool { - self.type_id == TextNodeTypeId + self.type_id == NodeTypeId::Text } fn get_flag(self, flag: NodeFlags) -> bool { @@ -654,8 +652,8 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> { fn dirty_impl(self, damage: NodeDamage, force_ancestors: bool) { // 1. Dirty self. match damage { - NodeStyleDamaged => {} - OtherNodeDamage => self.set_has_changed(true), + NodeDamage::NodeStyleDamaged => {} + NodeDamage::OtherNodeDamage => self.set_has_changed(true), } if self.get_is_dirty() && !force_ancestors { @@ -741,7 +739,7 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> { fn query_selector(self, selectors: DOMString) -> Fallible<Option<Temporary<Element>>> { // Step 1. let parser_context = ParserContext { - origin: AuthorOrigin, + origin: StylesheetOrigin::Author, }; match style::parse_selector_list_from_str(&parser_context, selectors.as_slice()) { // Step 2. @@ -766,7 +764,7 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> { let nodes; let root = self.ancestors().last().unwrap_or(self.clone()); let parser_context = ParserContext { - origin: AuthorOrigin, + origin: StylesheetOrigin::Author, }; match style::parse_selector_list_from_str(&parser_context, selectors.as_slice()) { // Step 2. @@ -1176,7 +1174,7 @@ impl Node { fn new_(type_id: NodeTypeId, doc: Option<JSRef<Document>>) -> Node { Node { - eventtarget: EventTarget::new_inherited(NodeTargetTypeId(type_id)), + eventtarget: EventTarget::new_inherited(EventTargetTypeId::Node(type_id)), type_id: type_id, parent_node: Default::default(), @@ -1214,7 +1212,7 @@ impl Node { // Step 1. match node.parent_node().root() { Some(parent) => { - Node::remove(node, *parent, Unsuppressed); + Node::remove(node, *parent, SuppressObserver::Unsuppressed); } None => (), } @@ -1236,9 +1234,9 @@ impl Node { -> Fallible<Temporary<Node>> { // Step 1. match parent.type_id() { - DocumentNodeTypeId | - DocumentFragmentNodeTypeId | - ElementNodeTypeId(..) => (), + NodeTypeId::Document | + NodeTypeId::DocumentFragment | + NodeTypeId::Element(..) => (), _ => return Err(HierarchyRequest) } @@ -1255,29 +1253,29 @@ impl Node { // Step 4-5. match node.type_id() { - TextNodeTypeId => { + NodeTypeId::Text => { if parent.is_document() { return Err(HierarchyRequest); } }, - DoctypeNodeTypeId => { + NodeTypeId::DocumentType => { if !parent.is_document() { return Err(HierarchyRequest); } }, - DocumentFragmentNodeTypeId | - ElementNodeTypeId(_) | - ProcessingInstructionNodeTypeId | - CommentNodeTypeId => (), - DocumentNodeTypeId => return Err(HierarchyRequest) + NodeTypeId::DocumentFragment | + NodeTypeId::Element(_) | + NodeTypeId::ProcessingInstruction | + NodeTypeId::Comment => (), + NodeTypeId::Document => return Err(HierarchyRequest) } // Step 6. match parent.type_id() { - DocumentNodeTypeId => { + NodeTypeId::Document => { match node.type_id() { // Step 6.1 - DocumentFragmentNodeTypeId => { + NodeTypeId::DocumentFragment => { // Step 6.1.1(b) if node.children().any(|c| c.is_text()) { return Err(HierarchyRequest); @@ -1304,7 +1302,7 @@ impl Node { } }, // Step 6.2 - ElementNodeTypeId(_) => { + NodeTypeId::Element(_) => { if !parent.child_elements().is_empty() { return Err(HierarchyRequest); } @@ -1319,7 +1317,7 @@ impl Node { } }, // Step 6.3 - DoctypeNodeTypeId => { + NodeTypeId::DocumentType => { if parent.children().any(|c| c.is_doctype()) { return Err(HierarchyRequest); } @@ -1338,10 +1336,10 @@ impl Node { }, } }, - TextNodeTypeId | - ProcessingInstructionNodeTypeId | - CommentNodeTypeId => (), - DocumentNodeTypeId => unreachable!(), + NodeTypeId::Text | + NodeTypeId::ProcessingInstruction | + NodeTypeId::Comment => (), + NodeTypeId::Document => unreachable!(), } }, _ => (), @@ -1358,7 +1356,7 @@ impl Node { Node::adopt(node, *document); // Step 10. - Node::insert(node, parent, referenceChild, Unsuppressed); + Node::insert(node, parent, referenceChild, SuppressObserver::Unsuppressed); // Step 11. return Ok(Temporary::from_rooted(node)) @@ -1385,8 +1383,8 @@ impl Node { fn fire_observer_if_necessary(node: JSRef<Node>, suppress_observers: SuppressObserver) { match suppress_observers { - Unsuppressed => node.node_inserted(), - Suppressed => () + SuppressObserver::Unsuppressed => node.node_inserted(), + SuppressObserver::Suppressed => () } } @@ -1394,14 +1392,14 @@ impl Node { // Step 1-3: ranges. match node.type_id() { - DocumentFragmentNodeTypeId => { + NodeTypeId::DocumentFragment => { // Step 4. // Step 5: DocumentFragment, mutation records. // Step 6: DocumentFragment. let mut kids = Vec::new(); for kid in node.children() { kids.push(kid.clone()); - Node::remove(kid, node, Suppressed); + Node::remove(kid, node, SuppressObserver::Suppressed); } // Step 7: mutation records. @@ -1445,19 +1443,19 @@ impl Node { let addedNodes = match node { None => vec!(), Some(node) => match node.type_id() { - DocumentFragmentNodeTypeId => node.children().collect(), + NodeTypeId::DocumentFragment => node.children().collect(), _ => vec!(node.clone()), }, }; // Step 4. for child in parent.children() { - Node::remove(child, parent, Suppressed); + Node::remove(child, parent, SuppressObserver::Suppressed); } // Step 5. match node { - Some(node) => Node::insert(node, parent, None, Suppressed), + Some(node) => Node::insert(node, parent, None, SuppressObserver::Suppressed), None => (), } @@ -1482,7 +1480,7 @@ impl Node { } // Step 2. - Node::remove(child, parent, Unsuppressed); + Node::remove(child, parent, SuppressObserver::Unsuppressed); // Step 3. Ok(Temporary::from_rooted(child)) @@ -1501,8 +1499,8 @@ impl Node { // Step 9. match suppress_observers { - Suppressed => (), - Unsuppressed => node.node_removed(parent.is_in_doc()), + SuppressObserver::Suppressed => (), + SuppressObserver::Unsuppressed => node.node_removed(parent.is_in_doc()), } } @@ -1519,49 +1517,51 @@ impl Node { // Step 2. // XXXabinader: clone() for each node as trait? let copy: Root<Node> = match node.type_id() { - DoctypeNodeTypeId => { + NodeTypeId::DocumentType => { let doctype: JSRef<DocumentType> = DocumentTypeCast::to_ref(node).unwrap(); let doctype = DocumentType::new(doctype.name().clone(), Some(doctype.public_id().clone()), Some(doctype.system_id().clone()), *document); NodeCast::from_temporary(doctype) }, - DocumentFragmentNodeTypeId => { + NodeTypeId::DocumentFragment => { let doc_fragment = DocumentFragment::new(*document); NodeCast::from_temporary(doc_fragment) }, - CommentNodeTypeId => { + NodeTypeId::Comment => { let comment: JSRef<Comment> = CommentCast::to_ref(node).unwrap(); let comment = Comment::new(comment.characterdata().data().clone(), *document); NodeCast::from_temporary(comment) }, - DocumentNodeTypeId => { + NodeTypeId::Document => { let document: JSRef<Document> = DocumentCast::to_ref(node).unwrap(); let is_html_doc = match document.is_html_document() { - true => HTMLDocument, - false => NonHTMLDocument + true => IsHTMLDocument::HTMLDocument, + false => IsHTMLDocument::NonHTMLDocument, }; let window = document.window().root(); let document = Document::new(*window, Some(document.url().clone()), - is_html_doc, None, NotFromParser); + is_html_doc, None, + DocumentSource::NotFromParser); NodeCast::from_temporary(document) }, - ElementNodeTypeId(..) => { + NodeTypeId::Element(..) => { let element: JSRef<Element> = ElementCast::to_ref(node).unwrap(); let name = QualName { ns: element.namespace().clone(), local: element.local_name().clone() }; let element = Element::create(name, - element.prefix().as_ref().map(|p| p.as_slice().to_string()), *document, ScriptCreated); + element.prefix().as_ref().map(|p| p.as_slice().to_string()), + *document, ElementCreator::ScriptCreated); NodeCast::from_temporary(element) }, - TextNodeTypeId => { + NodeTypeId::Text => { let text: JSRef<Text> = TextCast::to_ref(node).unwrap(); let text = Text::new(text.characterdata().data().clone(), *document); NodeCast::from_temporary(text) }, - ProcessingInstructionNodeTypeId => { + NodeTypeId::ProcessingInstruction => { let pi: JSRef<ProcessingInstruction> = ProcessingInstructionCast::to_ref(node).unwrap(); let pi = ProcessingInstruction::new(pi.target().clone(), pi.characterdata().data().clone(), *document); @@ -1578,13 +1578,13 @@ impl Node { // Step 4 (some data already copied in step 2). match node.type_id() { - DocumentNodeTypeId => { + NodeTypeId::Document => { let node_doc: JSRef<Document> = DocumentCast::to_ref(node).unwrap(); let copy_doc: JSRef<Document> = DocumentCast::to_ref(*copy).unwrap(); copy_doc.set_encoding_name(node_doc.encoding_name().clone()); copy_doc.set_quirks_mode(node_doc.quirks_mode()); }, - ElementNodeTypeId(..) => { + NodeTypeId::Element(..) => { let node_elem: JSRef<Element> = ElementCast::to_ref(node).unwrap(); let copy_elem: JSRef<Element> = ElementCast::to_ref(*copy).unwrap(); @@ -1605,7 +1605,7 @@ impl Node { vtable_for(&node).cloning_steps(*copy, maybe_doc, clone_children); // Step 6. - if clone_children == CloneChildren { + if clone_children == CloneChildrenFlag::CloneChildren { for child in node.children() { let child_copy = Node::clone(child, Some(document), clone_children).root(); let _inserted_node = Node::pre_insert(*child_copy, *copy, None); @@ -1648,36 +1648,36 @@ impl<'a> NodeMethods for JSRef<'a, Node> { // http://dom.spec.whatwg.org/#dom-node-nodetype fn NodeType(self) -> u16 { match self.type_id { - ElementNodeTypeId(_) => NodeConstants::ELEMENT_NODE, - TextNodeTypeId => NodeConstants::TEXT_NODE, - ProcessingInstructionNodeTypeId => NodeConstants::PROCESSING_INSTRUCTION_NODE, - CommentNodeTypeId => NodeConstants::COMMENT_NODE, - DocumentNodeTypeId => NodeConstants::DOCUMENT_NODE, - DoctypeNodeTypeId => NodeConstants::DOCUMENT_TYPE_NODE, - DocumentFragmentNodeTypeId => NodeConstants::DOCUMENT_FRAGMENT_NODE, + NodeTypeId::Element(_) => NodeConstants::ELEMENT_NODE, + NodeTypeId::Text => NodeConstants::TEXT_NODE, + NodeTypeId::ProcessingInstruction => NodeConstants::PROCESSING_INSTRUCTION_NODE, + NodeTypeId::Comment => NodeConstants::COMMENT_NODE, + NodeTypeId::Document => NodeConstants::DOCUMENT_NODE, + NodeTypeId::DocumentType => NodeConstants::DOCUMENT_TYPE_NODE, + NodeTypeId::DocumentFragment => NodeConstants::DOCUMENT_FRAGMENT_NODE, } } // http://dom.spec.whatwg.org/#dom-node-nodename fn NodeName(self) -> DOMString { match self.type_id { - ElementNodeTypeId(..) => { + NodeTypeId::Element(..) => { let elem: JSRef<Element> = ElementCast::to_ref(self).unwrap(); elem.TagName() } - TextNodeTypeId => "#text".to_string(), - ProcessingInstructionNodeTypeId => { + NodeTypeId::Text => "#text".to_string(), + NodeTypeId::ProcessingInstruction => { let processing_instruction: JSRef<ProcessingInstruction> = ProcessingInstructionCast::to_ref(self).unwrap(); processing_instruction.Target() } - CommentNodeTypeId => "#comment".to_string(), - DoctypeNodeTypeId => { + NodeTypeId::Comment => "#comment".to_string(), + NodeTypeId::DocumentType => { let doctype: JSRef<DocumentType> = DocumentTypeCast::to_ref(self).unwrap(); doctype.name().clone() }, - DocumentFragmentNodeTypeId => "#document-fragment".to_string(), - DocumentNodeTypeId => "#document".to_string() + NodeTypeId::DocumentFragment => "#document-fragment".to_string(), + NodeTypeId::Document => "#document".to_string() } } @@ -1690,13 +1690,13 @@ impl<'a> NodeMethods for JSRef<'a, Node> { // http://dom.spec.whatwg.org/#dom-node-ownerdocument fn GetOwnerDocument(self) -> Option<Temporary<Document>> { match self.type_id { - ElementNodeTypeId(..) | - CommentNodeTypeId | - TextNodeTypeId | - ProcessingInstructionNodeTypeId | - DoctypeNodeTypeId | - DocumentFragmentNodeTypeId => Some(self.owner_doc()), - DocumentNodeTypeId => None + NodeTypeId::Element(..) | + NodeTypeId::Comment | + NodeTypeId::Text | + NodeTypeId::ProcessingInstruction | + NodeTypeId::DocumentType | + NodeTypeId::DocumentFragment => Some(self.owner_doc()), + NodeTypeId::Document => None } } @@ -1753,9 +1753,9 @@ impl<'a> NodeMethods for JSRef<'a, Node> { // http://dom.spec.whatwg.org/#dom-node-nodevalue fn GetNodeValue(self) -> Option<DOMString> { match self.type_id { - CommentNodeTypeId | - TextNodeTypeId | - ProcessingInstructionNodeTypeId => { + NodeTypeId::Comment | + NodeTypeId::Text | + NodeTypeId::ProcessingInstruction => { let chardata: JSRef<CharacterData> = CharacterDataCast::to_ref(self).unwrap(); Some(chardata.Data()) } @@ -1768,9 +1768,9 @@ impl<'a> NodeMethods for JSRef<'a, Node> { // http://dom.spec.whatwg.org/#dom-node-nodevalue fn SetNodeValue(self, val: Option<DOMString>) { match self.type_id { - CommentNodeTypeId | - TextNodeTypeId | - ProcessingInstructionNodeTypeId => { + NodeTypeId::Comment | + NodeTypeId::Text | + NodeTypeId::ProcessingInstruction => { self.SetTextContent(val) } _ => {} @@ -1780,19 +1780,19 @@ impl<'a> NodeMethods for JSRef<'a, Node> { // http://dom.spec.whatwg.org/#dom-node-textcontent fn GetTextContent(self) -> Option<DOMString> { match self.type_id { - DocumentFragmentNodeTypeId | - ElementNodeTypeId(..) => { + NodeTypeId::DocumentFragment | + NodeTypeId::Element(..) => { let content = Node::collect_text_contents(self.traverse_preorder()); Some(content) } - CommentNodeTypeId | - TextNodeTypeId | - ProcessingInstructionNodeTypeId => { + NodeTypeId::Comment | + NodeTypeId::Text | + NodeTypeId::ProcessingInstruction => { let characterdata: JSRef<CharacterData> = CharacterDataCast::to_ref(self).unwrap(); Some(characterdata.Data()) } - DoctypeNodeTypeId | - DocumentNodeTypeId => { + NodeTypeId::DocumentType | + NodeTypeId::Document => { None } } @@ -1802,8 +1802,8 @@ impl<'a> NodeMethods for JSRef<'a, Node> { fn SetTextContent(self, value: Option<DOMString>) { let value = null_str_as_empty(&value); match self.type_id { - DocumentFragmentNodeTypeId | - ElementNodeTypeId(..) => { + NodeTypeId::DocumentFragment | + NodeTypeId::Element(..) => { // Step 1-2. let node = if value.len() == 0 { None @@ -1815,18 +1815,18 @@ impl<'a> NodeMethods for JSRef<'a, Node> { // Step 3. Node::replace_all(node.root_ref(), self); } - CommentNodeTypeId | - TextNodeTypeId | - ProcessingInstructionNodeTypeId => { + NodeTypeId::Comment | + NodeTypeId::Text | + NodeTypeId::ProcessingInstruction => { let characterdata: JSRef<CharacterData> = CharacterDataCast::to_ref(self).unwrap(); characterdata.set_data(value); // Notify the document that the content of this node is different let document = self.owner_doc().root(); - document.content_changed(self, OtherNodeDamage); + document.content_changed(self, NodeDamage::OtherNodeDamage); } - DoctypeNodeTypeId | - DocumentNodeTypeId => {} + NodeTypeId::DocumentType | + NodeTypeId::Document => {} } } @@ -1845,9 +1845,9 @@ impl<'a> NodeMethods for JSRef<'a, Node> { // Step 1. match self.type_id { - DocumentNodeTypeId | - DocumentFragmentNodeTypeId | - ElementNodeTypeId(..) => (), + NodeTypeId::Document | + NodeTypeId::DocumentFragment | + NodeTypeId::Element(..) => (), _ => return Err(HierarchyRequest) } @@ -1863,23 +1863,23 @@ impl<'a> NodeMethods for JSRef<'a, Node> { // Step 4-5. match node.type_id() { - TextNodeTypeId if self.is_document() => return Err(HierarchyRequest), - DoctypeNodeTypeId if !self.is_document() => return Err(HierarchyRequest), - DocumentFragmentNodeTypeId | - DoctypeNodeTypeId | - ElementNodeTypeId(..) | - TextNodeTypeId | - ProcessingInstructionNodeTypeId | - CommentNodeTypeId => (), - DocumentNodeTypeId => return Err(HierarchyRequest) + NodeTypeId::Text if self.is_document() => return Err(HierarchyRequest), + NodeTypeId::DocumentType if !self.is_document() => return Err(HierarchyRequest), + NodeTypeId::DocumentFragment | + NodeTypeId::DocumentType | + NodeTypeId::Element(..) | + NodeTypeId::Text | + NodeTypeId::ProcessingInstruction | + NodeTypeId::Comment => (), + NodeTypeId::Document => return Err(HierarchyRequest) } // Step 6. match self.type_id { - DocumentNodeTypeId => { + NodeTypeId::Document => { match node.type_id() { // Step 6.1 - DocumentFragmentNodeTypeId => { + NodeTypeId::DocumentFragment => { // Step 6.1.1(b) if node.children().any(|c| c.is_text()) { return Err(HierarchyRequest); @@ -1901,7 +1901,7 @@ impl<'a> NodeMethods for JSRef<'a, Node> { } }, // Step 6.2 - ElementNodeTypeId(..) => { + NodeTypeId::Element(..) => { if self.child_elements().any(|c| NodeCast::from_ref(c) != child) { return Err(HierarchyRequest); } @@ -1911,7 +1911,7 @@ impl<'a> NodeMethods for JSRef<'a, Node> { } }, // Step 6.3 - DoctypeNodeTypeId => { + NodeTypeId::DocumentType => { if self.children().any(|c| c.is_doctype() && c != child) { return Err(HierarchyRequest); } @@ -1921,10 +1921,10 @@ impl<'a> NodeMethods for JSRef<'a, Node> { return Err(HierarchyRequest); } }, - TextNodeTypeId | - ProcessingInstructionNodeTypeId | - CommentNodeTypeId => (), - DocumentNodeTypeId => unreachable!() + NodeTypeId::Text | + NodeTypeId::ProcessingInstruction | + NodeTypeId::Comment => (), + NodeTypeId::Document => unreachable!() } }, _ => () @@ -1948,16 +1948,16 @@ impl<'a> NodeMethods for JSRef<'a, Node> { { // Step 10. - Node::remove(child, self, Suppressed); + Node::remove(child, self, SuppressObserver::Suppressed); // Step 11. - Node::insert(node, self, reference_child, Suppressed); + Node::insert(node, self, reference_child, SuppressObserver::Suppressed); } // Step 12-14. // Step 13: mutation records. child.node_removed(self.is_in_doc()); - if node.type_id() == DocumentFragmentNodeTypeId { + if node.type_id() == NodeTypeId::DocumentFragment { for child_node in node.children() { child_node.node_inserted(); } @@ -2005,7 +2005,11 @@ impl<'a> NodeMethods for JSRef<'a, Node> { // http://dom.spec.whatwg.org/#dom-node-clonenode fn CloneNode(self, deep: bool) -> Temporary<Node> { - Node::clone(self, None, if deep { CloneChildren } else { DoNotCloneChildren }) + Node::clone(self, None, if deep { + CloneChildrenFlag::CloneChildren + } else { + CloneChildrenFlag::DoNotCloneChildren + }) } // http://dom.spec.whatwg.org/#dom-node-isequalnode @@ -2056,13 +2060,13 @@ impl<'a> NodeMethods for JSRef<'a, Node> { match node.type_id() { // Step 3. - DoctypeNodeTypeId if !is_equal_doctype(this, node) => return false, - ElementNodeTypeId(..) if !is_equal_element(this, node) => return false, - ProcessingInstructionNodeTypeId if !is_equal_processinginstruction(this, node) => return false, - TextNodeTypeId | - CommentNodeTypeId if !is_equal_characterdata(this, node) => return false, + NodeTypeId::DocumentType if !is_equal_doctype(this, node) => return false, + NodeTypeId::Element(..) if !is_equal_element(this, node) => return false, + NodeTypeId::ProcessingInstruction if !is_equal_processinginstruction(this, node) => return false, + NodeTypeId::Text | + NodeTypeId::Comment if !is_equal_characterdata(this, node) => return false, // Step 4. - ElementNodeTypeId(..) if !is_equal_element_attrs(this, node) => return false, + NodeTypeId::Element(..) if !is_equal_element_attrs(this, node) => return false, _ => () } @@ -2280,11 +2284,11 @@ impl<'a> style::TNode<'a, JSRef<'a, Element>> for JSRef<'a, Node> { } }; match attr.namespace { - style::SpecificNamespace(ref ns) => { + style::NamespaceConstraint::Specific(ref ns) => { self.as_element().get_attribute(ns.clone(), name).root() .map_or(false, |attr| test(attr.value().as_slice())) }, - style::AnyNamespace => { + style::NamespaceConstraint::Any => { self.as_element().get_attributes(name).iter() .map(|attr| attr.root()) .any(|attr| test(attr.value().as_slice())) diff --git a/components/script/dom/nodelist.rs b/components/script/dom/nodelist.rs index d30f0ffc6b3..e2b09985146 100644 --- a/components/script/dom/nodelist.rs +++ b/components/script/dom/nodelist.rs @@ -38,19 +38,19 @@ impl NodeList { } pub fn new_simple_list(window: JSRef<Window>, elements: Vec<JSRef<Node>>) -> Temporary<NodeList> { - NodeList::new(window, Simple(elements.iter().map(|element| JS::from_rooted(*element)).collect())) + NodeList::new(window, NodeListType::Simple(elements.iter().map(|element| JS::from_rooted(*element)).collect())) } pub fn new_child_list(window: JSRef<Window>, node: JSRef<Node>) -> Temporary<NodeList> { - NodeList::new(window, Children(JS::from_rooted(node))) + NodeList::new(window, NodeListType::Children(JS::from_rooted(node))) } } impl<'a> NodeListMethods for JSRef<'a, NodeList> { fn Length(self) -> u32 { match self.list_type { - Simple(ref elems) => elems.len() as u32, - Children(ref node) => { + NodeListType::Simple(ref elems) => elems.len() as u32, + NodeListType::Children(ref node) => { let node = node.root(); node.children().count() as u32 } @@ -60,8 +60,8 @@ impl<'a> NodeListMethods for JSRef<'a, NodeList> { fn Item(self, index: u32) -> Option<Temporary<Node>> { match self.list_type { _ if index >= self.Length() => None, - Simple(ref elems) => Some(Temporary::new(elems[index as uint].clone())), - Children(ref node) => { + NodeListType::Simple(ref elems) => Some(Temporary::new(elems[index as uint].clone())), + NodeListType::Children(ref node) => { let node = node.root(); node.children().nth(index as uint) .map(|child| Temporary::from_rooted(child)) diff --git a/components/script/dom/processinginstruction.rs b/components/script/dom/processinginstruction.rs index 7b2c5f22ba6..99c904817a4 100644 --- a/components/script/dom/processinginstruction.rs +++ b/components/script/dom/processinginstruction.rs @@ -9,8 +9,8 @@ use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::characterdata::CharacterData; use dom::document::Document; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; -use dom::node::{Node, ProcessingInstructionNodeTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; /// An HTML processing instruction node. @@ -22,14 +22,14 @@ pub struct ProcessingInstruction { impl ProcessingInstructionDerived for EventTarget { fn is_processinginstruction(&self) -> bool { - *self.type_id() == NodeTargetTypeId(ProcessingInstructionNodeTypeId) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::ProcessingInstruction) } } impl ProcessingInstruction { fn new_inherited(target: DOMString, data: DOMString, document: JSRef<Document>) -> ProcessingInstruction { ProcessingInstruction { - characterdata: CharacterData::new_inherited(ProcessingInstructionNodeTypeId, data, document), + characterdata: CharacterData::new_inherited(NodeTypeId::ProcessingInstruction, data, document), target: target } } diff --git a/components/script/dom/progressevent.rs b/components/script/dom/progressevent.rs index 31b125f8634..f3b4d5f29db 100644 --- a/components/script/dom/progressevent.rs +++ b/components/script/dom/progressevent.rs @@ -10,7 +10,7 @@ use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; -use dom::event::{Event, ProgressEventTypeId}; +use dom::event::{Event, EventTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -23,14 +23,14 @@ pub struct ProgressEvent { impl ProgressEventDerived for Event { fn is_progressevent(&self) -> bool { - *self.type_id() == ProgressEventTypeId + *self.type_id() == EventTypeId::ProgressEvent } } impl ProgressEvent { fn new_inherited(length_computable: bool, loaded: u64, total: u64) -> ProgressEvent { ProgressEvent { - event: Event::new_inherited(ProgressEventTypeId), + event: Event::new_inherited(EventTypeId::ProgressEvent), length_computable: length_computable, loaded: loaded, total: total diff --git a/components/script/dom/testbinding.rs b/components/script/dom/testbinding.rs index 0184cbc99c2..8c4ea8d7817 100644 --- a/components/script/dom/testbinding.rs +++ b/components/script/dom/testbinding.rs @@ -4,12 +4,14 @@ use dom::bindings::codegen::Bindings::TestBindingBinding::TestBindingMethods; use dom::bindings::codegen::Bindings::TestBindingBinding::TestEnum; -use dom::bindings::codegen::Bindings::TestBindingBinding::TestEnumValues::_empty; +use dom::bindings::codegen::Bindings::TestBindingBinding::TestEnum::_empty; use dom::bindings::codegen::Bindings::EventListenerBinding::EventListener; use dom::bindings::codegen::Bindings::FunctionBinding::Function; -use dom::bindings::codegen::UnionTypes::BlobOrString::BlobOrString; -use dom::bindings::codegen::UnionTypes::EventOrString::{EventOrString, eString}; -use dom::bindings::codegen::UnionTypes::HTMLElementOrLong::{HTMLElementOrLong, eLong}; +use dom::bindings::codegen::UnionTypes::BlobOrString; +use dom::bindings::codegen::UnionTypes::EventOrString; +use dom::bindings::codegen::UnionTypes::EventOrString::eString; +use dom::bindings::codegen::UnionTypes::HTMLElementOrLong; +use dom::bindings::codegen::UnionTypes::HTMLElementOrLong::eLong; use dom::bindings::global::GlobalField; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::str::ByteString; diff --git a/components/script/dom/text.rs b/components/script/dom/text.rs index 1843bf58d21..368b1373fa7 100644 --- a/components/script/dom/text.rs +++ b/components/script/dom/text.rs @@ -11,8 +11,8 @@ use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::characterdata::CharacterData; use dom::document::Document; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; -use dom::node::{Node, TextNodeTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; +use dom::node::{Node, NodeTypeId}; use servo_util::str::DOMString; /// An HTML text node. @@ -23,14 +23,14 @@ pub struct Text { impl TextDerived for EventTarget { fn is_text(&self) -> bool { - *self.type_id() == NodeTargetTypeId(TextNodeTypeId) + *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Text) } } impl Text { fn new_inherited(text: DOMString, document: JSRef<Document>) -> Text { Text { - characterdata: CharacterData::new_inherited(TextNodeTypeId, text, document) + characterdata: CharacterData::new_inherited(NodeTypeId::Text, text, document) } } diff --git a/components/script/dom/treewalker.rs b/components/script/dom/treewalker.rs index bac939062ee..d9037788c85 100644 --- a/components/script/dom/treewalker.rs +++ b/components/script/dom/treewalker.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::bindings::callback::RethrowExceptions; +use dom::bindings::callback::ExceptionHandling::RethrowExceptions; use dom::bindings::codegen::Bindings::TreeWalkerBinding; use dom::bindings::codegen::Bindings::TreeWalkerBinding::TreeWalkerMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; @@ -58,8 +58,8 @@ impl TreeWalker { what_to_show: u32, node_filter: Option<NodeFilter>) -> Temporary<TreeWalker> { let filter = match node_filter { - None => FilterNone, - Some(jsfilter) => FilterJS(jsfilter) + None => Filter::None, + Some(jsfilter) => Filter::JS(jsfilter) }; TreeWalker::new_with_filter(document, root_node, what_to_show, filter) } @@ -76,9 +76,9 @@ impl<'a> TreeWalkerMethods for JSRef<'a, TreeWalker> { fn GetFilter(self) -> Option<NodeFilter> { match self.filter { - FilterNone => None, - FilterJS(nf) => Some(nf), - FilterNative(_) => panic!("Cannot convert native node filter to DOM NodeFilter") + Filter::None => None, + Filter::JS(nf) => Some(nf), + Filter::Native(_) => panic!("Cannot convert native node filter to DOM NodeFilter") } } @@ -331,9 +331,9 @@ impl<'a> PrivateTreeWalkerHelpers<'a> for JSRef<'a, TreeWalker> { // "5. If an exception was thrown, re-throw the exception." // "6. Return result." match self.filter { - FilterNone => Ok(NodeFilterConstants::FILTER_ACCEPT), - FilterNative(f) => Ok((f)(node)), - FilterJS(callback) => callback.AcceptNode_(self, node, RethrowExceptions) + Filter::None => Ok(NodeFilterConstants::FILTER_ACCEPT), + Filter::Native(f) => Ok((f)(node)), + Filter::JS(callback) => callback.AcceptNode_(self, node, RethrowExceptions) } } @@ -551,9 +551,9 @@ impl<'a> Iterator<JSRef<'a, Node>> for JSRef<'a, TreeWalker> { #[jstraceable] pub enum Filter { - FilterNone, - FilterNative(fn (node: JSRef<Node>) -> u16), - FilterJS(NodeFilter) + None, + Native(fn (node: JSRef<Node>) -> u16), + JS(NodeFilter) } // FIXME: NodeFilterConstants will be defined in NodeFilterBindings.rs diff --git a/components/script/dom/uievent.rs b/components/script/dom/uievent.rs index f0c2dddf23a..eca5ababb22 100644 --- a/components/script/dom/uievent.rs +++ b/components/script/dom/uievent.rs @@ -12,7 +12,7 @@ use dom::bindings::global; use dom::bindings::js::{MutNullableJS, JSRef, RootedReference, Temporary, OptionalSettable}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; -use dom::event::{Event, EventTypeId, UIEventTypeId}; +use dom::event::{Event, EventTypeId}; use dom::window::Window; use servo_util::str::DOMString; @@ -28,7 +28,7 @@ pub struct UIEvent { impl UIEventDerived for Event { fn is_uievent(&self) -> bool { - *self.type_id() == UIEventTypeId + *self.type_id() == EventTypeId::UIEvent } } @@ -42,7 +42,7 @@ impl UIEvent { } pub fn new_uninitialized(window: JSRef<Window>) -> Temporary<UIEvent> { - reflect_dom_object(box UIEvent::new_inherited(UIEventTypeId), + reflect_dom_object(box UIEvent::new_inherited(EventTypeId::UIEvent), global::Window(window), UIEventBinding::Wrap) } diff --git a/components/script/dom/urlsearchparams.rs b/components/script/dom/urlsearchparams.rs index 11b827be41b..c71a28cc3d1 100644 --- a/components/script/dom/urlsearchparams.rs +++ b/components/script/dom/urlsearchparams.rs @@ -5,7 +5,8 @@ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::URLSearchParamsBinding; use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsMethods; -use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams::{StringOrURLSearchParams, eURLSearchParams, eString}; +use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams; +use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams::{eURLSearchParams, eString}; use dom::bindings::error::{Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; @@ -14,7 +15,7 @@ use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use servo_util::str::DOMString; use encoding::all::UTF_8; -use encoding::types::{EncodingRef, EncodeReplace}; +use encoding::types::{EncodingRef, EncoderTrap}; use std::collections::HashMap; use std::collections::hash_map::{Occupied, Vacant}; @@ -111,7 +112,7 @@ impl URLSearchParamsHelpers for URLSearchParams { let value = value.as_slice(); // XXXManishearth should this be a strict encoding? Can unwrap()ing the result fail? - let value = encoding.encode(value, EncodeReplace).unwrap(); + let value = encoding.encode(value, EncoderTrap::Replace).unwrap(); let mut buf = vec!(); for i in value.iter() { let append = match *i { diff --git a/components/script/dom/virtualmethods.rs b/components/script/dom/virtualmethods.rs index 94a74124eca..ff78a7beaa6 100644 --- a/components/script/dom/virtualmethods.rs +++ b/components/script/dom/virtualmethods.rs @@ -2,8 +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; -use dom::attr::{AttrValue, StringAttrValue}; +use dom::attr::{Attr, AttrValue}; use dom::bindings::codegen::InheritTypes::ElementCast; use dom::bindings::codegen::InheritTypes::HTMLAnchorElementCast; use dom::bindings::codegen::InheritTypes::HTMLAreaElementCast; @@ -31,30 +30,7 @@ use dom::bindings::codegen::InheritTypes::HTMLTitleElementCast; use dom::bindings::js::JSRef; use dom::document::Document; use dom::element::Element; -use dom::element::ElementTypeId_; -use dom::element::HTMLAnchorElementTypeId; -use dom::element::HTMLAreaElementTypeId; -use dom::element::HTMLBodyElementTypeId; -use dom::element::HTMLButtonElementTypeId; -use dom::element::HTMLCanvasElementTypeId; -use dom::element::HTMLFieldSetElementTypeId; -use dom::element::HTMLIFrameElementTypeId; -use dom::element::HTMLImageElementTypeId; -use dom::element::HTMLInputElementTypeId; -use dom::element::HTMLLinkElementTypeId; -use dom::element::HTMLObjectElementTypeId; -use dom::element::HTMLOptGroupElementTypeId; -use dom::element::HTMLOptionElementTypeId; -use dom::element::HTMLScriptElementTypeId; -use dom::element::HTMLSelectElementTypeId; -use dom::element::HTMLStyleElementTypeId; -use dom::element::HTMLTableDataCellElementTypeId; -use dom::element::HTMLTableElementTypeId; -use dom::element::HTMLTableHeaderCellElementTypeId; -use dom::element::HTMLTableRowElementTypeId; -use dom::element::HTMLTableSectionElementTypeId; -use dom::element::HTMLTextAreaElementTypeId; -use dom::element::HTMLTitleElementTypeId; +use dom::element::ElementTypeId; use dom::event::Event; use dom::htmlanchorelement::HTMLAnchorElement; use dom::htmlareaelement::HTMLAreaElement; @@ -79,7 +55,7 @@ use dom::htmltablerowelement::HTMLTableRowElement; use dom::htmltablesectionelement::HTMLTableSectionElement; use dom::htmltextareaelement::HTMLTextAreaElement; use dom::htmltitleelement::HTMLTitleElement; -use dom::node::{Node, NodeHelpers, ElementNodeTypeId, CloneChildrenFlag}; +use dom::node::{Node, NodeHelpers, NodeTypeId, CloneChildrenFlag}; use servo_util::str::DOMString; @@ -115,7 +91,7 @@ pub trait VirtualMethods { fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { match self.super_type() { Some(ref s) => s.parse_plain_attribute(name, value), - _ => StringAttrValue(value), + _ => AttrValue::String(value), } } @@ -171,105 +147,105 @@ pub trait VirtualMethods { /// interrupted. pub fn vtable_for<'a>(node: &'a JSRef<'a, Node>) -> &'a VirtualMethods + 'a { match node.type_id() { - ElementNodeTypeId(HTMLAnchorElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLAnchorElement) => { let element: &'a JSRef<'a, HTMLAnchorElement> = HTMLAnchorElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLAreaElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLAreaElement) => { let element: &'a JSRef<'a, HTMLAreaElement> = HTMLAreaElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLBodyElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLBodyElement) => { let element: &'a JSRef<'a, HTMLBodyElement> = HTMLBodyElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLButtonElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLButtonElement) => { let element: &'a JSRef<'a, HTMLButtonElement> = HTMLButtonElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLCanvasElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLCanvasElement) => { let element: &'a JSRef<'a, HTMLCanvasElement> = HTMLCanvasElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLFieldSetElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLFieldSetElement) => { let element: &'a JSRef<'a, HTMLFieldSetElement> = HTMLFieldSetElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLImageElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLImageElement) => { let element: &'a JSRef<'a, HTMLImageElement> = HTMLImageElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLIFrameElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLIFrameElement) => { let element: &'a JSRef<'a, HTMLIFrameElement> = HTMLIFrameElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLInputElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLInputElement) => { let element: &'a JSRef<'a, HTMLInputElement> = HTMLInputElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLLinkElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLLinkElement) => { let element: &'a JSRef<'a, HTMLLinkElement> = HTMLLinkElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLObjectElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLObjectElement) => { let element: &'a JSRef<'a, HTMLObjectElement> = HTMLObjectElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLOptGroupElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLOptGroupElement) => { let element: &'a JSRef<'a, HTMLOptGroupElement> = HTMLOptGroupElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLOptionElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLOptionElement) => { let element: &'a JSRef<'a, HTMLOptionElement> = HTMLOptionElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLScriptElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLScriptElement) => { let element: &'a JSRef<'a, HTMLScriptElement> = HTMLScriptElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLSelectElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLSelectElement) => { let element: &'a JSRef<'a, HTMLSelectElement> = HTMLSelectElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLStyleElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLStyleElement) => { let element: &'a JSRef<'a, HTMLStyleElement> = HTMLStyleElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLTableElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLTableElement) => { let element: &'a JSRef<'a, HTMLTableElement> = HTMLTableElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLTableDataCellElementTypeId) | - ElementNodeTypeId(HTMLTableHeaderCellElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLTableDataCellElement) | + NodeTypeId::Element(ElementTypeId::HTMLTableHeaderCellElement) => { let element: &'a JSRef<'a, HTMLTableCellElement> = HTMLTableCellElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLTableRowElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLTableRowElement) => { let element: &'a JSRef<'a, HTMLTableRowElement> = HTMLTableRowElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLTableSectionElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLTableSectionElement) => { let element: &'a JSRef<'a, HTMLTableSectionElement> = HTMLTableSectionElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLTextAreaElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLTextAreaElement) => { let element: &'a JSRef<'a, HTMLTextAreaElement> = HTMLTextAreaElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(HTMLTitleElementTypeId) => { + NodeTypeId::Element(ElementTypeId::HTMLTitleElement) => { let element: &'a JSRef<'a, HTMLTitleElement> = HTMLTitleElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(ElementTypeId_) => { + NodeTypeId::Element(ElementTypeId::Element) => { let element: &'a JSRef<'a, Element> = ElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } - ElementNodeTypeId(_) => { + NodeTypeId::Element(_) => { let element: &'a JSRef<'a, HTMLElement> = HTMLElementCast::to_borrowed_ref(node).unwrap(); element as &'a VirtualMethods + 'a } diff --git a/components/script/dom/websocket.rs b/components/script/dom/websocket.rs index c40ac560f49..3e565bfd367 100644 --- a/components/script/dom/websocket.rs +++ b/components/script/dom/websocket.rs @@ -8,7 +8,7 @@ use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{Temporary, JSRef}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; -use dom::eventtarget::{EventTarget, WebSocketTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use servo_util::str::DOMString; #[dom_struct] @@ -20,7 +20,7 @@ pub struct WebSocket { impl WebSocket { pub fn new_inherited(url: DOMString) -> WebSocket { WebSocket { - eventtarget: EventTarget::new_inherited(WebSocketTypeId), + eventtarget: EventTarget::new_inherited(EventTargetTypeId::WebSocket), url: url } } diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index be5d8ad35b2..8142b455f99 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -8,14 +8,15 @@ use dom::bindings::codegen::Bindings::FunctionBinding::Function; use dom::bindings::codegen::Bindings::WindowBinding; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::InheritTypes::EventTargetCast; -use dom::bindings::error::{Fallible, InvalidCharacter}; +use dom::bindings::error::Fallible; +use dom::bindings::error::Error::InvalidCharacter; use dom::bindings::global; use dom::bindings::js::{MutNullableJS, JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::browsercontext::BrowserContext; use dom::console::Console; use dom::document::Document; -use dom::eventtarget::{EventTarget, WindowTypeId, EventTargetHelpers}; +use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; use dom::location::Location; use dom::navigator::Navigator; use dom::performance::Performance; @@ -23,10 +24,10 @@ use dom::screen::Screen; use dom::storage::Storage; use layout_interface::{NoQuery, ReflowForDisplay, ReflowGoal, ReflowQueryType}; use page::Page; -use script_task::{ExitWindowMsg, ScriptChan, TriggerLoadMsg, TriggerFragmentMsg}; -use script_task::FromWindow; +use script_task::{TimerSource, ScriptChan}; +use script_task::ScriptMsg::{ExitWindowMsg, TriggerLoadMsg, TriggerFragmentMsg}; use script_traits::ScriptControlChan; -use timers::{Interval, NonInterval, TimerId, TimerManager}; +use timers::{IsInterval, TimerId, TimerManager}; use servo_msg::compositor_msg::ScriptListener; use servo_msg::constellation_msg::LoadData; @@ -218,8 +219,8 @@ impl<'a> WindowMethods for JSRef<'a, Window> { self.timers.set_timeout_or_interval(callback, args, timeout, - NonInterval, - FromWindow(self.page.id.clone()), + IsInterval::NonInterval, + TimerSource::FromWindow(self.page.id.clone()), self.script_chan.clone()) } @@ -231,8 +232,8 @@ impl<'a> WindowMethods for JSRef<'a, Window> { self.timers.set_timeout_or_interval(callback, args, timeout, - Interval, - FromWindow(self.page.id.clone()), + IsInterval::Interval, + TimerSource::FromWindow(self.page.id.clone()), self.script_chan.clone()) } @@ -370,7 +371,7 @@ impl Window { image_cache_task: ImageCacheTask) -> Temporary<Window> { let win = box Window { - eventtarget: EventTarget::new_inherited(WindowTypeId), + eventtarget: EventTarget::new_inherited(EventTargetTypeId::Window), script_chan: script_chan, control_chan: control_chan, console: Default::default(), diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index ae7af114d7a..ed90118d1fd 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -6,15 +6,17 @@ use dom::bindings::codegen::Bindings::WorkerBinding; use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMethods; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::InheritTypes::EventTargetCast; -use dom::bindings::error::{Fallible, Syntax, ErrorResult, DataClone}; +use dom::bindings::error::{Fallible, ErrorResult}; +use dom::bindings::error::Error::{Syntax, DataClone}; use dom::bindings::global::{GlobalRef, GlobalField}; use dom::bindings::js::{JS, JSRef, Temporary}; use dom::bindings::trace::JSTraceable; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScope; -use dom::eventtarget::{EventTarget, EventTargetHelpers, WorkerTypeId}; +use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; use dom::messageevent::MessageEvent; -use script_task::{ScriptChan, DOMMessage}; +use script_task::ScriptChan; +use script_task::ScriptMsg::DOMMessage; use servo_util::str::DOMString; @@ -44,7 +46,7 @@ pub struct Worker { impl Worker { fn new_inherited(global: &GlobalRef, sender: ScriptChan) -> Worker { Worker { - eventtarget: EventTarget::new_inherited(WorkerTypeId), + eventtarget: EventTarget::new_inherited(EventTargetTypeId::Worker), refcount: Cell::new(0), global: GlobalField::from_rooted(global), sender: sender, diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index c5e87e90a83..f1dcbd5adfd 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -4,17 +4,18 @@ use dom::bindings::codegen::Bindings::WorkerGlobalScopeBinding::WorkerGlobalScopeMethods; use dom::bindings::codegen::Bindings::FunctionBinding::Function; -use dom::bindings::error::{ErrorResult, Fallible, Syntax, Network, FailureUnknown}; +use dom::bindings::error::{ErrorResult, Fallible}; +use dom::bindings::error::Error::{Syntax, Network, FailureUnknown}; use dom::bindings::global; use dom::bindings::js::{MutNullableJS, JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::console::Console; -use dom::eventtarget::{EventTarget, WorkerGlobalScopeTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::workerlocation::WorkerLocation; use dom::workernavigator::WorkerNavigator; use dom::window::{base64_atob, base64_btoa}; -use script_task::{ScriptChan, FromWorker}; -use timers::{Interval, NonInterval, TimerId, TimerManager}; +use script_task::{ScriptChan, TimerSource}; +use timers::{IsInterval, TimerId, TimerManager}; use servo_net::resource_task::{ResourceTask, load_whole_resource}; use servo_util::str::DOMString; @@ -29,7 +30,7 @@ use url::{Url, UrlParser}; #[deriving(PartialEq)] #[jstraceable] -pub enum WorkerGlobalScopeId { +pub enum WorkerGlobalScopeTypeId { DedicatedGlobalScope, } @@ -47,13 +48,13 @@ pub struct WorkerGlobalScope { } impl WorkerGlobalScope { - pub fn new_inherited(type_id: WorkerGlobalScopeId, + pub fn new_inherited(type_id: WorkerGlobalScopeTypeId, worker_url: Url, cx: Rc<Cx>, resource_task: ResourceTask, script_chan: ScriptChan) -> WorkerGlobalScope { WorkerGlobalScope { - eventtarget: EventTarget::new_inherited(WorkerGlobalScopeTypeId(type_id)), + eventtarget: EventTarget::new_inherited(EventTargetTypeId::WorkerGlobalScope(type_id)), worker_url: worker_url, js_context: cx, resource_task: resource_task, @@ -150,8 +151,8 @@ impl<'a> WorkerGlobalScopeMethods for JSRef<'a, WorkerGlobalScope> { self.timers.set_timeout_or_interval(callback, args, timeout, - NonInterval, - FromWorker, + IsInterval::NonInterval, + TimerSource::FromWorker, self.script_chan.clone()) } @@ -163,8 +164,8 @@ impl<'a> WorkerGlobalScopeMethods for JSRef<'a, WorkerGlobalScope> { self.timers.set_timeout_or_interval(callback, args, timeout, - Interval, - FromWorker, + IsInterval::Interval, + TimerSource::FromWorker, self.script_chan.clone()) } diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index b5f580fc6a5..451c3ab8079 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -2,32 +2,40 @@ * 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 self::SyncOrAsync::*; +use self::TerminateReason::*; +use self::XHRProgress::*; +use self::XMLHttpRequestState::*; + use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::XMLHttpRequestBinding; use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::XMLHttpRequestMethods; use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::XMLHttpRequestResponseType; -use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::XMLHttpRequestResponseTypeValues; -use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::XMLHttpRequestResponseTypeValues::{_empty, Json, Text}; +use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::XMLHttpRequestResponseType::{_empty, Json, Text}; use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast, XMLHttpRequestDerived}; use dom::bindings::conversions::ToJSValConvertible; -use dom::bindings::error::{Error, ErrorResult, Fallible, InvalidState, InvalidAccess}; -use dom::bindings::error::{Network, Syntax, Security, Abort, Timeout}; +use dom::bindings::error::{Error, ErrorResult, Fallible}; +use dom::bindings::error::Error::{InvalidState, InvalidAccess}; +use dom::bindings::error::Error::{Network, Syntax, Security, Abort, Timeout}; use dom::bindings::global::{GlobalField, GlobalRef, WorkerRoot}; use dom::bindings::js::{MutNullableJS, JS, JSRef, Temporary, OptionalRootedRootable}; use dom::bindings::str::ByteString; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::document::Document; -use dom::event::{Event, DoesNotBubble, Cancelable}; -use dom::eventtarget::{EventTarget, EventTargetHelpers, XMLHttpRequestTargetTypeId}; +use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; use dom::progressevent::ProgressEvent; use dom::urlsearchparams::URLSearchParamsHelpers; use dom::xmlhttprequesteventtarget::XMLHttpRequestEventTarget; +use dom::xmlhttprequesteventtarget::XMLHttpRequestEventTargetTypeId; use dom::xmlhttprequestupload::XMLHttpRequestUpload; +use script_task::ScriptChan; +use script_task::ScriptMsg::{XHRProgressMsg, XHRReleaseMsg}; use encoding::all::UTF_8; use encoding::label::encoding_from_whatwg_label; -use encoding::types::{DecodeReplace, Encoding, EncodingRef, EncodeReplace}; +use encoding::types::{DecoderTrap, Encoding, EncodingRef, EncoderTrap}; use hyper::header::Headers; use hyper::header::common::{Accept, ContentLength, ContentType}; @@ -43,8 +51,7 @@ use libc; use libc::c_void; use net::resource_task::{ResourceTask, ResourceCORSData, Load, LoadData, LoadResponse, Payload, Done}; -use cors::{allow_cross_origin_request, CORSRequest, CORSMode, ForcedPreflightMode}; -use script_task::{ScriptChan, XHRProgressMsg, XHRReleaseMsg}; +use cors::{allow_cross_origin_request, CORSRequest, RequestMode}; use servo_util::str::DOMString; use servo_util::task::spawn_named; @@ -53,23 +60,15 @@ use std::cell::Cell; use std::comm::{Sender, Receiver, channel}; use std::default::Default; use std::io::Timer; -use std::from_str::FromStr; +use std::str::FromStr; use std::time::duration::Duration; -use std::num::Zero; use time; use url::{Url, UrlParser}; -use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams::{eString, eURLSearchParams, StringOrURLSearchParams}; +use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams; +use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams::{eString, eURLSearchParams}; pub type SendParam = StringOrURLSearchParams; - -#[deriving(PartialEq)] -#[jstraceable] -pub enum XMLHttpRequestId { - XMLHttpRequestTypeId, - XMLHttpRequestUploadTypeId -} - #[deriving(PartialEq)] #[jstraceable] enum XMLHttpRequestState { @@ -152,7 +151,7 @@ pub struct XMLHttpRequest { impl XMLHttpRequest { fn new_inherited(global: &GlobalRef) -> XMLHttpRequest { XMLHttpRequest { - eventtarget: XMLHttpRequestEventTarget::new_inherited(XMLHttpRequestTypeId), + eventtarget: XMLHttpRequestEventTarget::new_inherited(XMLHttpRequestEventTargetTypeId::XMLHttpRequest), ready_state: Cell::new(Unsent), timeout: Cell::new(0u32), with_credentials: Cell::new(false), @@ -570,7 +569,7 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> { if !request_headers.has::<Accept>() { request_headers.set( - Accept(vec![Mime(mime::TopStar, mime::SubStar, vec![])])); + Accept(vec![Mime(mime::TopLevel::Star, mime::SubLevel::Star, vec![])])); } } // drops the borrow_mut @@ -582,9 +581,9 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> { // CORS stuff let referer_url = self.global.root().root_ref().get_url(); let mode = if self.upload_events.get() { - ForcedPreflightMode + RequestMode::ForcedPreflight } else { - CORSMode + RequestMode::CORS }; let cors_request = CORSRequest::maybe_new(referer_url.clone(), load_data.url.clone(), mode, load_data.method.clone(), load_data.headers.clone()); @@ -681,7 +680,7 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> { } fn SetResponseType(self, response_type: XMLHttpRequestResponseType) -> ErrorResult { match self.global.root() { - WorkerRoot(_) if response_type == XMLHttpRequestResponseTypeValues::Document + WorkerRoot(_) if response_type == XMLHttpRequestResponseType::Document => return Ok(()), _ => {} } @@ -706,7 +705,7 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> { }, _ if self.ready_state.get() != XHRDone => NullValue(), Json => { - let decoded = UTF_8.decode(self.response.borrow().as_slice(), DecodeReplace).unwrap().to_string(); + let decoded = UTF_8.decode(self.response.borrow().as_slice(), DecoderTrap::Replace).unwrap().to_string(); let decoded: Vec<u16> = decoded.as_slice().utf16_units().collect(); let mut vp = UndefinedValue(); unsafe { @@ -748,7 +747,7 @@ impl Reflectable for XMLHttpRequest { impl XMLHttpRequestDerived for EventTarget { fn is_xmlhttprequest(&self) -> bool { match *self.type_id() { - XMLHttpRequestTargetTypeId(XMLHttpRequestTypeId) => true, + EventTargetTypeId::XMLHttpRequestEventTarget(XMLHttpRequestEventTargetTypeId::XMLHttpRequest) => true, _ => false } } @@ -815,7 +814,8 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> { let global = self.global.root(); let event = Event::new(global.root_ref(), "readystatechange".to_string(), - DoesNotBubble, Cancelable).root(); + EventBubbles::DoesNotBubble, + EventCancelable::Cancelable).root(); let target: JSRef<EventTarget> = EventTargetCast::from_ref(self); target.dispatch_event(*event); } @@ -859,7 +859,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> { // Substep 2 status.map(|RawStatus(code, reason)| { self.status.set(code); - *self.status_text.borrow_mut() = ByteString::new(reason.into_bytes()); + *self.status_text.borrow_mut() = ByteString::new(format!("{}", reason).into_bytes()); }); headers.as_ref().map(|h| *self.response_headers.borrow_mut() = h.clone()); @@ -995,7 +995,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> { fn cancel_timeout(self) { // oneshot() closes the previous channel, canceling the timeout - self.timer.borrow_mut().oneshot(Zero::zero()); + self.timer.borrow_mut().oneshot(Duration::zero()); } fn text_response(self) -> DOMString { @@ -1013,7 +1013,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> { // According to Simon, decode() should never return an error, so unwrap()ing // the result should be fine. XXXManishearth have a closer look at this later - encoding.decode(self.response.borrow().as_slice(), DecodeReplace).unwrap().to_string() + encoding.decode(self.response.borrow().as_slice(), DecoderTrap::Replace).unwrap().to_string() } fn filter_response_headers(self) -> Headers { // http://fetch.spec.whatwg.org/#concept-response-header-list @@ -1055,7 +1055,7 @@ impl Extractable for SendParam { // http://fetch.spec.whatwg.org/#concept-fetchbodyinit-extract let encoding = UTF_8 as EncodingRef; match *self { - eString(ref s) => encoding.encode(s.as_slice(), EncodeReplace).unwrap(), + eString(ref s) => encoding.encode(s.as_slice(), EncoderTrap::Replace).unwrap(), eURLSearchParams(ref usp) => usp.root().serialize(None) // Default encoding is UTF8 } } diff --git a/components/script/dom/xmlhttprequesteventtarget.rs b/components/script/dom/xmlhttprequesteventtarget.rs index 0510a37bfbb..231cf1e0d4a 100644 --- a/components/script/dom/xmlhttprequesteventtarget.rs +++ b/components/script/dom/xmlhttprequesteventtarget.rs @@ -8,8 +8,14 @@ use dom::bindings::codegen::InheritTypes::EventTargetCast; use dom::bindings::codegen::InheritTypes::XMLHttpRequestEventTargetDerived; use dom::bindings::js::JSRef; use dom::bindings::utils::{Reflectable, Reflector}; -use dom::eventtarget::{EventTarget, EventTargetHelpers, XMLHttpRequestTargetTypeId}; -use dom::xmlhttprequest::XMLHttpRequestId; +use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; + +#[deriving(PartialEq)] +#[jstraceable] +pub enum XMLHttpRequestEventTargetTypeId { + XMLHttpRequest, + XMLHttpRequestUpload, +} #[dom_struct] pub struct XMLHttpRequestEventTarget { @@ -17,9 +23,9 @@ pub struct XMLHttpRequestEventTarget { } impl XMLHttpRequestEventTarget { - pub fn new_inherited(type_id: XMLHttpRequestId) -> XMLHttpRequestEventTarget { + pub fn new_inherited(type_id: XMLHttpRequestEventTargetTypeId) -> XMLHttpRequestEventTarget { XMLHttpRequestEventTarget { - eventtarget: EventTarget::new_inherited(XMLHttpRequestTargetTypeId(type_id)) + eventtarget: EventTarget::new_inherited(EventTargetTypeId::XMLHttpRequestEventTarget(type_id)) } } @@ -31,7 +37,7 @@ impl XMLHttpRequestEventTarget { impl XMLHttpRequestEventTargetDerived for EventTarget { fn is_xmlhttprequesteventtarget(&self) -> bool { match *self.type_id() { - XMLHttpRequestTargetTypeId(_) => true, + EventTargetTypeId::XMLHttpRequestEventTarget(_) => true, _ => false } } diff --git a/components/script/dom/xmlhttprequestupload.rs b/components/script/dom/xmlhttprequestupload.rs index 1b21eb35548..2af3245689a 100644 --- a/components/script/dom/xmlhttprequestupload.rs +++ b/components/script/dom/xmlhttprequestupload.rs @@ -7,9 +7,9 @@ use dom::bindings::codegen::Bindings::XMLHttpRequestUploadBinding; use dom::bindings::global::GlobalRef; use dom::bindings::js::Temporary; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; -use dom::eventtarget::{EventTarget, XMLHttpRequestTargetTypeId}; -use dom::xmlhttprequest::{XMLHttpRequestUploadTypeId}; +use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::xmlhttprequesteventtarget::XMLHttpRequestEventTarget; +use dom::xmlhttprequesteventtarget::XMLHttpRequestEventTargetTypeId; #[dom_struct] pub struct XMLHttpRequestUpload { @@ -19,7 +19,7 @@ pub struct XMLHttpRequestUpload { impl XMLHttpRequestUpload { fn new_inherited() -> XMLHttpRequestUpload { XMLHttpRequestUpload { - eventtarget:XMLHttpRequestEventTarget::new_inherited(XMLHttpRequestUploadTypeId) + eventtarget: XMLHttpRequestEventTarget::new_inherited(XMLHttpRequestEventTargetTypeId::XMLHttpRequestUpload) } } pub fn new(global: GlobalRef) -> Temporary<XMLHttpRequestUpload> { @@ -36,6 +36,6 @@ impl Reflectable for XMLHttpRequestUpload { impl XMLHttpRequestUploadDerived for EventTarget { fn is_xmlhttprequestupload(&self) -> bool { - *self.type_id() == XMLHttpRequestTargetTypeId(XMLHttpRequestUploadTypeId) + *self.type_id() == EventTargetTypeId::XMLHttpRequestEventTarget(XMLHttpRequestEventTargetTypeId::XMLHttpRequestUpload) } } diff --git a/components/script/layout_interface.rs b/components/script/layout_interface.rs index 0f3f4fbacbf..380289fd091 100644 --- a/components/script/layout_interface.rs +++ b/components/script/layout_interface.rs @@ -6,6 +6,10 @@ /// coupling between these two components, and enables the DOM to be placed in a separate crate /// from layout. +pub use self::Msg::*; +pub use self::ReflowGoal::*; +pub use self::ReflowQueryType::*; + use dom::node::LayoutDataRef; use geom::point::Point2D; diff --git a/components/script/lib.rs b/components/script/lib.rs index 2cf8f99d4f3..26f773f6006 100644 --- a/components/script/lib.rs +++ b/components/script/lib.rs @@ -5,7 +5,7 @@ #![comment = "The Servo Parallel Browser Project"] #![license = "MPL"] -#![feature(default_type_params, globs, macro_rules, struct_variant, phase, unsafe_destructor)] +#![feature(default_type_params, globs, macro_rules, phase, unsafe_destructor)] #![deny(unused_imports)] #![deny(unused_variables)] diff --git a/components/script/page.rs b/components/script/page.rs index c5b1f74c73a..c4c0f741c4c 100644 --- a/components/script/page.rs +++ b/components/script/page.rs @@ -33,7 +33,7 @@ use servo_util::smallvec::SmallVec; use std::cell::{Cell, Ref, RefMut}; use std::comm::{channel, Receiver, Empty, Disconnected}; use std::mem::replace; -use std::num::abs; +use std::num::Float; use std::rc::Rc; use url::Url; @@ -456,10 +456,10 @@ fn should_move_clip_rect(clip_rect: Rect<Au>, new_viewport: Rect<f32>) -> bool{ static VIEWPORT_SCROLL_MARGIN_SIZE: f32 = 0.5; let viewport_scroll_margin = new_viewport.size * VIEWPORT_SCROLL_MARGIN_SIZE; - abs(clip_rect.origin.x - new_viewport.origin.x) <= viewport_scroll_margin.width || - abs(clip_rect.max_x() - new_viewport.max_x()) <= viewport_scroll_margin.width || - abs(clip_rect.origin.y - new_viewport.origin.y) <= viewport_scroll_margin.height || - abs(clip_rect.max_y() - new_viewport.max_y()) <= viewport_scroll_margin.height + (clip_rect.origin.x - new_viewport.origin.x).abs() <= viewport_scroll_margin.width || + (clip_rect.max_x() - new_viewport.max_x()).abs() <= viewport_scroll_margin.width || + (clip_rect.origin.y - new_viewport.origin.y).abs() <= viewport_scroll_margin.height || + (clip_rect.max_y() - new_viewport.max_y()).abs() <= viewport_scroll_margin.height } /// Information for one frame in the browsing context. diff --git a/components/script/parse/html.rs b/components/script/parse/html.rs index e4980fd6a1c..99d23e33674 100644 --- a/components/script/parse/html.rs +++ b/components/script/parse/html.rs @@ -9,7 +9,7 @@ use dom::bindings::js::{JS, JSRef, Temporary, OptionalRootable, Root}; use dom::comment::Comment; use dom::document::{Document, DocumentHelpers}; use dom::documenttype::DocumentType; -use dom::element::{Element, AttributeHandlers, ElementHelpers, ParserCreated}; +use dom::element::{Element, AttributeHandlers, ElementHelpers, ElementCreator}; use dom::htmlscriptelement::HTMLScriptElement; use dom::htmlscriptelement::HTMLScriptElementHelpers; use dom::node::{Node, NodeHelpers, TrustedNodeAddress}; @@ -19,7 +19,7 @@ use dom::text::Text; use parse::Parser; use encoding::all::UTF_8; -use encoding::types::{Encoding, DecodeReplace}; +use encoding::types::{Encoding, DecoderTrap}; use servo_net::resource_task::{Payload, Done, LoadResponse}; use servo_util::task_state; @@ -77,7 +77,8 @@ impl<'a> TreeSink<TrustedNodeAddress> for servohtmlparser::Sink { fn create_element(&mut self, name: QualName, attrs: Vec<Attribute>) -> TrustedNodeAddress { let doc = self.document.root(); - let elem = Element::create(name, None, *doc, ParserCreated).root(); + let elem = Element::create(name, None, *doc, + ElementCreator::ParserCreated).root(); for attr in attrs.into_iter() { elem.set_attribute_from_parser(attr.name, attr.value, None); @@ -170,10 +171,10 @@ pub fn parse_html(document: JSRef<Document>, task_state::enter(IN_HTML_PARSER); match input { - InputString(s) => { + HTMLInput::InputString(s) => { parser.parse_chunk(s); } - InputUrl(load_response) => { + HTMLInput::InputUrl(load_response) => { match load_response.metadata.content_type { Some((ref t, _)) if t.as_slice().eq_ignore_ascii_case("image") => { let page = format!("<html><body><img src='{:s}' /></body></html>", url.serialize()); @@ -184,7 +185,7 @@ pub fn parse_html(document: JSRef<Document>, match msg { Payload(data) => { // FIXME: use Vec<u8> (html5ever #34) - let data = UTF_8.decode(data.as_slice(), DecodeReplace).unwrap(); + let data = UTF_8.decode(data.as_slice(), DecoderTrap::Replace).unwrap(); parser.parse_chunk(data); } Done(Err(err)) => { diff --git a/components/script/script_task.rs b/components/script/script_task.rs index 4e9fe1a93c2..3fc455d588a 100644 --- a/components/script/script_task.rs +++ b/components/script/script_task.rs @@ -5,29 +5,31 @@ //! The script task is the task that owns the DOM in memory, runs JavaScript, and spawns parsing //! and layout tasks. +use self::ScriptMsg::*; + use dom::bindings::cell::DOMRefCell; -use dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, DocumentReadyStateValues}; +use dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, DocumentReadyState}; use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::EventTargetBinding::EventTargetMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::InheritTypes::{ElementCast, EventTargetCast, NodeCast, EventCast}; -use dom::bindings::conversions::{FromJSValConvertible, Empty}; +use dom::bindings::conversions::FromJSValConvertible; +use dom::bindings::conversions::StringificationBehavior; use dom::bindings::global; use dom::bindings::js::{JS, JSRef, RootCollection, Temporary, OptionalRootable}; use dom::bindings::trace::JSTraceable; use dom::bindings::utils::{wrap_for_same_compartment, pre_wrap}; -use dom::document::{Document, HTMLDocument, DocumentHelpers, FromParser}; -use dom::element::{Element, HTMLButtonElementTypeId, HTMLInputElementTypeId}; -use dom::element::{HTMLSelectElementTypeId, HTMLTextAreaElementTypeId, HTMLOptionElementTypeId, ActivationElementHelpers}; -use dom::event::{Event, EventHelpers, Bubbles, DoesNotBubble, Cancelable, NotCancelable}; +use dom::document::{Document, IsHTMLDocument, DocumentHelpers, DocumentSource}; +use dom::element::{Element, ElementTypeId, ActivationElementHelpers}; +use dom::event::{Event, EventHelpers, EventBubbles, EventCancelable}; use dom::uievent::UIEvent; use dom::eventtarget::{EventTarget, EventTargetHelpers}; use dom::keyboardevent::KeyboardEvent; -use dom::node::{mod, ElementNodeTypeId, Node, NodeHelpers, OtherNodeDamage}; +use dom::node::{mod, Node, NodeHelpers, NodeDamage, NodeTypeId}; use dom::window::{Window, WindowHelpers}; use dom::worker::{Worker, TrustedWorkerAddress}; use dom::xmlhttprequest::{TrustedXHRAddress, XMLHttpRequest, XHRProgress}; -use parse::html::{InputString, InputUrl, parse_html}; +use parse::html::{HTMLInput, parse_html}; use layout_interface::{ScriptLayoutChan, LayoutChan, NoQuery, ReflowForDisplay}; use layout_interface; use page::{Page, IterablePage, Frame}; @@ -235,12 +237,12 @@ trait PrivateScriptTaskHelpers { impl<'a> PrivateScriptTaskHelpers for JSRef<'a, Node> { fn click_event_filter_by_disabled_state(&self) -> bool { match self.type_id() { - ElementNodeTypeId(HTMLButtonElementTypeId) | - ElementNodeTypeId(HTMLInputElementTypeId) | - // ElementNodeTypeId(HTMLKeygenElementTypeId) | - ElementNodeTypeId(HTMLOptionElementTypeId) | - ElementNodeTypeId(HTMLSelectElementTypeId) | - ElementNodeTypeId(HTMLTextAreaElementTypeId) if self.get_disabled_state() => true, + NodeTypeId::Element(ElementTypeId::HTMLButtonElement) | + NodeTypeId::Element(ElementTypeId::HTMLInputElement) | + // NodeTypeId::Element(ElementTypeId::HTMLKeygenElement) | + NodeTypeId::Element(ElementTypeId::HTMLOptionElement) | + NodeTypeId::Element(ElementTypeId::HTMLSelectElement) | + NodeTypeId::Element(ElementTypeId::HTMLTextAreaElement) if self.get_disabled_state() => true, _ => false } } @@ -467,11 +469,11 @@ impl ScriptTask { } let ret = sel.wait(); if ret == port1.id() { - FromScript(self.port.recv()) + MixedMessage::FromScript(self.port.recv()) } else if ret == port2.id() { - FromConstellation(self.control_port.recv()) + MixedMessage::FromConstellation(self.control_port.recv()) } else if ret == port3.id() { - FromDevtools(self.devtools_port.recv()) + MixedMessage::FromDevtools(self.devtools_port.recv()) } else { panic!("unexpected select result") } @@ -483,15 +485,15 @@ impl ScriptTask { // This has to be handled before the ResizeMsg below, // otherwise the page may not have been added to the // child list yet, causing the find() to fail. - FromConstellation(AttachLayoutMsg(new_layout_info)) => { + MixedMessage::FromConstellation(AttachLayoutMsg(new_layout_info)) => { self.handle_new_layout(new_layout_info); } - FromConstellation(ResizeMsg(id, size)) => { + MixedMessage::FromConstellation(ResizeMsg(id, size)) => { let page = self.page.borrow_mut(); let page = page.find(id).expect("resize sent to nonexistent pipeline"); page.resize_event.set(Some(size)); } - FromConstellation(ViewportMsg(id, rect)) => { + MixedMessage::FromConstellation(ViewportMsg(id, rect)) => { let page = self.page.borrow_mut(); let inner_page = page.find(id).expect("Page rect message sent to nonexistent pipeline"); if inner_page.set_page_clip_rect_with_new_viewport(rect) { @@ -511,22 +513,22 @@ impl ScriptTask { Err(_) => match self.port.try_recv() { Err(_) => match self.devtools_port.try_recv() { Err(_) => break, - Ok(ev) => event = FromDevtools(ev), + Ok(ev) => event = MixedMessage::FromDevtools(ev), }, - Ok(ev) => event = FromScript(ev), + Ok(ev) => event = MixedMessage::FromScript(ev), }, - Ok(ev) => event = FromConstellation(ev), + Ok(ev) => event = MixedMessage::FromConstellation(ev), } } // Process the gathered events. for msg in sequential.into_iter() { match msg { - FromConstellation(ExitPipelineMsg(id)) => + MixedMessage::FromConstellation(ExitPipelineMsg(id)) => if self.handle_exit_pipeline_msg(id) { return false }, - FromConstellation(inner_msg) => self.handle_msg_from_constellation(inner_msg), - FromScript(inner_msg) => self.handle_msg_from_script(inner_msg), - FromDevtools(inner_msg) => self.handle_msg_from_devtools(inner_msg), + 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), } } @@ -563,9 +565,9 @@ impl ScriptTask { self.trigger_load(id, load_data), TriggerFragmentMsg(id, url) => self.trigger_fragment(id, url), - FireTimerMsg(FromWindow(id), timer_id) => + FireTimerMsg(TimerSource::FromWindow(id), timer_id) => self.handle_fire_timer_msg(id, timer_id), - FireTimerMsg(FromWorker, _) => + FireTimerMsg(TimerSource::FromWorker, _) => panic!("Worker timeouts must not be sent to script task"), NavigateMsg(direction) => self.handle_navigate_msg(direction), @@ -757,8 +759,9 @@ impl ScriptTask { } else { url.clone() }; - let document = Document::new(*window, Some(doc_url.clone()), HTMLDocument, - None, FromParser).root(); + let document = Document::new(*window, Some(doc_url.clone()), + IsHTMLDocument::HTMLDocument, None, + DocumentSource::FromParser).root(); window.init_browser_context(*document); @@ -802,17 +805,18 @@ impl ScriptTask { *page.mut_url() = Some((final_url.clone(), true)); } - (InputUrl(load_response), final_url) + (HTMLInput::InputUrl(load_response), final_url) } else { let evalstr = load_data.url.non_relative_scheme_data().unwrap(); let jsval = window.evaluate_js_with_result(evalstr); - let strval = FromJSValConvertible::from_jsval(self.get_cx(), jsval, Empty); - (InputString(strval.unwrap_or("".to_string())), doc_url) + let strval = FromJSValConvertible::from_jsval(self.get_cx(), jsval, + StringificationBehavior::Empty); + (HTMLInput::InputString(strval.unwrap_or("".to_string())), doc_url) }; parse_html(*document, parser_input, &final_url); - document.set_ready_state(DocumentReadyStateValues::Interactive); + document.set_ready_state(DocumentReadyState::Interactive); self.compositor.borrow_mut().set_ready_state(pipeline_id, PerformingLayout); // Kick off the initial reflow of the page. @@ -820,7 +824,7 @@ impl ScriptTask { { let document_js_ref = (&*document).clone(); let document_as_node = NodeCast::from_ref(document_js_ref); - document.content_changed(document_as_node, OtherNodeDamage); + document.content_changed(document_as_node, NodeDamage::OtherNodeDamage); } window.flush_layout(ReflowForDisplay, NoQuery); @@ -832,7 +836,8 @@ impl ScriptTask { // https://html.spec.whatwg.org/multipage/#the-end step 4 let event = Event::new(global::Window(*window), "DOMContentLoaded".to_string(), - DoesNotBubble, NotCancelable).root(); + EventBubbles::DoesNotBubble, + EventCancelable::NotCancelable).root(); let doctarget: JSRef<EventTarget> = EventTargetCast::from_ref(*document); let _ = doctarget.DispatchEvent(*event); @@ -841,9 +846,11 @@ impl ScriptTask { // the initial load. // https://html.spec.whatwg.org/multipage/#the-end step 7 - document.set_ready_state(DocumentReadyStateValues::Complete); + document.set_ready_state(DocumentReadyState::Complete); - let event = Event::new(global::Window(*window), "load".to_string(), DoesNotBubble, NotCancelable).root(); + let event = Event::new(global::Window(*window), "load".to_string(), + EventBubbles::DoesNotBubble, + EventCancelable::NotCancelable).root(); let wintarget: JSRef<EventTarget> = EventTargetCast::from_ref(*window); let _ = wintarget.dispatch_event_with_target(Some(doctarget), *event); @@ -913,7 +920,7 @@ impl ScriptTask { let page = get_page(&*self.page.borrow(), pipeline_id); let frame = page.frame(); let document = frame.as_ref().unwrap().document.root(); - document.content_changed(*node_to_dirty, OtherNodeDamage); + document.content_changed(*node_to_dirty, NodeDamage::OtherNodeDamage); } self.handle_reflow_event(pipeline_id); @@ -959,10 +966,10 @@ impl ScriptTask { let meta = modifiers.contains(SUPER); let is_composing = false; - let is_repeating = state == Repeated; + let is_repeating = state == KeyState::Repeated; let ev_type = match state { - Pressed | Repeated => "keydown", - Released => "keyup", + KeyState::Pressed | KeyState::Repeated => "keydown", + KeyState::Released => "keyup", }.to_string(); let props = KeyboardEvent::key_properties(key, modifiers); @@ -977,7 +984,7 @@ impl ScriptTask { let mut prevented = event.DefaultPrevented(); // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keys-cancelable-keys - if state != Released && props.is_printable() && !prevented { + if state != KeyState::Released && props.is_printable() && !prevented { // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keypress-event-order let event = KeyboardEvent::new(*window, "keypress".to_string(), true, true, Some(*window), 0, props.key.to_string(), props.code.to_string(), @@ -1001,11 +1008,11 @@ impl ScriptTask { // I'm dispatching it after the key event so the script has a chance to cancel it // https://www.w3.org/Bugs/Public/show_bug.cgi?id=27337 match key { - Key::KeySpace if !prevented && state == Released => { + Key::Space if !prevented && state == KeyState::Released => { let maybe_elem: Option<JSRef<Element>> = ElementCast::to_ref(target); maybe_elem.map(|el| el.as_maybe_activatable().map(|a| a.synthetic_click_activation(ctrl, alt, shift, meta))); } - Key::KeyEnter if !prevented && state == Released => { + Key::Enter if !prevented && state == KeyState::Released => { let maybe_elem: Option<JSRef<Element>> = ElementCast::to_ref(target); maybe_elem.map(|el| el.as_maybe_activatable().map(|a| a.implicit_submission(ctrl, alt, shift, meta))); } @@ -1116,7 +1123,8 @@ impl ScriptTask { let event = Event::new(global::Window(*window), "click".to_string(), - Bubbles, Cancelable).root(); + EventBubbles::Bubbles, + EventCancelable::Cancelable).root(); // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#trusted-events event.set_trusted(true); // https://html.spec.whatwg.org/multipage/interaction.html#run-authentic-click-activation-steps @@ -1272,7 +1280,7 @@ impl HeaderFormat for LastModified { // for document.lastModified. fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { let LastModified(ref tm) = *self; - match tm.tm_gmtoff { + match tm.tm_utcoff { 0 => tm.rfc822().fmt(f), _ => tm.to_utc().rfc822().fmt(f) } @@ -1280,5 +1288,5 @@ impl HeaderFormat for LastModified { } fn dom_last_modified(tm: &Tm) -> String { - tm.to_local().strftime("%m/%d/%Y %H:%M:%S").unwrap() + format!("{}", tm.to_local().strftime("%m/%d/%Y %H:%M:%S").unwrap()) } diff --git a/components/script/textinput.rs b/components/script/textinput.rs index ed120aae943..843838933c2 100644 --- a/components/script/textinput.rs +++ b/components/script/textinput.rs @@ -11,6 +11,7 @@ use servo_util::str::DOMString; use std::cmp::{min, max}; use std::default::Default; +use std::num::SignedInt; #[jstraceable] struct TextPoint { @@ -70,7 +71,7 @@ impl TextInput { lines: vec!(), edit_point: Default::default(), selection_begin: None, - multiline: lines == Multiple, + multiline: lines == Lines::Multiple, }; i.set_content(initial); i @@ -79,7 +80,11 @@ impl TextInput { /// Remove a character at the current editing point fn delete_char(&mut self, dir: DeleteDir) { if self.selection_begin.is_none() { - self.adjust_horizontal(if dir == Forward {1} else {-1}, true); + self.adjust_horizontal(if dir == DeleteDir::Forward { + 1 + } else { + -1 + }, true); } self.replace_selection("".to_string()); } @@ -210,10 +215,10 @@ impl TextInput { /// Deal with a newline input. fn handle_return(&mut self) -> KeyReaction { if !self.multiline { - return TriggerDefaultAction; + return KeyReaction::TriggerDefaultAction; } self.insert_char('\n'); - return DispatchInput; + return KeyReaction::DispatchInput; } /// Process a given `KeyboardEvent` and return an action for the caller to execute. @@ -222,55 +227,55 @@ impl TextInput { // printable characters have single-character key values c if c.len() == 1 => { self.insert_char(c.char_at(0)); - return DispatchInput; + return KeyReaction::DispatchInput; } "Space" => { self.insert_char(' '); - DispatchInput + KeyReaction::DispatchInput } "Delete" => { - self.delete_char(Forward); - DispatchInput + self.delete_char(DeleteDir::Forward); + KeyReaction::DispatchInput } "Backspace" => { - self.delete_char(Backward); - DispatchInput + self.delete_char(DeleteDir::Backward); + KeyReaction::DispatchInput } "ArrowLeft" => { self.adjust_horizontal(-1, event.ShiftKey()); - Nothing + KeyReaction::Nothing } "ArrowRight" => { self.adjust_horizontal(1, event.ShiftKey()); - Nothing + KeyReaction::Nothing } "ArrowUp" => { self.adjust_vertical(-1, event.ShiftKey()); - Nothing + KeyReaction::Nothing } "ArrowDown" => { self.adjust_vertical(1, event.ShiftKey()); - Nothing + KeyReaction::Nothing } "Enter" => self.handle_return(), "Home" => { self.edit_point.index = 0; - Nothing + KeyReaction::Nothing } "End" => { self.edit_point.index = self.current_line_length(); - Nothing + KeyReaction::Nothing } "PageUp" => { self.adjust_vertical(-28, event.ShiftKey()); - Nothing + KeyReaction::Nothing } "PageDown" => { self.adjust_vertical(28, event.ShiftKey()); - Nothing + KeyReaction::Nothing } - "Tab" => TriggerDefaultAction, - _ => Nothing, + "Tab" => KeyReaction::TriggerDefaultAction, + _ => KeyReaction::Nothing, } } diff --git a/components/script/timers.rs b/components/script/timers.rs index 8d802731487..1b642a85ca5 100644 --- a/components/script/timers.rs +++ b/components/script/timers.rs @@ -3,13 +3,13 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; -use dom::bindings::callback::ReportExceptions; +use dom::bindings::callback::ExceptionHandling::ReportExceptions; use dom::bindings::codegen::Bindings::FunctionBinding::Function; use dom::bindings::js::JSRef; use dom::bindings::utils::Reflectable; -use script_task::{FireTimerMsg, ScriptChan}; -use script_task::{TimerSource, FromWindow, FromWorker}; +use script_task::{ScriptChan, TimerSource}; +use script_task::ScriptMsg::FireTimerMsg; use servo_util::task::spawn_named; @@ -112,10 +112,10 @@ impl TimerManager { let tm = Timer::new().unwrap(); let (cancel_chan, cancel_port) = channel(); let spawn_name = match source { - FromWindow(_) if is_interval == IsInterval::Interval => "Window:SetInterval", - FromWorker if is_interval == IsInterval::Interval => "Worker:SetInterval", - FromWindow(_) => "Window:SetTimeout", - FromWorker => "Worker:SetTimeout", + TimerSource::FromWindow(_) if is_interval == IsInterval::Interval => "Window:SetInterval", + TimerSource::FromWorker if is_interval == IsInterval::Interval => "Worker:SetInterval", + TimerSource::FromWindow(_) => "Window:SetTimeout", + TimerSource::FromWorker => "Worker:SetTimeout", }; spawn_named(spawn_name, proc() { let mut tm = tm; diff --git a/components/servo/Cargo.lock b/components/servo/Cargo.lock index b0ee31419b0..bca176f29cb 100644 --- a/components/servo/Cargo.lock +++ b/components/servo/Cargo.lock @@ -10,6 +10,7 @@ dependencies = [ "msg 0.0.1", "net 0.0.1", "script 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", "util 0.0.1", ] @@ -17,7 +18,7 @@ dependencies = [ [[package]] name = "android_glue" version = "0.0.1" -source = "git+https://github.com/tomaka/android-rs-glue#cac0adb90bc576758f1ebf3b5e567961b1605c1f" +source = "git+https://github.com/servo/android-rs-glue?ref=servo#de9f604bfc71e07f4e968d5dd393de5442dbb2c8" dependencies = [ "compile_msg 0.1.1 (git+https://github.com/huonw/compile_msg)", ] @@ -25,7 +26,7 @@ dependencies = [ [[package]] name = "azure" version = "0.1.0" -source = "git+https://github.com/servo/rust-azure#e8323588209b47a07b67f61812c75dfeb2ad6851" +source = "git+https://github.com/servo/rust-azure#fe95551ca22f2a75b0dd690a72841df39b33885d" dependencies = [ "core_foundation 0.1.0 (git+https://github.com/servo/rust-core-foundation)", "core_graphics 0.1.0 (git+https://github.com/servo/rust-core-graphics)", @@ -63,7 +64,7 @@ source = "git+https://github.com/servo/rust-cocoa#19d6f6977dcedbf29000b65d83df66 [[package]] name = "compile_msg" version = "0.1.1" -source = "git+https://github.com/huonw/compile_msg#f526abe54b49642bc1e969e6c2af1411798b6776" +source = "git+https://github.com/huonw/compile_msg#32a98df61c600ca5487487d2b5e8c55f4bc7a91a" [[package]] name = "compositing" @@ -83,6 +84,7 @@ dependencies = [ "net 0.0.1", "png 0.1.0 (git+https://github.com/servo/rust-png)", "script_traits 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", "util 0.0.1", ] @@ -90,16 +92,17 @@ dependencies = [ [[package]] name = "cookie" version = "0.0.1" -source = "git+https://github.com/servo/cookie-rs#30520767a95b92e39265aaf6822db515b2418f1d" +source = "git+https://github.com/servo/cookie-rs#f82090b19c2738b90528167ef873d8eac0353294" dependencies = [ - "openssl 0.0.1 (git+https://github.com/servo/rust-openssl)", + "openssl 0.0.2 (git+https://github.com/servo/rust-openssl)", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", ] [[package]] name = "core_foundation" version = "0.1.0" -source = "git+https://github.com/servo/rust-core-foundation#6fa0b908f3912e20d081193e83bf5a9aa958fb83" +source = "git+https://github.com/servo/rust-core-foundation#d2dbe4fb6f6892521a37735cd7a97098d1b64808" [[package]] name = "core_graphics" @@ -121,9 +124,9 @@ dependencies = [ [[package]] name = "cssparser" version = "0.1.0" -source = "git+https://github.com/servo/rust-cssparser#3f98f1308b769b5d61efc6c133ac520df2b074ac" +source = "git+https://github.com/servo/rust-cssparser#97d8c3b20a240881573748d4eadcda610bfb888c" dependencies = [ - "encoding 0.2.0 (git+https://github.com/lifthrasiir/rust-encoding)", + "encoding 0.2.3 (git+https://github.com/lifthrasiir/rust-encoding)", ] [[package]] @@ -149,8 +152,8 @@ source = "git+https://github.com/servo/rust-egl#88f2a13812ddbce2bf2317221663a61c [[package]] name = "encoding" -version = "0.2.0" -source = "git+https://github.com/lifthrasiir/rust-encoding#a06637cc6d0da37c12c68661e2ee9ca1999764a4" +version = "0.2.3" +source = "git+https://github.com/lifthrasiir/rust-encoding#15ac0ded3ca592c31ded5b9ff6f9fe2fa4b73fc4" dependencies = [ "encoding-index-japanese 1.0.20140915 (git+https://github.com/lifthrasiir/rust-encoding)", "encoding-index-korean 1.0.20140915 (git+https://github.com/lifthrasiir/rust-encoding)", @@ -162,27 +165,47 @@ dependencies = [ [[package]] name = "encoding-index-japanese" version = "1.0.20140915" -source = "git+https://github.com/lifthrasiir/rust-encoding#a06637cc6d0da37c12c68661e2ee9ca1999764a4" +source = "git+https://github.com/lifthrasiir/rust-encoding#15ac0ded3ca592c31ded5b9ff6f9fe2fa4b73fc4" +dependencies = [ + "encoding_index_tests 0.1.0 (git+https://github.com/lifthrasiir/rust-encoding)", +] [[package]] name = "encoding-index-korean" version = "1.0.20140915" -source = "git+https://github.com/lifthrasiir/rust-encoding#a06637cc6d0da37c12c68661e2ee9ca1999764a4" +source = "git+https://github.com/lifthrasiir/rust-encoding#15ac0ded3ca592c31ded5b9ff6f9fe2fa4b73fc4" +dependencies = [ + "encoding_index_tests 0.1.0 (git+https://github.com/lifthrasiir/rust-encoding)", +] [[package]] name = "encoding-index-simpchinese" version = "1.0.20140915" -source = "git+https://github.com/lifthrasiir/rust-encoding#a06637cc6d0da37c12c68661e2ee9ca1999764a4" +source = "git+https://github.com/lifthrasiir/rust-encoding#15ac0ded3ca592c31ded5b9ff6f9fe2fa4b73fc4" +dependencies = [ + "encoding_index_tests 0.1.0 (git+https://github.com/lifthrasiir/rust-encoding)", +] [[package]] name = "encoding-index-singlebyte" version = "1.0.20140915" -source = "git+https://github.com/lifthrasiir/rust-encoding#a06637cc6d0da37c12c68661e2ee9ca1999764a4" +source = "git+https://github.com/lifthrasiir/rust-encoding#15ac0ded3ca592c31ded5b9ff6f9fe2fa4b73fc4" +dependencies = [ + "encoding_index_tests 0.1.0 (git+https://github.com/lifthrasiir/rust-encoding)", +] [[package]] name = "encoding-index-tradchinese" version = "1.0.20140915" -source = "git+https://github.com/lifthrasiir/rust-encoding#a06637cc6d0da37c12c68661e2ee9ca1999764a4" +source = "git+https://github.com/lifthrasiir/rust-encoding#15ac0ded3ca592c31ded5b9ff6f9fe2fa4b73fc4" +dependencies = [ + "encoding_index_tests 0.1.0 (git+https://github.com/lifthrasiir/rust-encoding)", +] + +[[package]] +name = "encoding_index_tests" +version = "0.1.0" +source = "git+https://github.com/lifthrasiir/rust-encoding#15ac0ded3ca592c31ded5b9ff6f9fe2fa4b73fc4" [[package]] name = "expat-sys" @@ -217,6 +240,11 @@ version = "2.4.11" source = "git+https://github.com/servo/libfreetype2#f5c49c0da1d5bc6b206c4176344012ac37524243" [[package]] +name = "gcc" +version = "0.0.2" +source = "git+https://github.com/alexcrichton/gcc-rs#903e8f8a2e3766ad3d514404d452dbaa1d3b2d79" + +[[package]] name = "geom" version = "0.1.0" source = "git+https://github.com/servo/rust-geom#95e746133b4a35b53eb259304668b63ee8de42b8" @@ -241,6 +269,7 @@ dependencies = [ "script_traits 0.0.1", "stb_image 0.1.0 (git+https://github.com/servo/rust-stb-image)", "style 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", "util 0.0.1", ] @@ -248,16 +277,16 @@ dependencies = [ [[package]] name = "gl_common" version = "0.0.1" -source = "git+https://github.com/bjz/gl-rs.git#79cd3b3f9f19aa0e39f6af572fc8673a6d9760bc" +source = "git+https://github.com/bjz/gl-rs.git#c76c23fc9a0dae824b45550d4b823cdb726f242d" [[package]] name = "gl_generator" version = "0.0.1" -source = "git+https://github.com/bjz/gl-rs.git#79cd3b3f9f19aa0e39f6af572fc8673a6d9760bc" +source = "git+https://github.com/bjz/gl-rs.git#c76c23fc9a0dae824b45550d4b823cdb726f242d" dependencies = [ "gl_common 0.0.1 (git+https://github.com/bjz/gl-rs.git)", - "khronos_api 0.0.1 (git+https://github.com/bjz/gl-rs.git)", - "rust-xml 0.1.0 (git+https://github.com/netvl/rust-xml)", + "khronos_api 0.0.2 (git+https://github.com/bjz/gl-rs.git)", + "rust-xml 0.1.2-pre (git+https://github.com/netvl/rust-xml)", ] [[package]] @@ -271,10 +300,10 @@ dependencies = [ [[package]] name = "glfw" version = "0.0.1" -source = "git+https://github.com/servo/glfw-rs?ref=servo#46f82b46589720f202ab2d4a99e4f4fd48df6469" +source = "git+https://github.com/servo/glfw-rs?ref=servo#1b05fdc7eab45e1d462758ab991065ee78593b7f" dependencies = [ "glfw-sys 3.0.4 (git+https://github.com/servo/glfw?ref=cargo-3.0.4)", - "semver 0.1.0 (git+https://github.com/rust-lang/semver)", + "semver 0.1.3 (git+https://github.com/rust-lang/semver)", ] [[package]] @@ -293,20 +322,21 @@ dependencies = [ "glfw 0.0.1 (git+https://github.com/servo/glfw-rs?ref=servo)", "layers 0.1.0 (git+https://github.com/servo/rust-layers)", "msg 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "util 0.0.1", ] [[package]] name = "glutin" version = "0.0.2" -source = "git+https://github.com/tomaka/glutin#749c47d8c20af078b06e8506b68a54e3799c1a8b" +source = "git+https://github.com/servo/glutin?ref=servo#b86cbe5c61a943683309384fc9d7e7e97d58e290" dependencies = [ - "android_glue 0.0.1 (git+https://github.com/tomaka/android-rs-glue)", + "android_glue 0.0.1 (git+https://github.com/servo/android-rs-glue?ref=servo)", "cocoa 0.1.1 (git+https://github.com/servo/rust-cocoa)", - "compile_msg 0.1.1 (git+https://github.com/huonw/compile_msg)", "core_graphics 0.1.0 (git+https://github.com/servo/rust-core-graphics)", "gl_common 0.0.1 (git+https://github.com/bjz/gl-rs.git)", "gl_generator 0.0.1 (git+https://github.com/bjz/gl-rs.git)", + "winapi 0.0.1 (git+https://github.com/retep998/winapi-rs)", ] [[package]] @@ -317,9 +347,10 @@ dependencies = [ "compositing 0.0.1", "geom 0.1.0 (git+https://github.com/servo/rust-geom)", "gleam 0.0.1 (git+https://github.com/servo/gleam)", - "glutin 0.0.2 (git+https://github.com/tomaka/glutin)", + "glutin 0.0.2 (git+https://github.com/servo/glutin?ref=servo)", "layers 0.1.0 (git+https://github.com/servo/rust-layers)", "msg 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "util 0.0.1", ] @@ -339,30 +370,30 @@ source = "git+https://github.com/servo/rust-harfbuzz#8aab215463214647b7a81f66011 [[package]] name = "html5ever" version = "0.0.0" -source = "git+https://github.com/servo/html5ever?ref=servo#87c7e8b710391338b2463652be835f498923653c" +source = "git+https://github.com/servo/html5ever#e6f8d83de9fffe63a825d95d957ba6bcbc3e1632" dependencies = [ - "html5ever_macros 0.0.0 (git+https://github.com/servo/html5ever?ref=servo)", + "html5ever_macros 0.0.0 (git+https://github.com/servo/html5ever)", "phf 0.0.0 (git+https://github.com/sfackler/rust-phf)", "phf_mac 0.0.0 (git+https://github.com/sfackler/rust-phf)", "string_cache 0.0.0 (git+https://github.com/servo/string-cache)", "string_cache_macros 0.0.0 (git+https://github.com/servo/string-cache)", + "time 0.1.0 (git+https://github.com/rust-lang/time)", ] [[package]] name = "html5ever_macros" version = "0.0.0" -source = "git+https://github.com/servo/html5ever?ref=servo#87c7e8b710391338b2463652be835f498923653c" +source = "git+https://github.com/servo/html5ever#e6f8d83de9fffe63a825d95d957ba6bcbc3e1632" [[package]] name = "hyper" version = "0.0.1" -source = "git+https://github.com/servo/hyper?ref=servo#dd9d1830f35f7a8371b1b3bcb2d3e9cf2763f33f" +source = "git+https://github.com/servo/hyper?ref=servo#9c70c58e65ec80446fdb6e338f1060589b562f8c" dependencies = [ "cookie 0.0.1 (git+https://github.com/servo/cookie-rs)", "mime 0.0.1 (git+https://github.com/hyperium/mime.rs)", - "move-acceptor 0.0.1 (git+https://github.com/reem/rust-move-acceptor)", - "openssl 0.0.1 (git+https://github.com/servo/rust-openssl)", - "typeable 0.0.3 (git+https://github.com/reem/rust-typeable)", + "openssl 0.0.2 (git+https://github.com/servo/rust-openssl)", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "unsafe-any 0.1.0 (git+https://github.com/reem/rust-unsafe-any)", "url 0.1.0 (git+https://github.com/servo/rust-url)", ] @@ -381,20 +412,20 @@ dependencies = [ [[package]] name = "js" version = "0.1.0" -source = "git+https://github.com/servo/rust-mozjs#7563bbd5abf12a1f0d01661c525b1f2491f783a9" +source = "git+https://github.com/servo/rust-mozjs#e04e7307a3e52f46bc9ba3d5682188285110bc67" dependencies = [ "mozjs-sys 0.0.0 (git+https://github.com/servo/mozjs)", ] [[package]] name = "khronos_api" -version = "0.0.1" -source = "git+https://github.com/bjz/gl-rs.git#79cd3b3f9f19aa0e39f6af572fc8673a6d9760bc" +version = "0.0.2" +source = "git+https://github.com/bjz/gl-rs.git#c76c23fc9a0dae824b45550d4b823cdb726f242d" [[package]] name = "layers" version = "0.1.0" -source = "git+https://github.com/servo/rust-layers#63d1093f2a01a6fb9599ea6d932aadf79598451f" +source = "git+https://github.com/servo/rust-layers#5fbdc521b82296e325d2df13fce8026c727c01d2" dependencies = [ "cgl 0.0.1 (git+https://github.com/servo/rust-cgl)", "core_foundation 0.1.0 (git+https://github.com/servo/rust-core-foundation)", @@ -411,7 +442,7 @@ name = "layout" version = "0.0.1" dependencies = [ "cssparser 0.1.0 (git+https://github.com/servo/rust-cssparser)", - "encoding 0.2.0 (git+https://github.com/lifthrasiir/rust-encoding)", + "encoding 0.2.3 (git+https://github.com/lifthrasiir/rust-encoding)", "geom 0.1.0 (git+https://github.com/servo/rust-geom)", "gfx 0.0.1", "layout_traits 0.0.1", @@ -444,8 +475,8 @@ source = "git+https://github.com/Kimundi/lazy-static.rs#62976cb611c5396e11315ae6 [[package]] name = "libressl-pnacl-sys" -version = "2.0.2" -source = "git+https://github.com/DiamondLovesYou/libressl-pnacl-sys.git#8e9349e0280b069bfab247a2202cd10b8beae154" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "pnacl-build-helper 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -453,12 +484,7 @@ dependencies = [ [[package]] name = "mime" version = "0.0.1" -source = "git+https://github.com/hyperium/mime.rs#5264e04655974f85c8d6581395cc24597266c653" - -[[package]] -name = "move-acceptor" -version = "0.0.1" -source = "git+https://github.com/reem/rust-move-acceptor#25c5c33a83f605fdd0f3d37d2589e2b0b4e6cbd1" +source = "git+https://github.com/hyperium/mime.rs#7898f1c29c7f5d35d0c3c7aed37ebcfc95a40873" [[package]] name = "mozjs-sys" @@ -487,31 +513,32 @@ dependencies = [ "hyper 0.0.1 (git+https://github.com/servo/hyper?ref=servo)", "png 0.1.0 (git+https://github.com/servo/rust-png)", "stb_image 0.1.0 (git+https://github.com/servo/rust-stb-image)", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", "util 0.0.1", ] [[package]] name = "openssl" -version = "0.0.1" -source = "git+https://github.com/servo/rust-openssl#82b520100532dba9a4cdd4588709eaedb37c7a77" +version = "0.0.2" +source = "git+https://github.com/servo/rust-openssl#19d9b53a86d602e16ab2274813a517cfaa4a2512" dependencies = [ - "libressl-pnacl-sys 2.0.2 (git+https://github.com/DiamondLovesYou/libressl-pnacl-sys.git)", - "openssl-sys 0.0.1 (git+https://github.com/servo/rust-openssl)", + "libressl-pnacl-sys 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "openssl-sys 0.0.2 (git+https://github.com/servo/rust-openssl)", ] [[package]] name = "openssl-sys" -version = "0.0.1" -source = "git+https://github.com/servo/rust-openssl#82b520100532dba9a4cdd4588709eaedb37c7a77" +version = "0.0.2" +source = "git+https://github.com/servo/rust-openssl#19d9b53a86d602e16ab2274813a517cfaa4a2512" dependencies = [ - "pkg-config 0.1.0 (git+https://github.com/alexcrichton/pkg-config-rs)", + "pkg-config 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "phf" version = "0.0.0" -source = "git+https://github.com/sfackler/rust-phf#18a5ecc028055c3dbd650cc5a064b6fb033d82ef" +source = "git+https://github.com/sfackler/rust-phf#aa3e2d0aedea4d55c2e4cea1bdf6e89418dc1206" dependencies = [ "xxhash 0.0.1 (git+https://github.com/Jurily/rust-xxhash)", ] @@ -519,15 +546,16 @@ dependencies = [ [[package]] name = "phf_mac" version = "0.0.0" -source = "git+https://github.com/sfackler/rust-phf#18a5ecc028055c3dbd650cc5a064b6fb033d82ef" +source = "git+https://github.com/sfackler/rust-phf#aa3e2d0aedea4d55c2e4cea1bdf6e89418dc1206" dependencies = [ + "time 0.1.0 (git+https://github.com/rust-lang/time)", "xxhash 0.0.1 (git+https://github.com/Jurily/rust-xxhash)", ] [[package]] name = "pkg-config" -version = "0.1.0" -source = "git+https://github.com/alexcrichton/pkg-config-rs#9b3b44a2e1a8ccc70c3f701aeb5154ad79e665e9" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "plugins" @@ -541,7 +569,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "png" version = "0.1.0" -source = "git+https://github.com/servo/rust-png#b0b4acde0080dd475dee93615276bfc19207a21e" +source = "git+https://github.com/servo/rust-png#f060a2d9484a150de286f930eb80f9f3bff3ea38" dependencies = [ "png-sys 1.6.3 (git+https://github.com/servo/libpng?ref=servo)", ] @@ -553,8 +581,8 @@ source = "git+https://github.com/servo/libpng?ref=servo#d01f32b4eb86904695efe7fc [[package]] name = "rust-xml" -version = "0.1.0" -source = "git+https://github.com/netvl/rust-xml#d6c57380a300b94f7e7881979dbe5459dbe4ca06" +version = "0.1.2-pre" +source = "git+https://github.com/netvl/rust-xml#2d9df3267aeaa4d442e1e19a4dfed733cb1397ed" [[package]] name = "script" @@ -563,10 +591,10 @@ dependencies = [ "canvas 0.0.1", "cssparser 0.1.0 (git+https://github.com/servo/rust-cssparser)", "devtools_traits 0.0.1", - "encoding 0.2.0 (git+https://github.com/lifthrasiir/rust-encoding)", + "encoding 0.2.3 (git+https://github.com/lifthrasiir/rust-encoding)", "geom 0.1.0 (git+https://github.com/servo/rust-geom)", "gfx 0.0.1", - "html5ever 0.0.0 (git+https://github.com/servo/html5ever?ref=servo)", + "html5ever 0.0.0 (git+https://github.com/servo/html5ever)", "hyper 0.0.1 (git+https://github.com/servo/hyper?ref=servo)", "js 0.1.0 (git+https://github.com/servo/rust-mozjs)", "msg 0.0.1", @@ -576,9 +604,10 @@ dependencies = [ "string_cache 0.0.0 (git+https://github.com/servo/string-cache)", "string_cache_macros 0.0.0 (git+https://github.com/servo/string-cache)", "style 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", "util 0.0.1", - "uuid 0.0.1 (git+https://github.com/rust-lang/uuid)", + "uuid 0.0.2 (git+https://github.com/rust-lang/uuid)", ] [[package]] @@ -595,8 +624,8 @@ dependencies = [ [[package]] name = "semver" -version = "0.1.0" -source = "git+https://github.com/rust-lang/semver#7dca047a9cd40e929a4545b37a1917daff82f156" +version = "0.1.3" +source = "git+https://github.com/rust-lang/semver#29212953f839337c672d185dde74e14b5dfb1f46" [[package]] name = "skia-sys" @@ -610,12 +639,12 @@ dependencies = [ [[package]] name = "stb_image" version = "0.1.0" -source = "git+https://github.com/servo/rust-stb-image#74488fef4740acf287ff5dc248d65cc74033467a" +source = "git+https://github.com/servo/rust-stb-image#97d7e440e80e41a304647363c322eab68e3700aa" [[package]] name = "string_cache" version = "0.0.0" -source = "git+https://github.com/servo/string-cache#ae950525434b642eff5f4904f5e0c76cd6ea99b9" +source = "git+https://github.com/servo/string-cache#a18a432fd274e816fc41876536f70e5380abb677" dependencies = [ "lazy_static 0.1.0 (git+https://github.com/Kimundi/lazy-static.rs)", "phf 0.0.0 (git+https://github.com/sfackler/rust-phf)", @@ -627,7 +656,7 @@ dependencies = [ [[package]] name = "string_cache_macros" version = "0.0.0" -source = "git+https://github.com/servo/string-cache#ae950525434b642eff5f4904f5e0c76cd6ea99b9" +source = "git+https://github.com/servo/string-cache#a18a432fd274e816fc41876536f70e5380abb677" dependencies = [ "lazy_static 0.1.0 (git+https://github.com/Kimundi/lazy-static.rs)", ] @@ -637,7 +666,7 @@ name = "style" version = "0.0.1" dependencies = [ "cssparser 0.1.0 (git+https://github.com/servo/rust-cssparser)", - "encoding 0.2.0 (git+https://github.com/lifthrasiir/rust-encoding)", + "encoding 0.2.3 (git+https://github.com/lifthrasiir/rust-encoding)", "geom 0.1.0 (git+https://github.com/servo/rust-geom)", "lazy_static 0.1.0 (git+https://github.com/Kimundi/lazy-static.rs)", "plugins 0.0.1", @@ -652,9 +681,12 @@ name = "task_info" version = "0.0.1" [[package]] -name = "typeable" -version = "0.0.3" -source = "git+https://github.com/reem/rust-typeable#db8975daaa3889871f67eea11baeaefd8e706eaf" +name = "time" +version = "0.1.0" +source = "git+https://github.com/rust-lang/time#afab521f3b91658a3ba2d3e877b7e01699733bef" +dependencies = [ + "gcc 0.0.2 (git+https://github.com/alexcrichton/gcc-rs)", +] [[package]] name = "unsafe-any" @@ -664,10 +696,7 @@ source = "git+https://github.com/reem/rust-unsafe-any#2863af363bbd83079b6773920b [[package]] name = "url" version = "0.1.0" -source = "git+https://github.com/servo/rust-url#8a61b7654ab5378b488225a1d8a9cbbbcbd38894" -dependencies = [ - "encoding 0.2.0 (git+https://github.com/lifthrasiir/rust-encoding)", -] +source = "git+https://github.com/servo/rust-url#46458f80e48c542b2f175e36e5b7d30782ca7dc5" [[package]] name = "util" @@ -679,13 +708,19 @@ dependencies = [ "string_cache 0.0.0 (git+https://github.com/servo/string-cache)", "string_cache_macros 0.0.0 (git+https://github.com/servo/string-cache)", "task_info 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", ] [[package]] name = "uuid" +version = "0.0.2" +source = "git+https://github.com/rust-lang/uuid#f5d94d0043a615756edefaf9c6041f11e52b8370" + +[[package]] +name = "winapi" version = "0.0.1" -source = "git+https://github.com/rust-lang/uuid#7c5af48d4f9074717199e05a1895f42b9fb1c1f0" +source = "git+https://github.com/retep998/winapi-rs#80b6574a8bad8fc0a1f19c788b27a459bab26c83" [[package]] name = "xlib" @@ -695,5 +730,5 @@ source = "git+https://github.com/servo/rust-xlib#58ec3847b592aeabdcfeb6a2d02033d [[package]] name = "xxhash" version = "0.0.1" -source = "git+https://github.com/Jurily/rust-xxhash#7e4174e780af0cfb29a5e53ede0b987adca16396" +source = "git+https://github.com/Jurily/rust-xxhash#64f8d02314735f511cb4272563d0f703d575c159" diff --git a/components/servo/Cargo.toml b/components/servo/Cargo.toml index db5e2b692f4..52bdb2b6f31 100644 --- a/components/servo/Cargo.toml +++ b/components/servo/Cargo.toml @@ -61,3 +61,6 @@ optional = true [dependencies.url] git = "https://github.com/servo/rust-url" + +[dependencies.time] +git = "https://github.com/rust-lang/time" diff --git a/components/servo/lib.rs b/components/servo/lib.rs index 9e5d4be9467..58f3bb9f2d2 100644 --- a/components/servo/lib.rs +++ b/components/servo/lib.rs @@ -117,7 +117,7 @@ impl<Window> Browser<Window> where Window: WindowMethods + 'static { for url in opts.urls.iter() { let url = match url::Url::parse(url.as_slice()) { Ok(url) => url, - Err(url::RelativeUrlWithoutBase) + Err(url::ParseError::RelativeUrlWithoutBase) => url::Url::from_file_path(&cwd.join(url.as_slice())).unwrap(), Err(_) => panic!("URL parsing failed"), }; diff --git a/components/servo/main.rs b/components/servo/main.rs index 01cd4fbc591..edfd76f2de8 100644 --- a/components/servo/main.rs +++ b/components/servo/main.rs @@ -42,9 +42,7 @@ use servo_util::rtinstrument; #[cfg(not(test))] use servo::Browser; #[cfg(not(test))] -use compositing::windowing::{IdleWindowEvent, InitializeCompositingWindowEvent, ResizeWindowEvent}; -#[cfg(not(test))] -use compositing::windowing::{WindowEvent}; +use compositing::windowing::WindowEvent; #[cfg(not(any(test,target_os="android")))] use std::os; @@ -135,11 +133,11 @@ fn main() { } } - browser.browser.handle_event(InitializeCompositingWindowEvent); + browser.browser.handle_event(WindowEvent::InitializeCompositing); loop { let should_continue = match window { - None => browser.browser.handle_event(IdleWindowEvent), + None => browser.browser.handle_event(WindowEvent::Idle), Some(ref window) => { let event = window.wait_events(); browser.browser.handle_event(event) @@ -171,7 +169,7 @@ fn main() { impl app::NestedEventLoopListener for BrowserWrapper { fn handle_event_from_nested_event_loop(&mut self, event: WindowEvent) -> bool { let is_resize = match event { - ResizeWindowEvent(..) => true, + WindowEvent::Resize(..) => true, _ => false, }; if !self.browser.handle_event(event) { diff --git a/components/style/font_face.rs b/components/style/font_face.rs index ca9110d0603..2519b30c32b 100644 --- a/components/style/font_face.rs +++ b/components/style/font_face.rs @@ -8,8 +8,8 @@ use errors::{ErrorLoggerIterator, log_css_error}; use std::ascii::AsciiExt; use parsing_utils::{BufferedIter, ParserIter, parse_slice_comma_separated}; use properties::longhands::font_family::parse_one_family; -use properties::computed_values::font_family::FamilyName; -use stylesheets::{CSSRule, CSSFontFaceRule, CSSStyleRule, CSSMediaRule}; +use properties::computed_values::font_family::FontFamily::FamilyName; +use stylesheets::CSSRule; use media_queries::Device; use url::{Url, UrlParser}; @@ -18,11 +18,11 @@ pub fn iter_font_face_rules_inner(rules: &[CSSRule], device: &Device, callback: |family: &str, source: &Source|) { for rule in rules.iter() { match *rule { - CSSStyleRule(_) => {}, - CSSMediaRule(ref rule) => if rule.media_queries.evaluate(device) { + CSSRule::Style(_) => {}, + CSSRule::Media(ref rule) => if rule.media_queries.evaluate(device) { iter_font_face_rules_inner(rule.rules.as_slice(), device, |f, s| callback(f, s)) }, - CSSFontFaceRule(ref rule) => { + CSSRule::FontFace(ref rule) => { for source in rule.sources.iter() { callback(rule.family.as_slice(), source) } @@ -33,8 +33,8 @@ pub fn iter_font_face_rules_inner(rules: &[CSSRule], device: &Device, #[deriving(Clone)] pub enum Source { - UrlSource_(UrlSource), - LocalSource(String), + Url(UrlSource), + Local(String), } #[deriving(Clone)] @@ -67,9 +67,9 @@ pub fn parse_font_face_rule(rule: AtRule, parent_rules: &mut Vec<CSSRule>, base_ for item in ErrorLoggerIterator(parse_declaration_list(block.into_iter())) { match item { - DeclAtRule(rule) => log_css_error( + DeclarationListItem::AtRule(rule) => log_css_error( rule.location, format!("Unsupported at-rule in declaration list: @{:s}", rule.name).as_slice()), - Declaration_(Declaration{ location, name, value, important }) => { + DeclarationListItem::Declaration(Declaration{ location, name, value, important }) => { if important { log_css_error(location, "!important is not allowed on @font-face descriptors"); continue @@ -102,7 +102,7 @@ pub fn parse_font_face_rule(rule: AtRule, parent_rules: &mut Vec<CSSRule>, base_ } match (maybe_family, maybe_sources) { - (Some(family), Some(sources)) => parent_rules.push(CSSFontFaceRule(FontFaceRule { + (Some(family), Some(sources)) => parent_rules.push(CSSRule::FontFace(FontFaceRule { family: family, sources: sources, })), @@ -124,7 +124,7 @@ fn parse_one_src(iter: ParserIter, base_url: &Url) -> Result<Source, ()> { if name.as_slice().eq_ignore_ascii_case("local") { let iter = &mut BufferedIter::new(arguments.as_slice().skip_whitespace()); match parse_one_family(iter) { - Ok(FamilyName(name)) => return Ok(LocalSource(name)), + Ok(FamilyName(name)) => return Ok(Source::Local(name)), _ => return Err(()) } } @@ -148,7 +148,7 @@ fn parse_one_src(iter: ParserIter, base_url: &Url) -> Result<Source, ()> { None => vec![], }; - Ok(UrlSource_(UrlSource { + Ok(Source::Url(UrlSource { url: url, format_hints: format_hints, })) diff --git a/components/style/legacy.rs b/components/style/legacy.rs index 09da76d1694..504471d7b04 100644 --- a/components/style/legacy.rs +++ b/components/style/legacy.rs @@ -5,29 +5,32 @@ //! Legacy presentational attributes defined in the HTML5 specification: `<td width>`, //! `<input size>`, and so forth. +use self::UnsignedIntegerAttribute::*; +use self::SimpleColorAttribute::*; + use node::{TElement, TElementAttributes, TNode}; -use properties::{BackgroundColorDeclaration, BorderBottomWidthDeclaration, CSSFloat}; -use properties::{BorderLeftWidthDeclaration, BorderRightWidthDeclaration, HeightDeclaration}; -use properties::{BorderTopWidthDeclaration, SpecifiedValue, WidthDeclaration, specified}; +use properties::DeclaredValue::SpecifiedValue; +use properties::PropertyDeclaration::*; +use properties::{CSSFloat, specified}; use selector_matching::{DeclarationBlock, Stylist}; -use cssparser::RGBAColor; +use cssparser::Color; use servo_util::geometry::Au; use servo_util::smallvec::VecLike; -use servo_util::str::{AutoLpa, LengthLpa, PercentageLpa}; +use servo_util::str::LengthOrPercentageOrAuto; /// Legacy presentational attributes that take a length as defined in HTML5 § 2.4.4.4. pub enum LengthAttribute { /// `<td width>` - WidthLengthAttribute, + Width, } /// Legacy presentational attributes that take an integer as defined in HTML5 § 2.4.4.2. pub enum IntegerAttribute { /// `<input size>` - SizeIntegerAttribute, - ColsIntegerAttribute, - RowsIntegerAttribute, + Size, + Cols, + Rows, } /// Legacy presentational attributes that take a nonnegative integer as defined in HTML5 § 2.4.4.2. @@ -100,16 +103,16 @@ impl PresentationalHintSynthesis for Stylist { let element = node.as_element(); match element.get_local_name() { name if *name == atom!("td") => { - match element.get_length_attribute(WidthLengthAttribute) { - AutoLpa => {} - PercentageLpa(percentage) => { - let width_value = specified::LPA_Percentage(percentage); + match element.get_length_attribute(LengthAttribute::Width) { + LengthOrPercentageOrAuto::Auto => {} + LengthOrPercentageOrAuto::Percentage(percentage) => { + let width_value = specified::LengthOrPercentageOrAuto::Percentage(percentage); matching_rules_list.vec_push(DeclarationBlock::from_declaration( WidthDeclaration(SpecifiedValue(width_value)))); *shareable = false } - LengthLpa(length) => { - let width_value = specified::LPA_Length(specified::Au_(length)); + LengthOrPercentageOrAuto::Length(length) => { + let width_value = specified::LengthOrPercentageOrAuto::Length(specified::Length::Au(length)); matching_rules_list.vec_push(DeclarationBlock::from_declaration( WidthDeclaration(SpecifiedValue(width_value)))); *shareable = false @@ -142,7 +145,7 @@ impl PresentationalHintSynthesis for Stylist { shareable); } name if *name == atom!("input") => { - match element.get_integer_attribute(SizeIntegerAttribute) { + match element.get_integer_attribute(IntegerAttribute::Size) { Some(value) if value != 0 => { // Per HTML 4.01 § 17.4, this value is in characters if `type` is `text` or // `password` and in pixels otherwise. @@ -150,12 +153,12 @@ impl PresentationalHintSynthesis for Stylist { // FIXME(pcwalton): More use of atoms, please! let value = match element.get_attr(&ns!(""), &atom!("type")) { Some("text") | Some("password") => { - specified::ServoCharacterWidth(value) + specified::Length::ServoCharacterWidth(value) } - _ => specified::Au_(Au::from_px(value as int)), + _ => specified::Length::Au(Au::from_px(value as int)), }; matching_rules_list.vec_push(DeclarationBlock::from_declaration( - WidthDeclaration(SpecifiedValue(specified::LPA_Length( + WidthDeclaration(SpecifiedValue(specified::LengthOrPercentageOrAuto::Length( value))))); *shareable = false } @@ -163,29 +166,29 @@ impl PresentationalHintSynthesis for Stylist { } } name if *name == atom!("textarea") => { - match element.get_integer_attribute(ColsIntegerAttribute) { + match element.get_integer_attribute(IntegerAttribute::Cols) { Some(value) if value != 0 => { // TODO(mttr) ServoCharacterWidth uses the size math for <input type="text">, but // the math for <textarea> is a little different since we need to take // scrollbar size into consideration (but we don't have a scrollbar yet!) // // https://html.spec.whatwg.org/multipage/rendering.html#textarea-effective-width - let value = specified::ServoCharacterWidth(value); + let value = specified::Length::ServoCharacterWidth(value); matching_rules_list.vec_push(DeclarationBlock::from_declaration( - WidthDeclaration(SpecifiedValue(specified::LPA_Length( + WidthDeclaration(SpecifiedValue(specified::LengthOrPercentageOrAuto::Length( value))))); *shareable = false } Some(_) | None => {} } - match element.get_integer_attribute(RowsIntegerAttribute) { + match element.get_integer_attribute(IntegerAttribute::Rows) { Some(value) if value != 0 => { // TODO(mttr) This should take scrollbar size into consideration. // // https://html.spec.whatwg.org/multipage/rendering.html#textarea-effective-height - let value = specified::Em(value as CSSFloat); + let value = specified::Length::Em(value as CSSFloat); matching_rules_list.vec_push(DeclarationBlock::from_declaration( - HeightDeclaration(SpecifiedValue(specified::LPA_Length( + HeightDeclaration(SpecifiedValue(specified::LengthOrPercentageOrAuto::Length( value))))); *shareable = false } @@ -211,7 +214,7 @@ impl PresentationalHintSynthesis for Stylist { None => {} Some(color) => { matching_rules_list.vec_push(DeclarationBlock::from_declaration( - BackgroundColorDeclaration(SpecifiedValue(RGBAColor(color))))); + BackgroundColorDeclaration(SpecifiedValue(Color::RGBA(color))))); *shareable = false } } @@ -229,7 +232,7 @@ impl PresentationalHintSynthesis for Stylist { match element.get_unsigned_integer_attribute(BorderUnsignedIntegerAttribute) { None => {} Some(length) => { - let width_value = specified::Au_(Au::from_px(length as int)); + let width_value = specified::Length::Au(Au::from_px(length as int)); matching_rules_list.vec_push(DeclarationBlock::from_declaration( BorderTopWidthDeclaration(SpecifiedValue(width_value)))); matching_rules_list.vec_push(DeclarationBlock::from_declaration( diff --git a/components/style/lib.rs b/components/style/lib.rs index 9f016806ccc..6d256792028 100644 --- a/components/style/lib.rs +++ b/components/style/lib.rs @@ -34,12 +34,11 @@ extern crate "util" as servo_util; // Public API -pub use media_queries::{Device, Screen}; +pub use media_queries::{Device, MediaType}; pub use stylesheets::{Stylesheet, iter_font_face_rules}; -pub use selector_matching::{Stylist, StylesheetOrigin, UserAgentOrigin, AuthorOrigin, UserOrigin}; +pub use selector_matching::{Stylist, StylesheetOrigin}; pub use selector_matching::{DeclarationBlock, CommonStyleAffectingAttributes}; pub use selector_matching::{CommonStyleAffectingAttributeInfo, CommonStyleAffectingAttributeMode}; -pub use selector_matching::{AttrIsPresentMode, AttrIsEqualMode}; pub use selector_matching::{matches, matches_simple_selector, common_style_affecting_attributes}; pub use selector_matching::{rare_style_affecting_attributes}; pub use selector_matching::{RECOMMENDED_SELECTOR_BLOOM_FILTER_SIZE, SELECTOR_WHITESPACE}; @@ -47,18 +46,16 @@ pub use properties::{cascade, cascade_anonymous, computed}; pub use properties::{PropertyDeclaration, ComputedValues, computed_values, style_structs}; pub use properties::{PropertyDeclarationBlock, parse_style_attribute}; // Style attributes pub use properties::{CSSFloat, DeclaredValue, PropertyDeclarationParseResult}; -pub use properties::{Angle, AngleOrCorner, AngleAoc, CornerAoc}; -pub use properties::{Left, Right, Bottom, Top}; +pub use properties::{Angle, AngleOrCorner}; +pub use properties::{HorizontalDirection, VerticalDirection}; pub use node::{TElement, TElementAttributes, TNode}; -pub use selectors::{PseudoElement, Before, After, ParserContext, SelectorList}; -pub use selectors::{AttrSelector, NamespaceConstraint, SpecificNamespace, AnyNamespace}; -pub use selectors::{SimpleSelector, LocalNameSelector, parse_selector_list_from_str}; +pub use selectors::{PseudoElement, ParserContext, SelectorList}; +pub use selectors::{AttrSelector, NamespaceConstraint}; +pub use selectors::{SimpleSelector, parse_selector_list_from_str}; pub use cssparser::{Color, RGBA}; -pub use legacy::{BgColorSimpleColorAttribute, BorderUnsignedIntegerAttribute}; -pub use legacy::{ColSpanUnsignedIntegerAttribute, IntegerAttribute, LengthAttribute}; -pub use legacy::{SimpleColorAttribute, SizeIntegerAttribute, UnsignedIntegerAttribute}; -pub use legacy::{WidthLengthAttribute, ColsIntegerAttribute, RowsIntegerAttribute}; -pub use font_face::{Source, LocalSource, UrlSource_}; +pub use legacy::{IntegerAttribute, LengthAttribute}; +pub use legacy::{SimpleColorAttribute, UnsignedIntegerAttribute}; +pub use font_face::Source; mod stylesheets; mod errors; diff --git a/components/style/media_queries.rs b/components/style/media_queries.rs index f014be0114d..6600e9f9765 100644 --- a/components/style/media_queries.rs +++ b/components/style/media_queries.rs @@ -9,13 +9,12 @@ use cssparser::ast::*; use errors::{ErrorLoggerIterator, log_css_error}; use geom::size::TypedSize2D; use selectors::ParserContext; -use stylesheets::{CSSRule, CSSMediaRule}; +use stylesheets::{CSSRule, parse_style_rule, parse_nested_at_rule}; use namespaces::NamespaceMap; use parsing_utils::{BufferedIter, ParserIter}; use properties::common_types::*; use properties::longhands; use servo_util::geometry::ViewportPx; -use stylesheets; use url::Url; pub struct MediaRule { @@ -36,9 +35,9 @@ pub enum Range<T> { impl<T: Ord> Range<T> { fn evaluate(&self, value: T) -> bool { match *self { - Min(ref width) => { value >= *width }, - Max(ref width) => { value <= *width }, - //Eq(ref width) => { value == *width }, + Range::Min(ref width) => { value >= *width }, + Range::Max(ref width) => { value <= *width }, + //Range::Eq(ref width) => { value == *width }, } } } @@ -73,7 +72,7 @@ impl MediaQuery { #[deriving(PartialEq)] pub enum MediaQueryType { All, // Always true - MediaType_(MediaType), + MediaType(MediaType), } #[deriving(PartialEq)] @@ -113,20 +112,19 @@ pub fn parse_media_rule(context: &ParserContext, let mut rules = vec!(); for rule in ErrorLoggerIterator(parse_rule_list(block.into_iter())) { match rule { - QualifiedRule_(rule) => { - stylesheets::parse_style_rule(context, rule, &mut rules, namespaces, base_url) - } - AtRule_(rule) => { - stylesheets::parse_nested_at_rule(context, - rule.name.as_slice().to_ascii_lower().as_slice(), - rule, - &mut rules, - namespaces, - base_url) + Rule::QualifiedRule(rule) => { + parse_style_rule(context, rule, &mut rules, namespaces, base_url) } + Rule::AtRule(rule) => parse_nested_at_rule( + context, + rule.name.as_slice().to_ascii_lower().as_slice(), + rule, + &mut rules, + namespaces, + base_url), } } - parent_rules.push(CSSMediaRule(MediaRule { + parent_rules.push(CSSRule::Media(MediaRule { media_queries: media_queries, rules: rules, })) @@ -166,11 +164,11 @@ fn parse_media_query_expression(iter: ParserIter) -> Result<Expression, ()> { let expression = match variable.as_slice().to_ascii_lower().as_slice() { "min-width" => { let au = try!(parse_value_as_length(value)); - Width(Min(au)) + Expression::Width(Range::Min(au)) } "max-width" => { let au = try!(parse_value_as_length(value)); - Width(Max(au)) + Expression::Width(Range::Max(au)) } _ => return Err(()) }; @@ -190,8 +188,8 @@ fn parse_media_query(iter: ParserIter) -> Result<MediaQuery, ()> { // Check for optional 'only' or 'not' let qualifier = match iter.next() { - Some(&Ident(ref value)) if value.as_slice().to_ascii_lower().as_slice() == "only" => Some(Only), - Some(&Ident(ref value)) if value.as_slice().to_ascii_lower().as_slice() == "not" => Some(Not), + Some(&Ident(ref value)) if value.as_slice().to_ascii_lower().as_slice() == "only" => Some(Qualifier::Only), + Some(&Ident(ref value)) if value.as_slice().to_ascii_lower().as_slice() == "not" => Some(Qualifier::Not), Some(component_value) => { iter.push_back(component_value); None @@ -203,10 +201,10 @@ fn parse_media_query(iter: ParserIter) -> Result<MediaQuery, ()> { let media_type = match iter.next() { Some(&Ident(ref value)) => { match value.as_slice().to_ascii_lower().as_slice() { - "screen" => MediaType_(Screen), - "print" => MediaType_(Print), - "all" => All, - _ => MediaType_(Unknown), // Unknown media types never match + "screen" => MediaQueryType::MediaType(MediaType::Screen), + "print" => MediaQueryType::MediaType(MediaType::Print), + "all" => MediaQueryType::All, + _ => MediaQueryType::MediaType(MediaType::Unknown), // Unknown media types never match } } Some(component_value) => { @@ -220,7 +218,7 @@ fn parse_media_query(iter: ParserIter) -> Result<MediaQuery, ()> { let expression = try!(parse_media_query_expression(iter)); expressions.push(expression); - All + MediaQueryType::All } None => return Err(()), }; @@ -254,7 +252,7 @@ pub fn parse_media_query_list(input: &[ComponentValue]) -> MediaQueryList { let mut media_queries = vec!(); if iter.is_eof() { - media_queries.push(MediaQuery::new(None, All, vec!())); + media_queries.push(MediaQuery::new(None, MediaQueryType::All, vec!())); } else { loop { // Attempt to parse a media query. @@ -278,7 +276,7 @@ pub fn parse_media_query_list(input: &[ComponentValue]) -> MediaQueryList { // Otherwise, create a 'not all' media query, that will never match. let media_query = match (media_query_result, trailing_tokens) { (Ok(media_query), false) => media_query, - _ => MediaQuery::new(Some(Not), All, vec!()), + _ => MediaQuery::new(Some(Qualifier::Not), MediaQueryType::All, vec!()), }; media_queries.push(media_query); @@ -297,22 +295,22 @@ impl MediaQueryList { self.media_queries.iter().any(|mq| { // Check if media matches. Unknown media never matches. let media_match = match mq.media_type { - MediaType_(Unknown) => false, - MediaType_(media_type) => media_type == device.media_type, - All => true, + MediaQueryType::MediaType(MediaType::Unknown) => false, + MediaQueryType::MediaType(media_type) => media_type == device.media_type, + MediaQueryType::All => true, }; // Check if all conditions match (AND condition) let query_match = media_match && mq.expressions.iter().all(|expression| { match expression { - &Width(value) => value.evaluate( + &Expression::Width(value) => value.evaluate( Au::from_frac_px(device.viewport_size.to_untyped().width as f64)), } }); // Apply the logical NOT qualifier to the result match mq.qualifier { - Some(Not) => !query_match, + Some(Qualifier::Not) => !query_match, _ => query_match, } }) @@ -324,13 +322,14 @@ mod tests { use geom::size::TypedSize2D; use properties::common_types::*; use stylesheets::{iter_stylesheet_media_rules, iter_stylesheet_style_rules, Stylesheet}; - use selector_matching::AuthorOrigin; + use selector_matching::StylesheetOrigin; use super::*; use url::Url; fn test_media_rule(css: &str, callback: |&MediaQueryList, &str|) { let url = Url::parse("http://localhost").unwrap(); - let stylesheet = Stylesheet::from_str(css, url, AuthorOrigin); + let stylesheet = Stylesheet::from_str(css, url, + StylesheetOrigin::Author); let mut rule_count: int = 0; iter_stylesheet_media_rules(&stylesheet, |rule| { rule_count += 1; @@ -341,7 +340,7 @@ mod tests { fn media_query_test(device: &Device, css: &str, expected_rule_count: int) { let url = Url::parse("http://localhost").unwrap(); - let ss = Stylesheet::from_str(css, url, AuthorOrigin); + let ss = Stylesheet::from_str(css, url, StylesheetOrigin::Author); let mut rule_count: int = 0; iter_stylesheet_style_rules(&ss, device, |_| rule_count += 1); assert!(rule_count == expected_rule_count, css.to_string()); @@ -353,7 +352,7 @@ mod tests { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; assert!(q.qualifier == None, css.to_string()); - assert!(q.media_type == All, css.to_string()); + assert!(q.media_type == MediaQueryType::All, css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); } @@ -364,23 +363,23 @@ mod tests { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; assert!(q.qualifier == None, css.to_string()); - assert!(q.media_type == MediaType_(Screen), css.to_string()); + assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); test_media_rule("@media only screen { }", |list, css| { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; - assert!(q.qualifier == Some(Only), css.to_string()); - assert!(q.media_type == MediaType_(Screen), css.to_string()); + assert!(q.qualifier == Some(Qualifier::Only), css.to_string()); + assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); test_media_rule("@media not screen { }", |list, css| { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; - assert!(q.qualifier == Some(Not), css.to_string()); - assert!(q.media_type == MediaType_(Screen), css.to_string()); + assert!(q.qualifier == Some(Qualifier::Not), css.to_string()); + assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); } @@ -391,23 +390,23 @@ mod tests { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; assert!(q.qualifier == None, css.to_string()); - assert!(q.media_type == MediaType_(Print), css.to_string()); + assert!(q.media_type == MediaQueryType::MediaType(MediaType::Print), css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); test_media_rule("@media only print { }", |list, css| { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; - assert!(q.qualifier == Some(Only), css.to_string()); - assert!(q.media_type == MediaType_(Print), css.to_string()); + assert!(q.qualifier == Some(Qualifier::Only), css.to_string()); + assert!(q.media_type == MediaQueryType::MediaType(MediaType::Print), css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); test_media_rule("@media not print { }", |list, css| { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; - assert!(q.qualifier == Some(Not), css.to_string()); - assert!(q.media_type == MediaType_(Print), css.to_string()); + assert!(q.qualifier == Some(Qualifier::Not), css.to_string()); + assert!(q.media_type == MediaQueryType::MediaType(MediaType::Print), css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); } @@ -418,23 +417,23 @@ mod tests { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; assert!(q.qualifier == None, css.to_string()); - assert!(q.media_type == MediaType_(Unknown), css.to_string()); + assert!(q.media_type == MediaQueryType::MediaType(MediaType::Unknown), css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); test_media_rule("@media only glass { }", |list, css| { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; - assert!(q.qualifier == Some(Only), css.to_string()); - assert!(q.media_type == MediaType_(Unknown), css.to_string()); + assert!(q.qualifier == Some(Qualifier::Only), css.to_string()); + assert!(q.media_type == MediaQueryType::MediaType(MediaType::Unknown), css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); test_media_rule("@media not wood { }", |list, css| { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; - assert!(q.qualifier == Some(Not), css.to_string()); - assert!(q.media_type == MediaType_(Unknown), css.to_string()); + assert!(q.qualifier == Some(Qualifier::Not), css.to_string()); + assert!(q.media_type == MediaQueryType::MediaType(MediaType::Unknown), css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); } @@ -445,23 +444,23 @@ mod tests { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; assert!(q.qualifier == None, css.to_string()); - assert!(q.media_type == All, css.to_string()); + assert!(q.media_type == MediaQueryType::All, css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); test_media_rule("@media only all { }", |list, css| { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; - assert!(q.qualifier == Some(Only), css.to_string()); - assert!(q.media_type == All, css.to_string()); + assert!(q.qualifier == Some(Qualifier::Only), css.to_string()); + assert!(q.media_type == MediaQueryType::All, css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); test_media_rule("@media not all { }", |list, css| { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; - assert!(q.qualifier == Some(Not), css.to_string()); - assert!(q.media_type == All, css.to_string()); + assert!(q.qualifier == Some(Qualifier::Not), css.to_string()); + assert!(q.media_type == MediaQueryType::All, css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); } @@ -472,12 +471,12 @@ mod tests { assert!(list.media_queries.len() == 2, css.to_string()); let q0 = &list.media_queries[0]; assert!(q0.qualifier == None, css.to_string()); - assert!(q0.media_type == MediaType_(Screen), css.to_string()); + assert!(q0.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_string()); assert!(q0.expressions.len() == 0, css.to_string()); let q1 = &list.media_queries[1]; assert!(q1.qualifier == None, css.to_string()); - assert!(q1.media_type == MediaType_(Print), css.to_string()); + assert!(q1.media_type == MediaQueryType::MediaType(MediaType::Print), css.to_string()); assert!(q1.expressions.len() == 0, css.to_string()); }); } @@ -488,10 +487,10 @@ mod tests { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; assert!(q.qualifier == None, css.to_string()); - assert!(q.media_type == All, css.to_string()); + assert!(q.media_type == MediaQueryType::All, css.to_string()); assert!(q.expressions.len() == 1, css.to_string()); match q.expressions[0] { - Width(Min(w)) => assert!(w == Au::from_px(100)), + Expression::Width(Range::Min(w)) => assert!(w == Au::from_px(100)), _ => panic!("wrong expression type"), } }); @@ -500,10 +499,10 @@ mod tests { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; assert!(q.qualifier == None, css.to_string()); - assert!(q.media_type == All, css.to_string()); + assert!(q.media_type == MediaQueryType::All, css.to_string()); assert!(q.expressions.len() == 1, css.to_string()); match q.expressions[0] { - Width(Max(w)) => assert!(w == Au::from_px(43)), + Expression::Width(Range::Max(w)) => assert!(w == Au::from_px(43)), _ => panic!("wrong expression type"), } }); @@ -515,10 +514,10 @@ mod tests { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; assert!(q.qualifier == None, css.to_string()); - assert!(q.media_type == MediaType_(Screen), css.to_string()); + assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_string()); assert!(q.expressions.len() == 1, css.to_string()); match q.expressions[0] { - Width(Min(w)) => assert!(w == Au::from_px(100)), + Expression::Width(Range::Min(w)) => assert!(w == Au::from_px(100)), _ => panic!("wrong expression type"), } }); @@ -527,10 +526,10 @@ mod tests { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; assert!(q.qualifier == None, css.to_string()); - assert!(q.media_type == MediaType_(Print), css.to_string()); + assert!(q.media_type == MediaQueryType::MediaType(MediaType::Print), css.to_string()); assert!(q.expressions.len() == 1, css.to_string()); match q.expressions[0] { - Width(Max(w)) => assert!(w == Au::from_px(43)), + Expression::Width(Range::Max(w)) => assert!(w == Au::from_px(43)), _ => panic!("wrong expression type"), } }); @@ -539,10 +538,10 @@ mod tests { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; assert!(q.qualifier == None, css.to_string()); - assert!(q.media_type == MediaType_(Unknown), css.to_string()); + assert!(q.media_type == MediaQueryType::MediaType(MediaType::Unknown), css.to_string()); assert!(q.expressions.len() == 1, css.to_string()); match q.expressions[0] { - Width(Max(w)) => assert!(w == Au::from_px(52)), + Expression::Width(Range::Max(w)) => assert!(w == Au::from_px(52)), _ => panic!("wrong expression type"), } }); @@ -554,14 +553,14 @@ mod tests { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; assert!(q.qualifier == None, css.to_string()); - assert!(q.media_type == All, css.to_string()); + assert!(q.media_type == MediaQueryType::All, css.to_string()); assert!(q.expressions.len() == 2, css.to_string()); match q.expressions[0] { - Width(Min(w)) => assert!(w == Au::from_px(100)), + Expression::Width(Range::Min(w)) => assert!(w == Au::from_px(100)), _ => panic!("wrong expression type"), } match q.expressions[1] { - Width(Max(w)) => assert!(w == Au::from_px(200)), + Expression::Width(Range::Max(w)) => assert!(w == Au::from_px(200)), _ => panic!("wrong expression type"), } }); @@ -569,15 +568,15 @@ mod tests { test_media_rule("@media not screen and (min-width: 100px) and (max-width: 200px) { }", |list, css| { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; - assert!(q.qualifier == Some(Not), css.to_string()); - assert!(q.media_type == MediaType_(Screen), css.to_string()); + assert!(q.qualifier == Some(Qualifier::Not), css.to_string()); + assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_string()); assert!(q.expressions.len() == 2, css.to_string()); match q.expressions[0] { - Width(Min(w)) => assert!(w == Au::from_px(100)), + Expression::Width(Range::Min(w)) => assert!(w == Au::from_px(100)), _ => panic!("wrong expression type"), } match q.expressions[1] { - Width(Max(w)) => assert!(w == Au::from_px(200)), + Expression::Width(Range::Max(w)) => assert!(w == Au::from_px(200)), _ => panic!("wrong expression type"), } }); @@ -588,60 +587,60 @@ mod tests { test_media_rule("@media (min-width: 100blah) and (max-width: 200px) { }", |list, css| { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; - assert!(q.qualifier == Some(Not), css.to_string()); - assert!(q.media_type == All, css.to_string()); + assert!(q.qualifier == Some(Qualifier::Not), css.to_string()); + assert!(q.media_type == MediaQueryType::All, css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); test_media_rule("@media screen and (height: 200px) { }", |list, css| { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; - assert!(q.qualifier == Some(Not), css.to_string()); - assert!(q.media_type == All, css.to_string()); + assert!(q.qualifier == Some(Qualifier::Not), css.to_string()); + assert!(q.media_type == MediaQueryType::All, css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); test_media_rule("@media (min-width: 30em foo bar) {}", |list, css| { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; - assert!(q.qualifier == Some(Not), css.to_string()); - assert!(q.media_type == All, css.to_string()); + assert!(q.qualifier == Some(Qualifier::Not), css.to_string()); + assert!(q.media_type == MediaQueryType::All, css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); test_media_rule("@media not {}", |list, css| { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; - assert!(q.qualifier == Some(Not), css.to_string()); - assert!(q.media_type == All, css.to_string()); + assert!(q.qualifier == Some(Qualifier::Not), css.to_string()); + assert!(q.media_type == MediaQueryType::All, css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); test_media_rule("@media not (min-width: 300px) {}", |list, css| { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; - assert!(q.qualifier == Some(Not), css.to_string()); - assert!(q.media_type == All, css.to_string()); + assert!(q.qualifier == Some(Qualifier::Not), css.to_string()); + assert!(q.media_type == MediaQueryType::All, css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); test_media_rule("@media , {}", |list, css| { assert!(list.media_queries.len() == 1, css.to_string()); let q = &list.media_queries[0]; - assert!(q.qualifier == Some(Not), css.to_string()); - assert!(q.media_type == All, css.to_string()); + assert!(q.qualifier == Some(Qualifier::Not), css.to_string()); + assert!(q.media_type == MediaQueryType::All, css.to_string()); assert!(q.expressions.len() == 0, css.to_string()); }); test_media_rule("@media screen 4px, print {}", |list, css| { assert!(list.media_queries.len() == 2, css.to_string()); let q0 = &list.media_queries[0]; - assert!(q0.qualifier == Some(Not), css.to_string()); - assert!(q0.media_type == All, css.to_string()); + assert!(q0.qualifier == Some(Qualifier::Not), css.to_string()); + assert!(q0.media_type == MediaQueryType::All, css.to_string()); assert!(q0.expressions.len() == 0, css.to_string()); let q1 = &list.media_queries[1]; assert!(q1.qualifier == None, css.to_string()); - assert!(q1.media_type == MediaType_(Print), css.to_string()); + assert!(q1.media_type == MediaQueryType::MediaType(MediaType::Print), css.to_string()); assert!(q1.expressions.len() == 0, css.to_string()); }); @@ -649,11 +648,11 @@ mod tests { assert!(list.media_queries.len() == 2, css.to_string()); let q0 = &list.media_queries[0]; assert!(q0.qualifier == None, css.to_string()); - assert!(q0.media_type == MediaType_(Screen), css.to_string()); + assert!(q0.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_string()); assert!(q0.expressions.len() == 0, css.to_string()); let q1 = &list.media_queries[1]; - assert!(q1.qualifier == Some(Not), css.to_string()); - assert!(q1.media_type == All, css.to_string()); + assert!(q1.qualifier == Some(Qualifier::Not), css.to_string()); + assert!(q1.media_type == MediaQueryType::All, css.to_string()); assert!(q1.expressions.len() == 0, css.to_string()); }); } @@ -661,7 +660,7 @@ mod tests { #[test] fn test_matching_simple() { let device = Device { - media_type: Screen, + media_type: MediaType::Screen, viewport_size: TypedSize2D(200.0, 100.0), }; @@ -680,7 +679,7 @@ mod tests { #[test] fn test_matching_width() { let device = Device { - media_type: Screen, + media_type: MediaType::Screen, viewport_size: TypedSize2D(200.0, 100.0), }; @@ -718,7 +717,7 @@ mod tests { #[test] fn test_matching_invalid() { let device = Device { - media_type: Screen, + media_type: MediaType::Screen, viewport_size: TypedSize2D(200.0, 100.0), }; diff --git a/components/style/properties/common_types.rs b/components/style/properties/common_types.rs index 46a6a784b43..69b3576f410 100644 --- a/components/style/properties/common_types.rs +++ b/components/style/properties/common_types.rs @@ -22,7 +22,7 @@ pub mod specified { #[deriving(Clone, Show)] pub enum Length { - Au_(Au), // application units + Au(Au), // application units Em(CSSFloat), Ex(CSSFloat), Rem(CSSFloat), @@ -52,7 +52,7 @@ pub mod specified { match input { &Dimension(ref value, ref unit) if negative_ok || value.value >= 0. => Length::parse_dimension(value.value, unit.as_slice()), - &Number(ref value) if value.value == 0. => Ok(Au_(Au(0))), + &Number(ref value) if value.value == 0. => Ok(Length::Au(Au(0))), _ => Err(()) } } @@ -66,38 +66,40 @@ pub mod specified { pub fn parse_dimension(value: CSSFloat, unit: &str) -> Result<Length, ()> { match unit.to_ascii_lower().as_slice() { "px" => Ok(Length::from_px(value)), - "in" => Ok(Au_(Au((value * AU_PER_IN) as i32))), - "cm" => Ok(Au_(Au((value * AU_PER_CM) as i32))), - "mm" => Ok(Au_(Au((value * AU_PER_MM) as i32))), - "pt" => Ok(Au_(Au((value * AU_PER_PT) as i32))), - "pc" => Ok(Au_(Au((value * AU_PER_PC) as i32))), - "em" => Ok(Em(value)), - "ex" => Ok(Ex(value)), - "rem" => Ok(Rem(value)), + "in" => Ok(Length::Au(Au((value * AU_PER_IN) as i32))), + "cm" => Ok(Length::Au(Au((value * AU_PER_CM) as i32))), + "mm" => Ok(Length::Au(Au((value * AU_PER_MM) as i32))), + "pt" => Ok(Length::Au(Au((value * AU_PER_PT) as i32))), + "pc" => Ok(Length::Au(Au((value * AU_PER_PC) as i32))), + "em" => Ok(Length::Em(value)), + "ex" => Ok(Length::Ex(value)), + "rem" => Ok(Length::Rem(value)), _ => Err(()) } } #[inline] pub fn from_px(px_value: CSSFloat) -> Length { - Au_(Au((px_value * AU_PER_PX) as i32)) + Length::Au(Au((px_value * AU_PER_PX) as i32)) } } #[deriving(Clone, Show)] pub enum LengthOrPercentage { - LP_Length(Length), - LP_Percentage(CSSFloat), // [0 .. 100%] maps to [0.0 .. 1.0] + Length(Length), + Percentage(CSSFloat), // [0 .. 100%] maps to [0.0 .. 1.0] } impl LengthOrPercentage { fn parse_internal(input: &ComponentValue, negative_ok: bool) -> Result<LengthOrPercentage, ()> { match input { - &Dimension(ref value, ref unit) if negative_ok || value.value >= 0. - => Length::parse_dimension(value.value, unit.as_slice()).map(LP_Length), - &ast::Percentage(ref value) if negative_ok || value.value >= 0. - => Ok(LP_Percentage(value.value / 100.)), - &Number(ref value) if value.value == 0. => Ok(LP_Length(Au_(Au(0)))), + &Dimension(ref value, ref unit) if negative_ok || value.value >= 0. => + Length::parse_dimension(value.value, unit.as_slice()) + .map(LengthOrPercentage::Length), + &ast::Percentage(ref value) if negative_ok || value.value >= 0. => + Ok(LengthOrPercentage::Percentage(value.value / 100.)), + &Number(ref value) if value.value == 0. => + Ok(LengthOrPercentage::Length(Length::Au(Au(0)))), _ => Err(()) } } @@ -114,20 +116,22 @@ pub mod specified { #[deriving(Clone)] pub enum LengthOrPercentageOrAuto { - LPA_Length(Length), - LPA_Percentage(CSSFloat), // [0 .. 100%] maps to [0.0 .. 1.0] - LPA_Auto, + Length(Length), + Percentage(CSSFloat), // [0 .. 100%] maps to [0.0 .. 1.0] + Auto, } impl LengthOrPercentageOrAuto { fn parse_internal(input: &ComponentValue, negative_ok: bool) -> Result<LengthOrPercentageOrAuto, ()> { match input { - &Dimension(ref value, ref unit) if negative_ok || value.value >= 0. - => Length::parse_dimension(value.value, unit.as_slice()).map(LPA_Length), - &ast::Percentage(ref value) if negative_ok || value.value >= 0. - => Ok(LPA_Percentage(value.value / 100.)), - &Number(ref value) if value.value == 0. => Ok(LPA_Length(Au_(Au(0)))), - &Ident(ref value) if value.as_slice().eq_ignore_ascii_case("auto") => Ok(LPA_Auto), + &Dimension(ref value, ref unit) if negative_ok || value.value >= 0. => + Length::parse_dimension(value.value, unit.as_slice()).map(LengthOrPercentageOrAuto::Length), + &ast::Percentage(ref value) if negative_ok || value.value >= 0. => + Ok(LengthOrPercentageOrAuto::Percentage(value.value / 100.)), + &Number(ref value) if value.value == 0. => + Ok(LengthOrPercentageOrAuto::Length(Length::Au(Au(0)))), + &Ident(ref value) if value.as_slice().eq_ignore_ascii_case("auto") => + Ok(LengthOrPercentageOrAuto::Auto), _ => Err(()) } } @@ -143,20 +147,20 @@ pub mod specified { #[deriving(Clone)] pub enum LengthOrPercentageOrNone { - LPN_Length(Length), - LPN_Percentage(CSSFloat), // [0 .. 100%] maps to [0.0 .. 1.0] - LPN_None, + Length(Length), + Percentage(CSSFloat), // [0 .. 100%] maps to [0.0 .. 1.0] + None, } impl LengthOrPercentageOrNone { fn parse_internal(input: &ComponentValue, negative_ok: bool) -> Result<LengthOrPercentageOrNone, ()> { match input { &Dimension(ref value, ref unit) if negative_ok || value.value >= 0. - => Length::parse_dimension(value.value, unit.as_slice()).map(LPN_Length), + => Length::parse_dimension(value.value, unit.as_slice()).map(LengthOrPercentageOrNone::Length), &ast::Percentage(ref value) if negative_ok || value.value >= 0. - => Ok(LPN_Percentage(value.value / 100.)), - &Number(ref value) if value.value == 0. => Ok(LPN_Length(Au_(Au(0)))), - &Ident(ref value) if value.as_slice().eq_ignore_ascii_case("none") => Ok(LPN_None), + => Ok(LengthOrPercentageOrNone::Percentage(value.value / 100.)), + &Number(ref value) if value.value == 0. => Ok(LengthOrPercentageOrNone::Length(Length::Au(Au(0)))), + &Ident(ref value) if value.as_slice().eq_ignore_ascii_case("none") => Ok(LengthOrPercentageOrNone::None), _ => Err(()) } } @@ -174,27 +178,27 @@ pub mod specified { // http://dev.w3.org/csswg/css2/colors.html#propdef-background-position #[deriving(Clone)] pub enum PositionComponent { - Pos_Length(Length), - Pos_Percentage(CSSFloat), // [0 .. 100%] maps to [0.0 .. 1.0] - Pos_Center, - Pos_Left, - Pos_Right, - Pos_Top, - Pos_Bottom, + Length(Length), + Percentage(CSSFloat), // [0 .. 100%] maps to [0.0 .. 1.0] + Center, + Left, + Right, + Top, + Bottom, } impl PositionComponent { pub fn parse(input: &ComponentValue) -> Result<PositionComponent, ()> { match input { &Dimension(ref value, ref unit) => - Length::parse_dimension(value.value, unit.as_slice()).map(Pos_Length), - &ast::Percentage(ref value) => Ok(Pos_Percentage(value.value / 100.)), - &Number(ref value) if value.value == 0. => Ok(Pos_Length(Au_(Au(0)))), + Length::parse_dimension(value.value, unit.as_slice()).map(PositionComponent::Length), + &ast::Percentage(ref value) => Ok(PositionComponent::Percentage(value.value / 100.)), + &Number(ref value) if value.value == 0. => Ok(PositionComponent::Length(Length::Au(Au(0)))), &Ident(ref value) => { - if value.as_slice().eq_ignore_ascii_case("center") { Ok(Pos_Center) } - else if value.as_slice().eq_ignore_ascii_case("left") { Ok(Pos_Left) } - else if value.as_slice().eq_ignore_ascii_case("right") { Ok(Pos_Right) } - else if value.as_slice().eq_ignore_ascii_case("top") { Ok(Pos_Top) } - else if value.as_slice().eq_ignore_ascii_case("bottom") { Ok(Pos_Bottom) } + if value.as_slice().eq_ignore_ascii_case("center") { Ok(PositionComponent::Center) } + else if value.as_slice().eq_ignore_ascii_case("left") { Ok(PositionComponent::Left) } + else if value.as_slice().eq_ignore_ascii_case("right") { Ok(PositionComponent::Right) } + else if value.as_slice().eq_ignore_ascii_case("top") { Ok(PositionComponent::Top) } + else if value.as_slice().eq_ignore_ascii_case("bottom") { Ok(PositionComponent::Bottom) } else { Err(()) } } _ => Err(()) @@ -203,11 +207,11 @@ pub mod specified { #[inline] pub fn to_length_or_percentage(self) -> LengthOrPercentage { match self { - Pos_Length(x) => LP_Length(x), - Pos_Percentage(x) => LP_Percentage(x), - Pos_Center => LP_Percentage(0.5), - Pos_Left | Pos_Top => LP_Percentage(0.0), - Pos_Right | Pos_Bottom => LP_Percentage(1.0), + PositionComponent::Length(x) => LengthOrPercentage::Length(x), + PositionComponent::Percentage(x) => LengthOrPercentage::Percentage(x), + PositionComponent::Center => LengthOrPercentage::Percentage(0.5), + PositionComponent::Left | PositionComponent::Top => LengthOrPercentage::Percentage(0.0), + PositionComponent::Right | PositionComponent::Bottom => LengthOrPercentage::Percentage(1.0), } } } @@ -245,8 +249,8 @@ pub mod specified { /// Specified values for an image according to CSS-IMAGES. #[deriving(Clone)] pub enum Image { - UrlImage(Url), - LinearGradientImage(LinearGradient), + Url(Url), + LinearGradient(LinearGradient), } impl Image { @@ -255,11 +259,11 @@ pub mod specified { match component_value { &ast::URL(ref url) => { let image_url = super::parse_url(url.as_slice(), base_url); - Ok(UrlImage(image_url)) + Ok(Image::Url(image_url)) }, &ast::Function(ref name, ref args) => { if name.as_slice().eq_ignore_ascii_case("linear-gradient") { - Ok(LinearGradientImage(try!( + Ok(Image::LinearGradient(try!( super::specified::LinearGradient::parse_function( args.as_slice())))) } else { @@ -273,9 +277,9 @@ pub mod specified { pub fn to_computed_value(self, context: &super::computed::Context) -> super::computed::Image { match self { - UrlImage(url) => super::computed::UrlImage(url), - LinearGradientImage(linear_gradient) => { - super::computed::LinearGradientImage( + Image::Url(url) => super::computed::Image::Url(url), + Image::LinearGradient(linear_gradient) => { + super::computed::Image::LinearGradient( super::computed::LinearGradient::compute(linear_gradient, context)) } } @@ -295,8 +299,8 @@ pub mod specified { /// Specified values for an angle or a corner in a linear gradient. #[deriving(Clone, PartialEq)] pub enum AngleOrCorner { - AngleAoc(Angle), - CornerAoc(HorizontalDirection, VerticalDirection), + Angle(Angle), + Corner(HorizontalDirection, VerticalDirection), } /// Specified values for one color stop in a linear gradient. @@ -360,11 +364,11 @@ pub mod specified { Dimension(ref value, ref unit) => { match Angle::parse_dimension(value.value, unit.as_slice()) { Ok(angle) => { - (AngleAoc(angle), true) + (AngleOrCorner::Angle(angle), true) } Err(()) => { source.push_back(token); - (AngleAoc(Angle(PI)), false) + (AngleOrCorner::Angle(Angle(PI)), false) } } } @@ -379,16 +383,16 @@ pub mod specified { let ident = ident.as_slice(); if ident.eq_ignore_ascii_case("top") && vertical.is_none() { - vertical = Some(Top) + vertical = Some(VerticalDirection::Top) } else if ident.eq_ignore_ascii_case("bottom") && vertical.is_none() { - vertical = Some(Bottom) + vertical = Some(VerticalDirection::Bottom) } else if ident.eq_ignore_ascii_case("left") && horizontal.is_none() { - horizontal = Some(Left) + horizontal = Some(HorizontalDirection::Left) } else if ident.eq_ignore_ascii_case("right") && horizontal.is_none() { - horizontal = Some(Right) + horizontal = Some(HorizontalDirection::Right) } else { return Err(()) } @@ -404,19 +408,27 @@ pub mod specified { } (match (horizontal, vertical) { - (None, Some(Top)) => AngleAoc(Angle(0.0)), - (Some(Right), None) => AngleAoc(Angle(PI * 0.5)), - (None, Some(Bottom)) => AngleAoc(Angle(PI)), - (Some(Left), None) => AngleAoc(Angle(PI * 1.5)), + (None, Some(VerticalDirection::Top)) => { + AngleOrCorner::Angle(Angle(0.0)) + }, + (Some(HorizontalDirection::Right), None) => { + AngleOrCorner::Angle(Angle(PI * 0.5)) + }, + (None, Some(VerticalDirection::Bottom)) => { + AngleOrCorner::Angle(Angle(PI)) + }, + (Some(HorizontalDirection::Left), None) => { + AngleOrCorner::Angle(Angle(PI * 1.5)) + }, (Some(horizontal), Some(vertical)) => { - CornerAoc(horizontal, vertical) + AngleOrCorner::Corner(horizontal, vertical) } (None, None) => return Err(()), }, true) } _ => { source.push_back(token); - (AngleAoc(Angle(PI)), false) + (AngleOrCorner::Angle(Angle(PI)), false) } } } @@ -448,7 +460,7 @@ pub mod specified { } pub mod computed { - pub use super::specified::{Angle, AngleAoc, AngleOrCorner, CornerAoc, HorizontalDirection}; + pub use super::specified::{Angle, AngleOrCorner, HorizontalDirection}; pub use super::specified::{VerticalDirection}; pub use cssparser::Color as CSSColor; pub use super::super::longhands::computed_as_specified as compute_CSSColor; @@ -487,14 +499,14 @@ pub mod computed { #[inline] pub fn compute_Au_with_font_size(value: specified::Length, reference_font_size: Au, root_font_size: Au) -> Au { match value { - specified::Au_(value) => value, - specified::Em(value) => reference_font_size.scale_by(value), - specified::Ex(value) => { + specified::Length::Au(value) => value, + specified::Length::Em(value) => reference_font_size.scale_by(value), + specified::Length::Ex(value) => { let x_height = 0.5; // TODO: find that from the font reference_font_size.scale_by(value * x_height) }, - specified::Rem(value) => root_font_size.scale_by(value), - specified::ServoCharacterWidth(value) => { + specified::Length::Rem(value) => root_font_size.scale_by(value), + specified::Length::ServoCharacterWidth(value) => { // This applies the *converting a character width to pixels* algorithm as specified // in HTML5 § 14.5.4. // @@ -508,56 +520,64 @@ pub mod computed { #[deriving(PartialEq, Clone, Show)] pub enum LengthOrPercentage { - LP_Length(Au), - LP_Percentage(CSSFloat), + Length(Au), + Percentage(CSSFloat), } #[allow(non_snake_case)] pub fn compute_LengthOrPercentage(value: specified::LengthOrPercentage, context: &Context) -> LengthOrPercentage { match value { - specified::LP_Length(value) => LP_Length(compute_Au(value, context)), - specified::LP_Percentage(value) => LP_Percentage(value), + specified::LengthOrPercentage::Length(value) => + LengthOrPercentage::Length(compute_Au(value, context)), + specified::LengthOrPercentage::Percentage(value) => + LengthOrPercentage::Percentage(value), } } #[deriving(PartialEq, Clone, Show)] pub enum LengthOrPercentageOrAuto { - LPA_Length(Au), - LPA_Percentage(CSSFloat), - LPA_Auto, + Length(Au), + Percentage(CSSFloat), + Auto, } #[allow(non_snake_case)] pub fn compute_LengthOrPercentageOrAuto(value: specified::LengthOrPercentageOrAuto, context: &Context) -> LengthOrPercentageOrAuto { match value { - specified::LPA_Length(value) => LPA_Length(compute_Au(value, context)), - specified::LPA_Percentage(value) => LPA_Percentage(value), - specified::LPA_Auto => LPA_Auto, + specified::LengthOrPercentageOrAuto::Length(value) => + LengthOrPercentageOrAuto::Length(compute_Au(value, context)), + specified::LengthOrPercentageOrAuto::Percentage(value) => + LengthOrPercentageOrAuto::Percentage(value), + specified::LengthOrPercentageOrAuto::Auto => + LengthOrPercentageOrAuto::Auto, } } #[deriving(PartialEq, Clone, Show)] pub enum LengthOrPercentageOrNone { - LPN_Length(Au), - LPN_Percentage(CSSFloat), - LPN_None, + Length(Au), + Percentage(CSSFloat), + None, } #[allow(non_snake_case)] pub fn compute_LengthOrPercentageOrNone(value: specified::LengthOrPercentageOrNone, context: &Context) -> LengthOrPercentageOrNone { match value { - specified::LPN_Length(value) => LPN_Length(compute_Au(value, context)), - specified::LPN_Percentage(value) => LPN_Percentage(value), - specified::LPN_None => LPN_None, + specified::LengthOrPercentageOrNone::Length(value) => + LengthOrPercentageOrNone::Length(compute_Au(value, context)), + specified::LengthOrPercentageOrNone::Percentage(value) => + LengthOrPercentageOrNone::Percentage(value), + specified::LengthOrPercentageOrNone::None => + LengthOrPercentageOrNone::None, } } /// Computed values for an image according to CSS-IMAGES. #[deriving(Clone, PartialEq)] pub enum Image { - UrlImage(Url), - LinearGradientImage(LinearGradient), + Url(Url), + LinearGradient(LinearGradient), } /// Computed values for a CSS linear gradient. diff --git a/components/style/properties/mod.rs.mako b/components/style/properties/mod.rs.mako index 2107ac86c7b..1dd3ed561d0 100644 --- a/components/style/properties/mod.rs.mako +++ b/components/style/properties/mod.rs.mako @@ -13,8 +13,8 @@ pub use url::Url; pub use cssparser::*; pub use cssparser::ast::*; pub use geom::SideOffsets2D; -pub use self::common_types::specified::{Angle, AngleAoc, AngleOrCorner, Bottom, CornerAoc}; -pub use self::common_types::specified::{Left, Right, Top}; +pub use self::common_types::specified::{Angle, AngleOrCorner}; +pub use self::common_types::specified::{HorizontalDirection, VerticalDirection}; use errors::{ErrorLoggerIterator, log_css_error}; pub use parsing_utils::*; @@ -121,9 +121,9 @@ pub mod longhands { pub fn parse_declared(input: &[ComponentValue], base_url: &Url) -> Result<DeclaredValue<SpecifiedValue>, ()> { match CSSWideKeyword::parse(input) { - Ok(InheritKeyword) => Ok(Inherit), - Ok(InitialKeyword) => Ok(Initial), - Ok(UnsetKeyword) => Ok(${ + Ok(CSSWideKeyword::InheritKeyword) => Ok(DeclaredValue::Inherit), + Ok(CSSWideKeyword::InitialKeyword) => Ok(DeclaredValue::Initial), + Ok(CSSWideKeyword::UnsetKeyword) => Ok(DeclaredValue::${ "Inherit" if THIS_STYLE_STRUCT.inherited else "Initial"}), Err(()) => parse_specified(input, base_url), } @@ -139,7 +139,7 @@ pub mod longhands { % if derived_from is None: pub fn parse_specified(_input: &[ComponentValue], _base_url: &Url) -> Result<DeclaredValue<SpecifiedValue>, ()> { - parse(_input, _base_url).map(super::SpecifiedValue) + parse(_input, _base_url).map(super::DeclaredValue::SpecifiedValue) } % endif </%self:raw_longhand> @@ -169,14 +169,14 @@ pub mod longhands { } pub type SpecifiedValue = computed_value::T; #[inline] pub fn get_initial_value() -> computed_value::T { - ${to_rust_ident(values.split()[0])} + T::${to_rust_ident(values.split()[0])} } pub fn from_component_value(v: &ComponentValue, _base_url: &Url) -> Result<SpecifiedValue, ()> { get_ident_lower(v).and_then(|keyword| { match keyword.as_slice() { % for value in values.split(): - "${value}" => Ok(${to_rust_ident(value)}), + "${value}" => Ok(T::${to_rust_ident(value)}), % endfor _ => Err(()), } @@ -216,21 +216,21 @@ pub mod longhands { % for side in ["top", "right", "bottom", "left"]: ${predefined_type("margin-" + side, "LengthOrPercentageOrAuto", - "computed::LPA_Length(Au(0))")} + "computed::LengthOrPercentageOrAuto::Length(Au(0))")} % endfor ${new_style_struct("Padding", is_inherited=False)} % for side in ["top", "right", "bottom", "left"]: ${predefined_type("padding-" + side, "LengthOrPercentage", - "computed::LP_Length(Au(0))", + "computed::LengthOrPercentage::Length(Au(0))", "parse_non_negative")} % endfor ${new_style_struct("Border", is_inherited=False)} % for side in ["top", "right", "bottom", "left"]: - ${predefined_type("border-%s-color" % side, "CSSColor", "CurrentColor")} + ${predefined_type("border-%s-color" % side, "CSSColor", "super::super::computed::CSSColor::CurrentColor")} % endfor ${single_keyword("border-top-style", values="none solid double dotted dashed hidden groove ridge inset outset")} @@ -302,7 +302,7 @@ pub mod longhands { #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { - radius: computed::LP_Length(Au(0)), + radius: computed::LengthOrPercentage::Length(Au(0)), } } #[inline] @@ -358,7 +358,7 @@ pub mod longhands { ${new_style_struct("Outline", is_inherited=False)} // TODO(pcwalton): `invert` - ${predefined_type("outline-color", "CSSColor", "CurrentColor")} + ${predefined_type("outline-color", "CSSColor", "super::super::computed::CSSColor::CurrentColor")} <%self:single_component_value name="outline-style"> pub use super::border_top_style::{get_initial_value, to_computed_value}; @@ -391,7 +391,7 @@ pub mod longhands { % for side in ["top", "right", "bottom", "left"]: ${predefined_type(side, "LengthOrPercentageOrAuto", - "computed::LPA_Auto")} + "computed::LengthOrPercentageOrAuto::Auto")} % endfor // CSS 2.1, Section 9 - Visual formatting model @@ -413,12 +413,13 @@ pub mod longhands { // } if context.positioned || context.floated || context.is_root_element { match value { - inline_table => table, - inline | inline_block - | table_row_group | table_column | table_column_group - | table_header_group | table_footer_group | table_row - | table_cell | table_caption - => block, + T::inline_table => T::table, + T::inline | T::inline_block | + T::table_row_group | T::table_column | + T::table_column_group | T::table_header_group | + T::table_footer_group | T::table_row | T::table_cell | + T::table_caption + => T::block, _ => value, } } else { @@ -463,23 +464,23 @@ pub mod longhands { impl T { pub fn number_or_zero(self) -> i32 { match self { - Auto => 0, - Number(value) => value, + T::Auto => 0, + T::Number(value) => value, } } } } #[inline] pub fn get_initial_value() -> computed_value::T { - Auto + T::Auto } fn from_component_value(input: &ComponentValue, _: &Url) -> Result<SpecifiedValue,()> { match *input { - Ident(ref keyword) if keyword.as_slice().eq_ignore_ascii_case("auto") => Ok(Auto), + Ident(ref keyword) if keyword.as_slice().eq_ignore_ascii_case("auto") => Ok(T::Auto), ast::Number(ast::NumericValue { int_value: Some(value), .. - }) => Ok(Number(value as i32)), + }) => Ok(T::Number(value as i32)), _ => Err(()) } } @@ -494,7 +495,7 @@ pub mod longhands { ${switch_to_style_struct("Box")} ${predefined_type("width", "LengthOrPercentageOrAuto", - "computed::LPA_Auto", + "computed::LengthOrPercentageOrAuto::Auto", "parse_non_negative")} <%self:single_component_value name="height"> pub type SpecifiedValue = specified::LengthOrPercentageOrAuto; @@ -502,7 +503,7 @@ pub mod longhands { pub type T = super::super::computed::LengthOrPercentageOrAuto; } #[inline] - pub fn get_initial_value() -> computed_value::T { computed::LPA_Auto } + pub fn get_initial_value() -> computed_value::T { computed::LengthOrPercentageOrAuto::Auto } #[inline] pub fn from_component_value(v: &ComponentValue, _base_url: &Url) -> Result<SpecifiedValue, ()> { @@ -511,9 +512,9 @@ pub mod longhands { pub fn to_computed_value(value: SpecifiedValue, context: &computed::Context) -> computed_value::T { match (value, context.inherited_height) { - (specified::LPA_Percentage(_), computed::LPA_Auto) + (specified::LengthOrPercentageOrAuto::Percentage(_), computed::LengthOrPercentageOrAuto::Auto) if !context.is_root_element && !context.positioned => { - computed::LPA_Auto + computed::LengthOrPercentageOrAuto::Auto }, _ => computed::compute_LengthOrPercentageOrAuto(value, context) } @@ -521,17 +522,17 @@ pub mod longhands { </%self:single_component_value> ${predefined_type("min-width", "LengthOrPercentage", - "computed::LP_Length(Au(0))", + "computed::LengthOrPercentage::Length(Au(0))", "parse_non_negative")} ${predefined_type("max-width", "LengthOrPercentageOrNone", - "computed::LPN_None", + "computed::LengthOrPercentageOrNone::None", "parse_non_negative")} ${predefined_type("min-height", "LengthOrPercentage", - "computed::LP_Length(Au(0))", + "computed::LengthOrPercentage::Length(Au(0))", "parse_non_negative")} ${predefined_type("max-height", "LengthOrPercentageOrNone", - "computed::LPN_None", + "computed::LengthOrPercentageOrNone::None", "parse_non_negative")} ${switch_to_style_struct("InheritedBox")} @@ -539,24 +540,24 @@ pub mod longhands { <%self:single_component_value name="line-height"> #[deriving(Clone)] pub enum SpecifiedValue { - SpecifiedNormal, - SpecifiedLength(specified::Length), - SpecifiedNumber(CSSFloat), + Normal, + Length(specified::Length), + Number(CSSFloat), // percentage are the same as em. } /// normal | <number> | <length> | <percentage> pub fn from_component_value(input: &ComponentValue, _base_url: &Url) -> Result<SpecifiedValue, ()> { match input { - &ast::Number(ref value) if value.value >= 0. - => Ok(SpecifiedNumber(value.value)), - &ast::Percentage(ref value) if value.value >= 0. - => Ok(SpecifiedLength(specified::Em(value.value / 100.))), - &Dimension(ref value, ref unit) if value.value >= 0. - => specified::Length::parse_dimension(value.value, unit.as_slice()) - .map(SpecifiedLength), - &Ident(ref value) if value.as_slice().eq_ignore_ascii_case("normal") - => Ok(SpecifiedNormal), + &ast::Number(ref value) if value.value >= 0. => + Ok(SpecifiedValue::Number(value.value)), + &ast::Percentage(ref value) if value.value >= 0. => + Ok(SpecifiedValue::Length(specified::Length::Em(value.value / 100.))), + &Dimension(ref value, ref unit) if value.value >= 0. => + specified::Length::parse_dimension(value.value, unit.as_slice()) + .map(SpecifiedValue::Length), + &Ident(ref value) if value.as_slice().eq_ignore_ascii_case("normal") => + Ok(SpecifiedValue::Normal), _ => Err(()), } } @@ -570,14 +571,14 @@ pub mod longhands { } } #[inline] - pub fn get_initial_value() -> computed_value::T { Normal } + pub fn get_initial_value() -> computed_value::T { T::Normal } #[inline] pub fn to_computed_value(value: SpecifiedValue, context: &computed::Context) -> computed_value::T { match value { - SpecifiedNormal => Normal, - SpecifiedLength(value) => Length(computed::compute_Au(value, context)), - SpecifiedNumber(value) => Number(value), + SpecifiedValue::Normal => T::Normal, + SpecifiedValue::Length(value) => T::Length(computed::compute_Au(value, context)), + SpecifiedValue::Number(value) => T::Number(value), } } </%self:single_component_value> @@ -591,9 +592,9 @@ pub mod longhands { #[deriving(Clone)] pub enum SpecifiedValue { % for keyword in vertical_align_keywords: - Specified_${to_rust_ident(keyword)}, + ${to_rust_ident(keyword)}, % endfor - SpecifiedLengthOrPercentage(specified::LengthOrPercentage), + LengthOrPercentage(specified::LengthOrPercentage), } /// baseline | sub | super | top | text-top | middle | bottom | text-bottom /// | <percentage> | <length> @@ -603,13 +604,13 @@ pub mod longhands { &Ident(ref value) => { match value.as_slice().to_ascii_lower().as_slice() { % for keyword in vertical_align_keywords: - "${keyword}" => Ok(Specified_${to_rust_ident(keyword)}), + "${keyword}" => Ok(SpecifiedValue::${to_rust_ident(keyword)}), % endfor _ => Err(()), } }, _ => specified::LengthOrPercentage::parse_non_negative(input) - .map(SpecifiedLengthOrPercentage) + .map(SpecifiedValue::LengthOrPercentage) } } pub mod computed_value { @@ -625,18 +626,18 @@ pub mod longhands { } } #[inline] - pub fn get_initial_value() -> computed_value::T { baseline } + pub fn get_initial_value() -> computed_value::T { T::baseline } #[inline] pub fn to_computed_value(value: SpecifiedValue, context: &computed::Context) -> computed_value::T { match value { % for keyword in vertical_align_keywords: - Specified_${to_rust_ident(keyword)} => ${to_rust_ident(keyword)}, + SpecifiedValue::${to_rust_ident(keyword)} => computed_value::T::${to_rust_ident(keyword)}, % endfor - SpecifiedLengthOrPercentage(value) + SpecifiedValue::LengthOrPercentage(value) => match computed::compute_LengthOrPercentage(value, context) { - computed::LP_Length(value) => Length(value), - computed::LP_Percentage(value) => Percentage(value) + computed::LengthOrPercentage::Length(value) => T::Length(value), + computed::LengthOrPercentage::Percentage(value) => T::Percentage(value) } } } @@ -672,7 +673,7 @@ pub mod longhands { } } pub type SpecifiedValue = computed_value::T; - #[inline] pub fn get_initial_value() -> computed_value::T { normal } + #[inline] pub fn get_initial_value() -> computed_value::T { T::normal } // normal | none | [ <string> ]+ // TODO: <uri>, <counter>, attr(<identifier>), open-quote, close-quote, no-open-quote, no-close-quote @@ -680,8 +681,8 @@ pub mod longhands { match one_component_value(input) { Ok(&Ident(ref keyword)) => { match keyword.as_slice().to_ascii_lower().as_slice() { - "normal" => return Ok(normal), - "none" => return Ok(none), + "normal" => return Ok(T::normal), + "none" => return Ok(T::none), _ => () } }, @@ -691,11 +692,11 @@ pub mod longhands { for component_value in input.skip_whitespace() { match component_value { &QuotedString(ref value) - => content.push(StringContent(value.clone())), + => content.push(ContentItem::StringContent(value.clone())), _ => return Err(()) // invalid/unsupported value } } - Ok(Content(content)) + Ok(T::Content(content)) } </%self:longhand> @@ -743,7 +744,7 @@ pub mod longhands { ${new_style_struct("Background", is_inherited=False)} ${predefined_type("background-color", "CSSColor", - "RGBAColor(RGBA { red: 0., green: 0., blue: 0., alpha: 0. }) /* transparent */")} + "Color::RGBA(RGBA { red: 0., green: 0., blue: 0., alpha: 0. }) /* transparent */")} <%self:single_component_value name="background-image"> use super::common_types::specified as common_specified; @@ -804,13 +805,13 @@ pub mod longhands { -> Result<SpecifiedValue,()> { let (horiz, vert) = match (category(first), category(second)) { // Don't allow two vertical keywords or two horizontal keywords. - (HorizontalKeyword, HorizontalKeyword) | - (VerticalKeyword, VerticalKeyword) => return Err(()), + (PositionCategory::HorizontalKeyword, PositionCategory::HorizontalKeyword) | + (PositionCategory::VerticalKeyword, PositionCategory::VerticalKeyword) => return Err(()), // Swap if both are keywords and vertical precedes horizontal. - (VerticalKeyword, HorizontalKeyword) | - (VerticalKeyword, OtherKeyword) | - (OtherKeyword, HorizontalKeyword) => (second, first), + (PositionCategory::VerticalKeyword, PositionCategory::HorizontalKeyword) | + (PositionCategory::VerticalKeyword, PositionCategory::OtherKeyword) | + (PositionCategory::OtherKeyword, PositionCategory::HorizontalKeyword) => (second, first), // By default, horizontal is first. _ => (first, second), @@ -831,11 +832,17 @@ pub mod longhands { } fn category(p: specified::PositionComponent) -> PositionCategory { match p { - specified::Pos_Left | specified::Pos_Right => HorizontalKeyword, - specified::Pos_Top | specified::Pos_Bottom => VerticalKeyword, - specified::Pos_Center => OtherKeyword, - specified::Pos_Length(_) | - specified::Pos_Percentage(_) => LengthOrPercentage, + specified::PositionComponent::Left | + specified::PositionComponent::Right => + PositionCategory::HorizontalKeyword, + specified::PositionComponent::Top | + specified::PositionComponent::Bottom => + PositionCategory::VerticalKeyword, + specified::PositionComponent::Center => + PositionCategory::OtherKeyword, + specified::PositionComponent::Length(_) | + specified::PositionComponent::Percentage(_) => + PositionCategory::LengthOrPercentage, } } @@ -851,15 +858,15 @@ pub mod longhands { #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { - horizontal: computed::LP_Percentage(0.0), - vertical: computed::LP_Percentage(0.0), + horizontal: computed::LengthOrPercentage::Percentage(0.0), + vertical: computed::LengthOrPercentage::Percentage(0.0), } } pub fn parse_one(first: &ComponentValue) -> Result<SpecifiedValue, ()> { let first = try!(specified::PositionComponent::parse(first)); // If only one value is provided, use `center` for the second. - SpecifiedValue::new(first, specified::Pos_Center) + SpecifiedValue::new(first, specified::PositionComponent::Center) } pub fn parse_two(first: &ComponentValue, second: &ComponentValue) @@ -906,8 +913,8 @@ pub mod longhands { pub fn parse_specified(input: &[ComponentValue], _base_url: &Url) -> Result<DeclaredValue<SpecifiedValue>, ()> { match one_component_value(input).and_then(Color::parse) { - Ok(RGBAColor(rgba)) => Ok(SpecifiedValue(rgba)), - Ok(CurrentColor) => Ok(Inherit), + Ok(Color::RGBA(rgba)) => Ok(DeclaredValue::SpecifiedValue(rgba)), + Ok(Color::CurrentColor) => Ok(DeclaredValue::Inherit), Err(()) => Err(()), } } @@ -933,7 +940,7 @@ pub mod longhands { impl FontFamily { pub fn name(&self) -> &str { match *self { - FamilyName(ref name) => name.as_slice(), + FontFamily::FamilyName(ref name) => name.as_slice(), } } } @@ -943,7 +950,7 @@ pub mod longhands { #[inline] pub fn get_initial_value() -> computed_value::T { - vec![FamilyName("serif".to_string())] + vec![FontFamily::FamilyName("serif".to_string())] } /// <familiy-name># /// <familiy-name> = <string> | [ <ident>+ ] @@ -954,7 +961,7 @@ pub mod longhands { pub fn parse_one_family<'a>(iter: ParserIter) -> Result<FontFamily, ()> { // TODO: avoid copying strings? let mut idents = match iter.next() { - Some(&QuotedString(ref value)) => return Ok(FamilyName(value.clone())), + Some(&QuotedString(ref value)) => return Ok(FontFamily::FamilyName(value.clone())), Some(&Ident(ref value)) => { // match value.as_slice().to_ascii_lower().as_slice() { // "serif" => return Ok(Serif), @@ -982,7 +989,7 @@ pub mod longhands { None => break, } } - Ok(FamilyName(idents.connect(" "))) + Ok(FontFamily::FamilyName(idents.connect(" "))) } </%self:longhand> @@ -1005,23 +1012,23 @@ pub mod longhands { match input { &Ident(ref value) => { match value.as_slice().to_ascii_lower().as_slice() { - "bold" => Ok(SpecifiedWeight700), - "normal" => Ok(SpecifiedWeight400), - "bolder" => Ok(Bolder), - "lighter" => Ok(Lighter), + "bold" => Ok(SpecifiedValue::SpecifiedWeight700), + "normal" => Ok(SpecifiedValue::SpecifiedWeight400), + "bolder" => Ok(SpecifiedValue::Bolder), + "lighter" => Ok(SpecifiedValue::Lighter), _ => Err(()), } }, &Number(ref value) => match value.int_value { - Some(100) => Ok(SpecifiedWeight100), - Some(200) => Ok(SpecifiedWeight200), - Some(300) => Ok(SpecifiedWeight300), - Some(400) => Ok(SpecifiedWeight400), - Some(500) => Ok(SpecifiedWeight500), - Some(600) => Ok(SpecifiedWeight600), - Some(700) => Ok(SpecifiedWeight700), - Some(800) => Ok(SpecifiedWeight800), - Some(900) => Ok(SpecifiedWeight900), + Some(100) => Ok(SpecifiedValue::SpecifiedWeight100), + Some(200) => Ok(SpecifiedValue::SpecifiedWeight200), + Some(300) => Ok(SpecifiedValue::SpecifiedWeight300), + Some(400) => Ok(SpecifiedValue::SpecifiedWeight400), + Some(500) => Ok(SpecifiedValue::SpecifiedWeight500), + Some(600) => Ok(SpecifiedValue::SpecifiedWeight600), + Some(700) => Ok(SpecifiedValue::SpecifiedWeight700), + Some(800) => Ok(SpecifiedValue::SpecifiedWeight800), + Some(900) => Ok(SpecifiedValue::SpecifiedWeight900), _ => Err(()), }, _ => Err(()) @@ -1037,42 +1044,45 @@ pub mod longhands { impl T { pub fn is_bold(self) -> bool { match self { - Weight900 | Weight800 | Weight700 | Weight600 => true, + T::Weight900 | T::Weight800 | + T::Weight700 | T::Weight600 => true, _ => false } } } } #[inline] - pub fn get_initial_value() -> computed_value::T { Weight400 } // normal + pub fn get_initial_value() -> computed_value::T { + computed_value::T::Weight400 // normal + } #[inline] pub fn to_computed_value(value: SpecifiedValue, context: &computed::Context) -> computed_value::T { match value { % for weight in range(100, 901, 100): - SpecifiedWeight${weight} => Weight${weight}, + SpecifiedValue::SpecifiedWeight${weight} => computed_value::T::Weight${weight}, % endfor - Bolder => match context.inherited_font_weight { - Weight100 => Weight400, - Weight200 => Weight400, - Weight300 => Weight400, - Weight400 => Weight700, - Weight500 => Weight700, - Weight600 => Weight900, - Weight700 => Weight900, - Weight800 => Weight900, - Weight900 => Weight900, + SpecifiedValue::Bolder => match context.inherited_font_weight { + computed_value::T::Weight100 => computed_value::T::Weight400, + computed_value::T::Weight200 => computed_value::T::Weight400, + computed_value::T::Weight300 => computed_value::T::Weight400, + computed_value::T::Weight400 => computed_value::T::Weight700, + computed_value::T::Weight500 => computed_value::T::Weight700, + computed_value::T::Weight600 => computed_value::T::Weight900, + computed_value::T::Weight700 => computed_value::T::Weight900, + computed_value::T::Weight800 => computed_value::T::Weight900, + computed_value::T::Weight900 => computed_value::T::Weight900, }, - Lighter => match context.inherited_font_weight { - Weight100 => Weight100, - Weight200 => Weight100, - Weight300 => Weight100, - Weight400 => Weight100, - Weight500 => Weight100, - Weight600 => Weight400, - Weight700 => Weight400, - Weight800 => Weight700, - Weight900 => Weight700, + SpecifiedValue::Lighter => match context.inherited_font_weight { + computed_value::T::Weight100 => computed_value::T::Weight100, + computed_value::T::Weight200 => computed_value::T::Weight100, + computed_value::T::Weight300 => computed_value::T::Weight100, + computed_value::T::Weight400 => computed_value::T::Weight100, + computed_value::T::Weight500 => computed_value::T::Weight100, + computed_value::T::Weight600 => computed_value::T::Weight400, + computed_value::T::Weight700 => computed_value::T::Weight400, + computed_value::T::Weight800 => computed_value::T::Weight700, + computed_value::T::Weight900 => computed_value::T::Weight700, }, } } @@ -1098,22 +1108,22 @@ pub mod longhands { pub fn from_component_value(input: &ComponentValue, _base_url: &Url) -> Result<SpecifiedValue, ()> { match specified::LengthOrPercentage::parse_non_negative(input) { - Ok(specified::LP_Length(value)) => return Ok(value), - Ok(specified::LP_Percentage(value)) => return Ok(specified::Em(value)), + Ok(specified::LengthOrPercentage::Length(value)) => return Ok(value), + Ok(specified::LengthOrPercentage::Percentage(value)) => return Ok(specified::Length::Em(value)), Err(()) => (), } match try!(get_ident_lower(input)).as_slice() { - "xx-small" => Ok(specified::Au_(Au::from_px(MEDIUM_PX) * 3 / 5)), - "x-small" => Ok(specified::Au_(Au::from_px(MEDIUM_PX) * 3 / 4)), - "small" => Ok(specified::Au_(Au::from_px(MEDIUM_PX) * 8 / 9)), - "medium" => Ok(specified::Au_(Au::from_px(MEDIUM_PX))), - "large" => Ok(specified::Au_(Au::from_px(MEDIUM_PX) * 6 / 5)), - "x-large" => Ok(specified::Au_(Au::from_px(MEDIUM_PX) * 3 / 2)), - "xx-large" => Ok(specified::Au_(Au::from_px(MEDIUM_PX) * 2)), + "xx-small" => Ok(specified::Length::Au(Au::from_px(MEDIUM_PX) * 3 / 5)), + "x-small" => Ok(specified::Length::Au(Au::from_px(MEDIUM_PX) * 3 / 4)), + "small" => Ok(specified::Length::Au(Au::from_px(MEDIUM_PX) * 8 / 9)), + "medium" => Ok(specified::Length::Au(Au::from_px(MEDIUM_PX))), + "large" => Ok(specified::Length::Au(Au::from_px(MEDIUM_PX) * 6 / 5)), + "x-large" => Ok(specified::Length::Au(Au::from_px(MEDIUM_PX) * 3 / 2)), + "xx-large" => Ok(specified::Length::Au(Au::from_px(MEDIUM_PX) * 2)), // https://github.com/servo/servo/issues/3423#issuecomment-56321664 - "smaller" => Ok(specified::Em(0.85)), - "larger" => Ok(specified::Em(1.2)), + "smaller" => Ok(specified::Length::Em(0.85)), + "larger" => Ok(specified::Length::Em(1.2)), _ => return Err(()) } @@ -1173,7 +1183,7 @@ pub mod longhands { } </%self:single_component_value> - ${predefined_type("text-indent", "LengthOrPercentage", "computed::LP_Length(Au(0))")} + ${predefined_type("text-indent", "LengthOrPercentage", "computed::LengthOrPercentage::Length(Au(0))")} // Also known as "word-wrap" (which is more popular because of IE), but this is the preferred // name per CSS-TEXT 6.2. @@ -1269,7 +1279,7 @@ pub mod longhands { // Start with no declarations if this is a block; otherwise, start with the // declarations in effect and add in the text decorations that this inline specifies. let mut result = match context.display { - display::computed_value::inline => context.inherited_text_decorations_in_effect, + display::computed_value::T::inline => context.inherited_text_decorations_in_effect, _ => { SpecifiedValue { underline: None, @@ -1422,14 +1432,14 @@ pub mod longhands { offset_y: computed::compute_Au(value.offset_y, context), blur_radius: computed::compute_Au(value.blur_radius, context), spread_radius: computed::compute_Au(value.spread_radius, context), - color: value.color.unwrap_or(cssparser::CurrentColor), + color: value.color.unwrap_or(cssparser::Color::CurrentColor), inset: value.inset, } }).collect() } fn parse_one_box_shadow(iter: ParserIter) -> Result<SpecifiedBoxShadow,()> { - let mut lengths = [specified::Au_(Au(0)), ..4]; + let mut lengths = [specified::Length::Au(Au(0)), ..4]; let mut lengths_parsed = false; let mut color = None; let mut inset = false; @@ -1766,7 +1776,7 @@ pub mod shorthands { fn parse_one_set_of_border_radii<'a,I>(mut input: Peekable< &'a ComponentValue,I >) -> Result<[specified::LengthOrPercentage, ..4],()> where I: Iterator< &'a ComponentValue > { - let (mut count, mut values) = (0u, [specified::LP_Length(specified::Au_(Au(0))), ..4]); + let (mut count, mut values) = (0u, [specified::LengthOrPercentage::Length(specified::Length::Au(Au(0))), ..4]); while count < 4 { let token = match input.peek() { None => break, @@ -2004,14 +2014,14 @@ pub mod shorthands { Ok(Longhands { list_style_position: position, list_style_image: Some(None), - list_style_type: Some(list_style_type::none), + list_style_type: Some(list_style_type::T::none), }) } (true, 1, None, Some(image)) => { Ok(Longhands { list_style_position: position, list_style_image: Some(image), - list_style_type: Some(list_style_type::none), + list_style_type: Some(list_style_type::T::none), }) } (true, 1, Some(list_style_type), None) => { @@ -2025,7 +2035,7 @@ pub mod shorthands { Ok(Longhands { list_style_position: position, list_style_image: Some(None), - list_style_type: Some(list_style_type::none), + list_style_type: Some(list_style_type::T::none), }) } (true, 0, list_style_type, image) => { @@ -2105,9 +2115,9 @@ pub fn parse_property_declaration_list<I: Iterator<Node>>(input: I, base_url: &U ErrorLoggerIterator(parse_declaration_list(input)).collect(); for item in items.into_iter().rev() { match item { - DeclAtRule(rule) => log_css_error( + DeclarationListItem::AtRule(rule) => log_css_error( rule.location, format!("Unsupported at-rule in declaration list: @{:s}", rule.name).as_slice()), - Declaration_(Declaration{ location: l, name: n, value: v, important: i}) => { + DeclarationListItem::Declaration(Declaration{ location: l, name: n, value: v, important: i}) => { // TODO: only keep the last valid declaration for a given name. let (list, seen) = if i { (&mut important_declarations, &mut important_seen) @@ -2115,15 +2125,15 @@ pub fn parse_property_declaration_list<I: Iterator<Node>>(input: I, base_url: &U (&mut normal_declarations, &mut normal_seen) }; match PropertyDeclaration::parse(n.as_slice(), v.as_slice(), list, base_url, seen) { - UnknownProperty => log_css_error(l, format!( + PropertyDeclarationParseResult::UnknownProperty => log_css_error(l, format!( "Unsupported property: {}:{}", n, v.iter().to_css()).as_slice()), - ExperimentalProperty => log_css_error(l, format!( + PropertyDeclarationParseResult::ExperimentalProperty => log_css_error(l, format!( "Experimental property, use `servo --enable_experimental` \ or `servo -e` to enable: {}:{}", n, v.iter().to_css()).as_slice()), - InvalidValue => log_css_error(l, format!( + PropertyDeclarationParseResult::InvalidValue => log_css_error(l, format!( "Invalid value: {}:{}", n, v.iter().to_css()).as_slice()), - ValidOrIgnoredDeclaration => (), + PropertyDeclarationParseResult::ValidOrIgnoredDeclaration => (), } } } @@ -2145,9 +2155,9 @@ impl CSSWideKeyword { pub fn parse(input: &[ComponentValue]) -> Result<CSSWideKeyword, ()> { one_component_value(input).and_then(get_ident_lower).and_then(|keyword| { match keyword.as_slice() { - "initial" => Ok(InitialKeyword), - "inherit" => Ok(InheritKeyword), - "unset" => Ok(UnsetKeyword), + "initial" => Ok(CSSWideKeyword::InitialKeyword), + "inherit" => Ok(CSSWideKeyword::InheritKeyword), + "unset" => Ok(CSSWideKeyword::UnsetKeyword), _ => Err(()) } }) @@ -2192,84 +2202,86 @@ impl PropertyDeclaration { "${property.name}" => { % if property.experimental: if !::servo_util::opts::experimental_enabled() { - return ExperimentalProperty + return PropertyDeclarationParseResult::ExperimentalProperty } % endif if seen.get_${property.ident}() { - return ValidOrIgnoredDeclaration + return PropertyDeclarationParseResult::ValidOrIgnoredDeclaration } match longhands::${property.ident}::parse_declared(value, base_url) { Ok(value) => { seen.set_${property.ident}(); - result_list.push(${property.camel_case}Declaration(value)); - ValidOrIgnoredDeclaration + result_list.push(PropertyDeclaration::${property.camel_case}Declaration(value)); + PropertyDeclarationParseResult::ValidOrIgnoredDeclaration }, - Err(()) => InvalidValue, + Err(()) => PropertyDeclarationParseResult::InvalidValue, } }, % else: - "${property.name}" => UnknownProperty, + "${property.name}" => PropertyDeclarationParseResult::UnknownProperty, % endif % endfor % for shorthand in SHORTHANDS: "${shorthand.name}" => { if ${" && ".join("seen.get_%s()" % sub_property.ident for sub_property in shorthand.sub_properties)} { - return ValidOrIgnoredDeclaration + return PropertyDeclarationParseResult::ValidOrIgnoredDeclaration } match CSSWideKeyword::parse(value) { - Ok(InheritKeyword) => { + Ok(CSSWideKeyword::InheritKeyword) => { % for sub_property in shorthand.sub_properties: if !seen.get_${sub_property.ident}() { seen.set_${sub_property.ident}(); result_list.push( - ${sub_property.camel_case}Declaration(Inherit)); + PropertyDeclaration::${sub_property.camel_case}Declaration( + DeclaredValue::Inherit)); } % endfor - ValidOrIgnoredDeclaration + PropertyDeclarationParseResult::ValidOrIgnoredDeclaration }, - Ok(InitialKeyword) => { + Ok(CSSWideKeyword::InitialKeyword) => { % for sub_property in shorthand.sub_properties: if !seen.get_${sub_property.ident}() { seen.set_${sub_property.ident}(); result_list.push( - ${sub_property.camel_case}Declaration(Initial)); + PropertyDeclaration::${sub_property.camel_case}Declaration( + DeclaredValue::Initial)); } % endfor - ValidOrIgnoredDeclaration + PropertyDeclarationParseResult::ValidOrIgnoredDeclaration }, - Ok(UnsetKeyword) => { + Ok(CSSWideKeyword::UnsetKeyword) => { % for sub_property in shorthand.sub_properties: if !seen.get_${sub_property.ident}() { seen.set_${sub_property.ident}(); - result_list.push(${sub_property.camel_case}Declaration( - ${"Inherit" if sub_property.style_struct.inherited else "Initial"} + result_list.push(PropertyDeclaration::${sub_property.camel_case}Declaration( + DeclaredValue::${"Inherit" if sub_property.style_struct.inherited else "Initial"} )); } % endfor - ValidOrIgnoredDeclaration + PropertyDeclarationParseResult::ValidOrIgnoredDeclaration }, Err(()) => match shorthands::${shorthand.ident}::parse(value, base_url) { Ok(result) => { % for sub_property in shorthand.sub_properties: if !seen.get_${sub_property.ident}() { seen.set_${sub_property.ident}(); - result_list.push(${sub_property.camel_case}Declaration( + result_list.push(PropertyDeclaration::${sub_property.camel_case}Declaration( match result.${sub_property.ident} { - Some(value) => SpecifiedValue(value), - None => Initial, + Some(value) => DeclaredValue::SpecifiedValue(value), + None => DeclaredValue::Initial, } )); } % endfor - ValidOrIgnoredDeclaration + PropertyDeclarationParseResult::ValidOrIgnoredDeclaration }, - Err(()) => InvalidValue, + Err(()) => PropertyDeclarationParseResult::InvalidValue, } } }, % endfor - _ => UnknownProperty, + _ => PropertyDeclarationParseResult::UnknownProperty, } } } @@ -2308,8 +2320,8 @@ impl ComputedValues { #[inline] pub fn resolve_color(&self, color: computed::CSSColor) -> RGBA { match color { - RGBAColor(rgba) => rgba, - CurrentColor => self.get_color().color, + Color::RGBA(rgba) => rgba, + Color::CurrentColor => self.get_color().color, } } @@ -2414,27 +2426,27 @@ fn get_writing_mode(inheritedbox_style: &style_structs::InheritedBox) -> Writing use servo_util::logical_geometry; let mut flags = WritingMode::empty(); match inheritedbox_style.direction { - computed_values::direction::ltr => {}, - computed_values::direction::rtl => { + computed_values::direction::T::ltr => {}, + computed_values::direction::T::rtl => { flags.insert(logical_geometry::FLAG_RTL); }, } match inheritedbox_style.writing_mode { - computed_values::writing_mode::horizontal_tb => {}, - computed_values::writing_mode::vertical_rl => { + computed_values::writing_mode::T::horizontal_tb => {}, + computed_values::writing_mode::T::vertical_rl => { flags.insert(logical_geometry::FLAG_VERTICAL); }, - computed_values::writing_mode::vertical_lr => { + computed_values::writing_mode::T::vertical_lr => { flags.insert(logical_geometry::FLAG_VERTICAL); flags.insert(logical_geometry::FLAG_VERTICAL_LR); }, } match inheritedbox_style.text_orientation { - computed_values::text_orientation::sideways_right => {}, - computed_values::text_orientation::sideways_left => { + computed_values::text_orientation::T::sideways_right => {}, + computed_values::text_orientation::T::sideways_left => { flags.insert(logical_geometry::FLAG_VERTICAL_LR); }, - computed_values::text_orientation::sideways => { + computed_values::text_orientation::T::sideways => { if flags.intersects(logical_geometry::FLAG_VERTICAL_LR) { flags.insert(logical_geometry::FLAG_SIDEWAYS_LEFT); } @@ -2492,21 +2504,21 @@ fn cascade_with_cached_declarations(applicable_declarations: &[DeclarationBlock] % for style_struct in STYLE_STRUCTS: % for property in style_struct.longhands: % if property.derived_from is None: - ${property.camel_case}Declaration(ref ${'_' if not style_struct.inherited else ''}declared_value) => { + PropertyDeclaration::${property.camel_case}Declaration(ref ${'_' if not style_struct.inherited else ''}declared_value) => { % if style_struct.inherited: if seen.get_${property.ident}() { continue } seen.set_${property.ident}(); let computed_value = match *declared_value { - SpecifiedValue(ref specified_value) + DeclaredValue::SpecifiedValue(ref specified_value) => longhands::${property.ident}::to_computed_value( (*specified_value).clone(), context ), - Initial + DeclaredValue::Initial => longhands::${property.ident}::get_initial_value(), - Inherit => { + DeclaredValue::Inherit => { // This is a bit slow, but this is rare so it shouldn't // matter. // @@ -2538,7 +2550,7 @@ fn cascade_with_cached_declarations(applicable_declarations: &[DeclarationBlock] % endif } % else: - ${property.camel_case}Declaration(_) => { + PropertyDeclaration::${property.camel_case}Declaration(_) => { // Do not allow stylesheets to set derived properties. } % endif @@ -2613,9 +2625,9 @@ pub fn cascade(applicable_declarations: &[DeclarationBlock], macro_rules! get_specified( ($style_struct_getter: ident, $property: ident, $declared_value: expr) => { match *$declared_value { - SpecifiedValue(specified_value) => specified_value, - Initial => longhands::$property::get_initial_value(), - Inherit => inherited_style.$style_struct_getter().$property.clone(), + DeclaredValue::SpecifiedValue(specified_value) => specified_value, + DeclaredValue::Initial => longhands::$property::get_initial_value(), + DeclaredValue::Inherit => inherited_style.$style_struct_getter().$property.clone(), } }; ) @@ -2626,39 +2638,39 @@ pub fn cascade(applicable_declarations: &[DeclarationBlock], // Declarations are stored in reverse source order, we want them in forward order here. for declaration in sub_list.declarations.iter().rev() { match *declaration { - FontSizeDeclaration(ref value) => { + PropertyDeclaration::FontSizeDeclaration(ref value) => { context.font_size = match *value { - SpecifiedValue(specified_value) => computed::compute_Au_with_font_size( + DeclaredValue::SpecifiedValue(specified_value) => computed::compute_Au_with_font_size( specified_value, context.inherited_font_size, context.root_font_size), - Initial => longhands::font_size::get_initial_value(), - Inherit => context.inherited_font_size, + DeclaredValue::Initial => longhands::font_size::get_initial_value(), + DeclaredValue::Inherit => context.inherited_font_size, } } - ColorDeclaration(ref value) => { + PropertyDeclaration::ColorDeclaration(ref value) => { context.color = get_specified!(get_color, color, value); } - DisplayDeclaration(ref value) => { + PropertyDeclaration::DisplayDeclaration(ref value) => { context.display = get_specified!(get_box, display, value); } - PositionDeclaration(ref value) => { + PropertyDeclaration::PositionDeclaration(ref value) => { context.positioned = match get_specified!(get_box, position, value) { - longhands::position::absolute | longhands::position::fixed => true, + longhands::position::T::absolute | longhands::position::T::fixed => true, _ => false, } } - FloatDeclaration(ref value) => { + PropertyDeclaration::FloatDeclaration(ref value) => { context.floated = get_specified!(get_box, float, value) - != longhands::float::none; + != longhands::float::T::none; } - TextDecorationDeclaration(ref value) => { + PropertyDeclaration::TextDecorationDeclaration(ref value) => { context.text_decoration = get_specified!(get_text, text_decoration, value); } % for side in ["top", "right", "bottom", "left"]: - Border${side.capitalize()}StyleDeclaration(ref value) => { + PropertyDeclaration::Border${side.capitalize()}StyleDeclaration(ref value) => { context.border_${side}_present = match get_specified!(get_border, border_${side}_style, value) { - longhands::border_top_style::none | - longhands::border_top_style::hidden => false, + longhands::border_top_style::T::none | + longhands::border_top_style::T::hidden => false, _ => true, }; } @@ -2700,20 +2712,20 @@ pub fn cascade(applicable_declarations: &[DeclarationBlock], % for style_struct in STYLE_STRUCTS: % for property in style_struct.longhands: % if property.derived_from is None: - ${property.camel_case}Declaration(ref declared_value) => { + PropertyDeclaration::${property.camel_case}Declaration(ref declared_value) => { if seen.get_${property.ident}() { continue } seen.set_${property.ident}(); let computed_value = match *declared_value { - SpecifiedValue(ref specified_value) + DeclaredValue::SpecifiedValue(ref specified_value) => longhands::${property.ident}::to_computed_value( (*specified_value).clone(), &context ), - Initial + DeclaredValue::Initial => longhands::${property.ident}::get_initial_value(), - Inherit => { + DeclaredValue::Inherit => { // This is a bit slow, but this is rare so it shouldn't // matter. // @@ -2740,7 +2752,7 @@ pub fn cascade(applicable_declarations: &[DeclarationBlock], % endif } % else: - ${property.camel_case}Declaration(_) => { + PropertyDeclaration::${property.camel_case}Declaration(_) => { // Do not allow stylesheets to set derived properties. } % endif @@ -2824,7 +2836,7 @@ pub mod computed_values { pub use cssparser::RGBA; pub use super::common_types::computed::{ - LengthOrPercentage, LP_Length, LP_Percentage, - LengthOrPercentageOrAuto, LPA_Length, LPA_Percentage, LPA_Auto, - LengthOrPercentageOrNone, LPN_Length, LPN_Percentage, LPN_None}; + LengthOrPercentage, + LengthOrPercentageOrAuto, + LengthOrPercentageOrNone}; } diff --git a/components/style/selector_matching.rs b/components/style/selector_matching.rs index 091d6204886..787209ebc57 100644 --- a/components/style/selector_matching.rs +++ b/components/style/selector_matching.rs @@ -20,26 +20,16 @@ use legacy::PresentationalHintSynthesis; use media_queries::Device; use node::{TElement, TElementAttributes, TNode}; use properties::{PropertyDeclaration, PropertyDeclarationBlock}; -use selectors::{After, AnyLink, AttrDashMatch, AttrEqual}; -use selectors::{AttrExists, AttrIncludes, AttrPrefixMatch}; -use selectors::{AttrSubstringMatch, AttrSuffixMatch, Before, CaseInsensitive, CaseSensitive}; -use selectors::{Checked, Child, ClassSelector, Indeterminate}; -use selectors::{CompoundSelector, Descendant, Disabled, Enabled, FirstChild, FirstOfType}; -use selectors::{Hover, IDSelector, LastChild, LastOfType}; -use selectors::{LaterSibling, LocalName, LocalNameSelector}; -use selectors::{NamespaceSelector, Link, Negation}; -use selectors::{NextSibling, NthChild}; -use selectors::{NthLastChild, NthLastOfType}; -use selectors::{NthOfType, OnlyChild, OnlyOfType, PseudoElement, Root}; -use selectors::{SelectorList, ServoNonzeroBorder, SimpleSelector, Visited}; +use selectors::{CaseSensitivity, Combinator, CompoundSelector, LocalName}; +use selectors::{PseudoElement, SelectorList, SimpleSelector}; use selectors::{get_selector_list_selectors}; use stylesheets::{Stylesheet, iter_stylesheet_media_rules, iter_stylesheet_style_rules}; #[deriving(Clone, PartialEq)] pub enum StylesheetOrigin { - UserAgentOrigin, - AuthorOrigin, - UserOrigin, + UserAgent, + Author, + User, } /// The definition of whitespace per CSS Selectors Level 3 § 4. @@ -232,7 +222,7 @@ impl SelectorMap { match *ss { // TODO(pradeep): Implement case-sensitivity based on the document type and quirks // mode. - IDSelector(ref id) => return Some(id.clone()), + SimpleSelector::IDSelector(ref id) => return Some(id.clone()), _ => {} } } @@ -246,7 +236,7 @@ impl SelectorMap { match *ss { // TODO(pradeep): Implement case-sensitivity based on the document type and quirks // mode. - ClassSelector(ref class) => return Some(class.clone()), + SimpleSelector::ClassSelector(ref class) => return Some(class.clone()), _ => {} } } @@ -258,7 +248,7 @@ impl SelectorMap { let simple_selector_sequence = &rule.selector.simple_selectors; for ss in simple_selector_sequence.iter() { match *ss { - LocalNameSelector(ref name) => { + SimpleSelector::LocalNameSelector(ref name) => { return Some(name.clone()) } _ => {} @@ -314,7 +304,7 @@ impl Stylist { Url::parse(format!("chrome:///{}", filename).as_slice()).unwrap(), None, None, - UserAgentOrigin); + StylesheetOrigin::UserAgent); stylist.add_stylesheet(ua_stylesheet); } stylist @@ -329,17 +319,17 @@ impl Stylist { for stylesheet in self.stylesheets.iter() { let (mut element_map, mut before_map, mut after_map) = match stylesheet.origin { - UserAgentOrigin => ( + StylesheetOrigin::UserAgent => ( &mut self.element_map.user_agent, &mut self.before_map.user_agent, &mut self.after_map.user_agent, ), - AuthorOrigin => ( + StylesheetOrigin::Author => ( &mut self.element_map.author, &mut self.before_map.author, &mut self.after_map.author, ), - UserOrigin => ( + StylesheetOrigin::User => ( &mut self.element_map.user, &mut self.before_map.user, &mut self.after_map.user, @@ -355,8 +345,8 @@ impl Stylist { for selector in $style_rule.selectors.iter() { let map = match selector.pseudo_element { None => &mut element_map, - Some(Before) => &mut before_map, - Some(After) => &mut after_map, + Some(PseudoElement::Before) => &mut before_map, + Some(PseudoElement::After) => &mut after_map, }; map.$priority.insert(Rule { selector: selector.compound_selectors.clone(), @@ -406,7 +396,7 @@ impl Stylist { Url::parse("chrome:///quirks-mode.css").unwrap(), None, None, - UserAgentOrigin)) + StylesheetOrigin::UserAgent)) } pub fn add_stylesheet(&mut self, stylesheet: Stylesheet) { @@ -438,8 +428,8 @@ impl Stylist { let map = match pseudo_element { None => &self.element_map, - Some(Before) => &self.before_map, - Some(After) => &self.after_map, + Some(PseudoElement::Before) => &self.before_map, + Some(PseudoElement::After) => &self.after_map, }; let mut shareable = true; @@ -588,7 +578,7 @@ fn matches_compound_selector<'a,E,N>(selector: &CompoundSelector, -> bool where E: TElement<'a>, N: TNode<'a,E> { match matches_compound_selector_internal(selector, element, parent_bf, shareable) { - Matched => true, + SelectorMatchingResult::Matched => true, _ => false } } @@ -653,7 +643,7 @@ fn can_fast_reject<'a,E,N>(mut selector: &CompoundSelector, where E: TElement<'a>, N: TNode<'a,E> { if !selector.simple_selectors.iter().all(|simple_selector| { matches_simple_selector(simple_selector, element, shareable) }) { - return Some(NotMatchedAndRestartFromClosestLaterSibling); + return Some(SelectorMatchingResult::NotMatchedAndRestartFromClosestLaterSibling); } let bf: &BloomFilter = match *parent_bf { @@ -666,7 +656,7 @@ fn can_fast_reject<'a,E,N>(mut selector: &CompoundSelector, loop { match selector.next { None => break, - Some((ref cs, Descendant)) => selector = &**cs, + Some((ref cs, Combinator::Descendant)) => selector = &**cs, Some((ref cs, _)) => { selector = &**cs; continue; @@ -675,25 +665,25 @@ fn can_fast_reject<'a,E,N>(mut selector: &CompoundSelector, for ss in selector.simple_selectors.iter() { match *ss { - LocalNameSelector(LocalName { ref name, ref lower_name }) => { + SimpleSelector::LocalNameSelector(LocalName { ref name, ref lower_name }) => { if !bf.might_contain(name) && !bf.might_contain(lower_name) { - return Some(NotMatchedGlobally); + return Some(SelectorMatchingResult::NotMatchedGlobally); } }, - NamespaceSelector(ref namespace) => { + SimpleSelector::NamespaceSelector(ref namespace) => { if !bf.might_contain(namespace) { - return Some(NotMatchedGlobally); + return Some(SelectorMatchingResult::NotMatchedGlobally); } }, - IDSelector(ref id) => { + SimpleSelector::IDSelector(ref id) => { if !bf.might_contain(id) { - return Some(NotMatchedGlobally); + return Some(SelectorMatchingResult::NotMatchedGlobally); } }, - ClassSelector(ref class) => { + SimpleSelector::ClassSelector(ref class) => { if !bf.might_contain(class) { - return Some(NotMatchedGlobally); + return Some(SelectorMatchingResult::NotMatchedGlobally); } }, _ => {}, @@ -718,13 +708,13 @@ fn matches_compound_selector_internal<'a,E,N>(selector: &CompoundSelector, }; match selector.next { - None => Matched, + None => SelectorMatchingResult::Matched, Some((ref next_selector, combinator)) => { let (siblings, candidate_not_found) = match combinator { - Child => (false, NotMatchedGlobally), - Descendant => (false, NotMatchedGlobally), - NextSibling => (true, NotMatchedAndRestartFromClosestDescendant), - LaterSibling => (true, NotMatchedAndRestartFromClosestDescendant), + Combinator::Child => (false, SelectorMatchingResult::NotMatchedGlobally), + Combinator::Descendant => (false, SelectorMatchingResult::NotMatchedGlobally), + Combinator::NextSibling => (true, SelectorMatchingResult::NotMatchedAndRestartFromClosestDescendant), + Combinator::LaterSibling => (true, SelectorMatchingResult::NotMatchedAndRestartFromClosestDescendant), }; let mut node = (*element).clone(); loop { @@ -744,25 +734,25 @@ fn matches_compound_selector_internal<'a,E,N>(selector: &CompoundSelector, shareable); match (result, combinator) { // Return the status immediately. - (Matched, _) => return result, - (NotMatchedGlobally, _) => return result, + (SelectorMatchingResult::Matched, _) => return result, + (SelectorMatchingResult::NotMatchedGlobally, _) => return result, // Upgrade the failure status to // NotMatchedAndRestartFromClosestDescendant. - (_, Child) => return NotMatchedAndRestartFromClosestDescendant, + (_, Combinator::Child) => return SelectorMatchingResult::NotMatchedAndRestartFromClosestDescendant, // Return the status directly. - (_, NextSibling) => return result, + (_, Combinator::NextSibling) => return result, // If the failure status is NotMatchedAndRestartFromClosestDescendant - // and combinator is LaterSibling, give up this LaterSibling matching + // and combinator is Combinator::LaterSibling, give up this Combinator::LaterSibling matching // and restart from the closest descendant combinator. - (NotMatchedAndRestartFromClosestDescendant, LaterSibling) => return result, + (SelectorMatchingResult::NotMatchedAndRestartFromClosestDescendant, Combinator::LaterSibling) => return result, - // The Descendant combinator and the status is + // The Combinator::Descendant combinator and the status is // NotMatchedAndRestartFromClosestLaterSibling or // NotMatchedAndRestartFromClosestDescendant, - // or the LaterSibling combinator and the status is + // or the Combinator::LaterSibling combinator and the status is // NotMatchedAndRestartFromClosestDescendant // can continue to matching on the next candidate element. _ => {}, @@ -789,8 +779,8 @@ pub struct CommonStyleAffectingAttributeInfo { } pub enum CommonStyleAffectingAttributeMode { - AttrIsPresentMode(CommonStyleAffectingAttributes), - AttrIsEqualMode(&'static str, CommonStyleAffectingAttributes), + IsPresent(CommonStyleAffectingAttributes), + IsEqual(&'static str, CommonStyleAffectingAttributes), } // NB: This must match the order in `layout::css::matching::CommonStyleAffectingAttributes`. @@ -799,23 +789,23 @@ pub fn common_style_affecting_attributes() -> [CommonStyleAffectingAttributeInfo [ CommonStyleAffectingAttributeInfo { atom: atom!("hidden"), - mode: AttrIsPresentMode(HIDDEN_ATTRIBUTE), + mode: CommonStyleAffectingAttributeMode::IsPresent(HIDDEN_ATTRIBUTE), }, CommonStyleAffectingAttributeInfo { atom: atom!("nowrap"), - mode: AttrIsPresentMode(NO_WRAP_ATTRIBUTE), + mode: CommonStyleAffectingAttributeMode::IsPresent(NO_WRAP_ATTRIBUTE), }, CommonStyleAffectingAttributeInfo { atom: atom!("align"), - mode: AttrIsEqualMode("left", ALIGN_LEFT_ATTRIBUTE), + mode: CommonStyleAffectingAttributeMode::IsEqual("left", ALIGN_LEFT_ATTRIBUTE), }, CommonStyleAffectingAttributeInfo { atom: atom!("align"), - mode: AttrIsEqualMode("center", ALIGN_CENTER_ATTRIBUTE), + mode: CommonStyleAffectingAttributeMode::IsEqual("center", ALIGN_CENTER_ATTRIBUTE), }, CommonStyleAffectingAttributeInfo { atom: atom!("align"), - mode: AttrIsEqualMode("right", ALIGN_RIGHT_ATTRIBUTE), + mode: CommonStyleAffectingAttributeMode::IsEqual("right", ALIGN_RIGHT_ATTRIBUTE), } ] } @@ -840,48 +830,48 @@ pub fn matches_simple_selector<'a,E,N>(selector: &SimpleSelector, -> bool where E: TElement<'a>, N: TNode<'a,E> { match *selector { - LocalNameSelector(LocalName { ref name, ref lower_name }) => { + SimpleSelector::LocalNameSelector(LocalName { ref name, ref lower_name }) => { let name = if element.is_html_element_in_html_document() { lower_name } else { name }; let element = element.as_element(); element.get_local_name() == name } - NamespaceSelector(ref namespace) => { + SimpleSelector::NamespaceSelector(ref namespace) => { let element = element.as_element(); element.get_namespace() == namespace } // TODO: case-sensitivity depends on the document type and quirks mode - IDSelector(ref id) => { + SimpleSelector::IDSelector(ref id) => { *shareable = false; let element = element.as_element(); element.get_id().map_or(false, |attr| { attr == *id }) } - ClassSelector(ref class) => { + SimpleSelector::ClassSelector(ref class) => { let element = element.as_element(); element.has_class(class) } - AttrExists(ref attr) => { + SimpleSelector::AttrExists(ref attr) => { // NB(pcwalton): If you update this, remember to update the corresponding list in // `can_share_style_with()` as well. if common_style_affecting_attributes().iter().all(|common_attr_info| { !(common_attr_info.atom == attr.name && match common_attr_info.mode { - AttrIsPresentMode(_) => true, - AttrIsEqualMode(..) => false, + CommonStyleAffectingAttributeMode::IsPresent(_) => true, + CommonStyleAffectingAttributeMode::IsEqual(..) => false, }) }) { *shareable = false; } element.match_attr(attr, |_| true) } - AttrEqual(ref attr, ref value, case_sensitivity) => { + SimpleSelector::AttrEqual(ref attr, ref value, case_sensitivity) => { if value.as_slice() != "DIR" && common_style_affecting_attributes().iter().all(|common_attr_info| { !(common_attr_info.atom == attr.name && match common_attr_info.mode { - AttrIsEqualMode(target_value, _) => target_value == value.as_slice(), - AttrIsPresentMode(_) => false, + CommonStyleAffectingAttributeMode::IsEqual(target_value, _) => target_value == value.as_slice(), + CommonStyleAffectingAttributeMode::IsPresent(_) => false, }) }) { // FIXME(pcwalton): Remove once we start actually supporting RTL text. This is in @@ -890,56 +880,56 @@ pub fn matches_simple_selector<'a,E,N>(selector: &SimpleSelector, } element.match_attr(attr, |attr_value| { match case_sensitivity { - CaseSensitive => attr_value == value.as_slice(), - CaseInsensitive => attr_value.eq_ignore_ascii_case(value.as_slice()), + CaseSensitivity::CaseSensitive => attr_value == value.as_slice(), + CaseSensitivity::CaseInsensitive => attr_value.eq_ignore_ascii_case(value.as_slice()), } }) } - AttrIncludes(ref attr, ref value) => { + SimpleSelector::AttrIncludes(ref attr, ref value) => { *shareable = false; element.match_attr(attr, |attr_value| { attr_value.split(SELECTOR_WHITESPACE).any(|v| v == value.as_slice()) }) } - AttrDashMatch(ref attr, ref value, ref dashing_value) => { + SimpleSelector::AttrDashMatch(ref attr, ref value, ref dashing_value) => { *shareable = false; element.match_attr(attr, |attr_value| { attr_value == value.as_slice() || attr_value.starts_with(dashing_value.as_slice()) }) } - AttrPrefixMatch(ref attr, ref value) => { + SimpleSelector::AttrPrefixMatch(ref attr, ref value) => { *shareable = false; element.match_attr(attr, |attr_value| { attr_value.starts_with(value.as_slice()) }) } - AttrSubstringMatch(ref attr, ref value) => { + SimpleSelector::AttrSubstringMatch(ref attr, ref value) => { *shareable = false; element.match_attr(attr, |attr_value| { attr_value.contains(value.as_slice()) }) } - AttrSuffixMatch(ref attr, ref value) => { + SimpleSelector::AttrSuffixMatch(ref attr, ref value) => { *shareable = false; element.match_attr(attr, |attr_value| { attr_value.ends_with(value.as_slice()) }) } - AnyLink => { + SimpleSelector::AnyLink => { *shareable = false; let element = element.as_element(); element.get_link().is_some() } - Link => { + SimpleSelector::Link => { let elem = element.as_element(); match elem.get_link() { Some(url) => !url_is_visited(url), None => false, } } - Visited => { + SimpleSelector::Visited => { // NB(pcwalton): When we actually start supporting visited links, remember to update // `can_share_style_with`. let elem = element.as_element(); @@ -949,91 +939,91 @@ pub fn matches_simple_selector<'a,E,N>(selector: &SimpleSelector, } } - Hover => { + SimpleSelector::Hover => { *shareable = false; let elem = element.as_element(); elem.get_hover_state() }, // http://www.whatwg.org/html/#selector-disabled - Disabled => { + SimpleSelector::Disabled => { *shareable = false; let elem = element.as_element(); elem.get_disabled_state() }, // http://www.whatwg.org/html/#selector-enabled - Enabled => { + SimpleSelector::Enabled => { *shareable = false; let elem = element.as_element(); elem.get_enabled_state() }, // https://html.spec.whatwg.org/multipage/scripting.html#selector-checked - Checked => { + SimpleSelector::Checked => { *shareable = false; let elem = element.as_element(); elem.get_checked_state() } // https://html.spec.whatwg.org/multipage/scripting.html#selector-indeterminate - Indeterminate => { + SimpleSelector::Indeterminate => { *shareable = false; let elem = element.as_element(); elem.get_indeterminate_state() } - FirstChild => { + SimpleSelector::FirstChild => { *shareable = false; matches_first_child(element) } - LastChild => { + SimpleSelector::LastChild => { *shareable = false; matches_last_child(element) } - OnlyChild => { + SimpleSelector::OnlyChild => { *shareable = false; matches_first_child(element) && matches_last_child(element) } - Root => { + SimpleSelector::Root => { *shareable = false; matches_root(element) } - NthChild(a, b) => { + SimpleSelector::NthChild(a, b) => { *shareable = false; matches_generic_nth_child(element, a, b, false, false) } - NthLastChild(a, b) => { + SimpleSelector::NthLastChild(a, b) => { *shareable = false; matches_generic_nth_child(element, a, b, false, true) } - NthOfType(a, b) => { + SimpleSelector::NthOfType(a, b) => { *shareable = false; matches_generic_nth_child(element, a, b, true, false) } - NthLastOfType(a, b) => { + SimpleSelector::NthLastOfType(a, b) => { *shareable = false; matches_generic_nth_child(element, a, b, true, true) } - FirstOfType => { + SimpleSelector::FirstOfType => { *shareable = false; matches_generic_nth_child(element, 0, 1, true, false) } - LastOfType => { + SimpleSelector::LastOfType => { *shareable = false; matches_generic_nth_child(element, 0, 1, true, true) } - OnlyOfType => { + SimpleSelector::OnlyOfType => { *shareable = false; matches_generic_nth_child(element, 0, 1, true, false) && matches_generic_nth_child(element, 0, 1, true, true) } - ServoNonzeroBorder => { + SimpleSelector::ServoNonzeroBorder => { *shareable = false; let elem = element.as_element(); elem.has_nonzero_border() } - Negation(ref negated) => { + SimpleSelector::Negation(ref negated) => { *shareable = false; !negated.iter().all(|s| matches_simple_selector(s, element, shareable)) }, @@ -1186,13 +1176,13 @@ mod tests { fn get_mock_rules(css_selectors: &[&str]) -> Vec<Vec<Rule>> { use namespaces::NamespaceMap; use selectors::{ParserContext, parse_selector_list}; - use selector_matching::AuthorOrigin; + use selector_matching::StylesheetOrigin; use cssparser::tokenize; let namespaces = NamespaceMap::new(); css_selectors.iter().enumerate().map(|(i, selectors)| { let context = ParserContext { - origin: AuthorOrigin, + origin: StylesheetOrigin::Author, }; parse_selector_list(&context, tokenize(*selectors).map(|(c, _)| c), &namespaces) .unwrap().into_iter().map(|s| { diff --git a/components/style/selectors.rs b/components/style/selectors.rs index 5217ea2828a..52c84f94569 100644 --- a/components/style/selectors.rs +++ b/components/style/selectors.rs @@ -9,7 +9,7 @@ use sync::Arc; use cssparser::ast::*; use cssparser::{tokenize, parse_nth}; -use selector_matching::{StylesheetOrigin, UserAgentOrigin}; +use selector_matching::StylesheetOrigin; use string_cache::{Atom, Namespace}; use namespaces::NamespaceMap; @@ -114,8 +114,8 @@ pub struct AttrSelector { #[deriving(Eq, PartialEq, Clone, Hash)] pub enum NamespaceConstraint { - AnyNamespace, - SpecificNamespace(Namespace), + Any, + Specific(Namespace), } @@ -162,21 +162,37 @@ fn compute_specificity(mut selector: &CompoundSelector, specificity: &mut Specificity) { for simple_selector in simple_selectors.iter() { match simple_selector { - &LocalNameSelector(..) => specificity.element_selectors += 1, - &IDSelector(..) => specificity.id_selectors += 1, - &ClassSelector(..) - | &AttrExists(..) | &AttrEqual(..) | &AttrIncludes(..) | &AttrDashMatch(..) - | &AttrPrefixMatch(..) | &AttrSubstringMatch(..) | &AttrSuffixMatch(..) - | &AnyLink | &Link | &Visited | &Hover | &Disabled | &Enabled - | &FirstChild | &LastChild | &OnlyChild | &Root | &Checked | &Indeterminate -// | &Empty | &Lang(*) - | &NthChild(..) | &NthLastChild(..) - | &NthOfType(..) | &NthLastOfType(..) - | &FirstOfType | &LastOfType | &OnlyOfType | &ServoNonzeroBorder - => specificity.class_like_selectors += 1, - &NamespaceSelector(..) => (), - &Negation(ref negated) - => simple_selectors_specificity(negated.as_slice(), specificity), + &SimpleSelector::LocalNameSelector(..) => + specificity.element_selectors += 1, + &SimpleSelector::IDSelector(..) => + specificity.id_selectors += 1, + &SimpleSelector::ClassSelector(..) | + &SimpleSelector::AttrExists(..) | + &SimpleSelector::AttrEqual(..) | + &SimpleSelector::AttrIncludes(..) | + &SimpleSelector::AttrDashMatch(..) | + &SimpleSelector::AttrPrefixMatch(..) | + &SimpleSelector::AttrSubstringMatch(..) | + &SimpleSelector::AttrSuffixMatch(..) | + &SimpleSelector::AnyLink | &SimpleSelector::Link | + &SimpleSelector::Visited | &SimpleSelector::Hover | + &SimpleSelector::Disabled | &SimpleSelector::Enabled | + &SimpleSelector::FirstChild | &SimpleSelector::LastChild | + &SimpleSelector::OnlyChild | &SimpleSelector::Root | + &SimpleSelector::Checked | + &SimpleSelector::Indeterminate | +// &SimpleSelector::Empty | &SimpleSelector::Lang(*) | + &SimpleSelector::NthChild(..) | + &SimpleSelector::NthLastChild(..) | + &SimpleSelector::NthOfType(..) | + &SimpleSelector::NthLastOfType(..) | + &SimpleSelector::FirstOfType | &SimpleSelector::LastOfType | + &SimpleSelector::OnlyOfType | + &SimpleSelector::ServoNonzeroBorder => + specificity.class_like_selectors += 1, + &SimpleSelector::NamespaceSelector(..) => (), + &SimpleSelector::Negation(ref negated) => + simple_selectors_specificity(negated.as_slice(), specificity), } } } @@ -201,12 +217,14 @@ fn parse_type_selector<I: Iterator<ComponentValue>>( Some((namespace, local_name)) => { let mut simple_selectors = vec!(); match namespace { - SpecificNamespace(ns) => simple_selectors.push(NamespaceSelector(ns)), - AnyNamespace => (), + NamespaceConstraint::Specific(ns) => { + simple_selectors.push(SimpleSelector::NamespaceSelector(ns)) + }, + NamespaceConstraint::Any => (), } match local_name { Some(name) => { - simple_selectors.push(LocalNameSelector(LocalName { + simple_selectors.push(SimpleSelector::LocalNameSelector(LocalName { name: Atom::from_slice(name.as_slice()), lower_name: Atom::from_slice(name.into_ascii_lower().as_slice()) })) @@ -220,8 +238,8 @@ fn parse_type_selector<I: Iterator<ComponentValue>>( enum SimpleSelectorParseResult { - SimpleSelectorResult(SimpleSelector), - PseudoElementResult(PseudoElement), + SimpleSelector(SimpleSelector), + PseudoElement(PseudoElement), } @@ -233,8 +251,8 @@ fn parse_qualified_name<I: Iterator<ComponentValue>>( -> Result<Option<(NamespaceConstraint, Option<String>)>, ()> { let default_namespace = |local_name| { let namespace = match namespaces.default { - Some(ref ns) => SpecificNamespace(ns.clone()), - None => AnyNamespace, + Some(ref ns) => NamespaceConstraint::Specific(ns.clone()), + None => NamespaceConstraint::Any, }; Ok(Some((namespace, local_name))) }; @@ -264,24 +282,24 @@ fn parse_qualified_name<I: Iterator<ComponentValue>>( None => return Err(()), // Undeclared namespace prefix Some(ref ns) => (*ns).clone(), }; - explicit_namespace(iter, SpecificNamespace(namespace)) + explicit_namespace(iter, NamespaceConstraint::Specific(namespace)) }, _ if in_attr_selector => Ok(Some( - (SpecificNamespace(ns!("")), Some(value)))), + (NamespaceConstraint::Specific(ns!("")), Some(value)))), _ => default_namespace(Some(value)), } }, Some(&Delim('*')) => { iter.next(); // Consume '*' match iter.peek() { - Some(&Delim('|')) => explicit_namespace(iter, AnyNamespace), + Some(&Delim('|')) => explicit_namespace(iter, NamespaceConstraint::Any), _ => { if !in_attr_selector { default_namespace(None) } else { Err(()) } }, } }, - Some(&Delim('|')) => explicit_namespace(iter, SpecificNamespace(ns!(""))), + Some(&Delim('|')) => explicit_namespace(iter, NamespaceConstraint::Specific(ns!(""))), _ => Ok(None), } } @@ -302,20 +320,37 @@ fn parse_attribute_selector(content: Vec<ComponentValue>, namespaces: &Namespace skip_whitespace(iter); // TODO: deal with empty value or value containing whitespace (see spec) let result = match iter.next() { - None => AttrExists(attr), // [foo] - Some(Delim('=')) => AttrEqual( - attr, try!(parse_attribute_value(iter)), - try!(parse_attribute_flags(iter))), // [foo=bar] - Some(IncludeMatch) => AttrIncludes(attr, try!(parse_attribute_value(iter))), // [foo~=bar] + // [foo] + None => SimpleSelector::AttrExists(attr), + + // [foo=bar] + Some(Delim('=')) => + SimpleSelector::AttrEqual(attr, try!(parse_attribute_value(iter)), + try!(parse_attribute_flags(iter))), + + // [foo~=bar] + Some(IncludeMatch) => + SimpleSelector::AttrIncludes(attr, try!(parse_attribute_value(iter))), + + // [foo|=bar] Some(DashMatch) => { let value = try!(parse_attribute_value(iter)); let dashing_value = format!("{}-", value); - AttrDashMatch(attr, value, dashing_value) // [foo|=bar] + SimpleSelector::AttrDashMatch(attr, value, dashing_value) }, - Some(PrefixMatch) => AttrPrefixMatch(attr, try!(parse_attribute_value(iter))), // [foo^=bar] + + // [foo^=bar] + Some(PrefixMatch) => + SimpleSelector::AttrPrefixMatch(attr, try!(parse_attribute_value(iter))), + // [foo*=bar] - Some(SubstringMatch) => AttrSubstringMatch(attr, try!(parse_attribute_value(iter))), - Some(SuffixMatch) => AttrSuffixMatch(attr, try!(parse_attribute_value(iter))), // [foo$=bar] + Some(SubstringMatch) => + SimpleSelector::AttrSubstringMatch(attr, try!(parse_attribute_value(iter))), + + // [foo$=bar] + Some(SuffixMatch) => + SimpleSelector::AttrSuffixMatch(attr, try!(parse_attribute_value(iter))), + _ => return Err(()) }; skip_whitespace(iter); @@ -336,9 +371,9 @@ fn parse_attribute_flags<I: Iterator<ComponentValue>>(iter: &mut Iter<I>) -> Result<CaseSensitivity, ()> { skip_whitespace(iter); match iter.next() { - None => Ok(CaseSensitive), + None => Ok(CaseSensitivity::CaseSensitive), Some(Ident(ref value)) if value.as_slice().eq_ignore_ascii_case("i") - => Ok(CaseInsensitive), + => Ok(CaseSensitivity::CaseInsensitive), _ => Err(()) } } @@ -388,11 +423,11 @@ fn parse_selector<I>(context: &ParserContext, iter: &mut Iter<I>, namespaces: &N let combinator = match iter.peek() { None => break, // EOF Some(&Comma) => break, - Some(&Delim('>')) => { iter.next(); Child }, - Some(&Delim('+')) => { iter.next(); NextSibling }, - Some(&Delim('~')) => { iter.next(); LaterSibling }, + Some(&Delim('>')) => { iter.next(); Combinator::Child }, + Some(&Delim('+')) => { iter.next(); Combinator::NextSibling }, + Some(&Delim('~')) => { iter.next(); Combinator::LaterSibling }, Some(_) => { - if any_whitespace { Descendant } + if any_whitespace { Combinator::Descendant } else { return Err(()) } } }; @@ -417,14 +452,14 @@ fn parse_negation(context: &ParserContext, -> Result<SimpleSelector,()> { let iter = &mut arguments.into_iter().peekable(); match try!(parse_type_selector(iter, namespaces)) { - Some(type_selector) => Ok(Negation(type_selector)), + Some(type_selector) => Ok(SimpleSelector::Negation(type_selector)), None => { match try!(parse_one_simple_selector(context, iter, namespaces, /* inside_negation = */ true)) { - Some(SimpleSelectorResult(simple_selector)) => { - Ok(Negation(vec![simple_selector])) + Some(SimpleSelectorParseResult::SimpleSelector(simple_selector)) => { + Ok(SimpleSelector::Negation(vec![simple_selector])) } _ => Err(()) } @@ -455,8 +490,8 @@ fn parse_simple_selectors<I>(context: &ParserContext, namespaces, /* inside_negation = */ false)) { None => break, - Some(SimpleSelectorResult(s)) => { simple_selectors.push(s); empty = false }, - Some(PseudoElementResult(p)) => { pseudo_element = Some(p); empty = false; break }, + Some(SimpleSelectorParseResult::SimpleSelector(s)) => { simple_selectors.push(s); empty = false }, + Some(SimpleSelectorParseResult::PseudoElement(p)) => { pseudo_element = Some(p); empty = false; break }, } } if empty { @@ -475,10 +510,10 @@ fn parse_functional_pseudo_class(context: &ParserContext, -> Result<SimpleSelector,()> { match name.as_slice().to_ascii_lower().as_slice() { // "lang" => parse_lang(arguments), - "nth-child" => parse_nth(arguments.as_slice()).map(|(a, b)| NthChild(a, b)), - "nth-last-child" => parse_nth(arguments.as_slice()).map(|(a, b)| NthLastChild(a, b)), - "nth-of-type" => parse_nth(arguments.as_slice()).map(|(a, b)| NthOfType(a, b)), - "nth-last-of-type" => parse_nth(arguments.as_slice()).map(|(a, b)| NthLastOfType(a, b)), + "nth-child" => parse_nth(arguments.as_slice()).map(|(a, b)| SimpleSelector::NthChild(a, b)), + "nth-last-child" => parse_nth(arguments.as_slice()).map(|(a, b)| SimpleSelector::NthLastChild(a, b)), + "nth-of-type" => parse_nth(arguments.as_slice()).map(|(a, b)| SimpleSelector::NthOfType(a, b)), + "nth-last-of-type" => parse_nth(arguments.as_slice()).map(|(a, b)| SimpleSelector::NthLastOfType(a, b)), "not" => { if inside_negation { Err(()) @@ -503,21 +538,21 @@ fn parse_one_simple_selector<I>(context: &ParserContext, where I: Iterator<ComponentValue> { match iter.peek() { Some(&IDHash(_)) => match iter.next() { - Some(IDHash(id)) => Ok(Some(SimpleSelectorResult( - IDSelector(Atom::from_slice(id.as_slice()))))), + Some(IDHash(id)) => Ok(Some(SimpleSelectorParseResult::SimpleSelector( + SimpleSelector::IDSelector(Atom::from_slice(id.as_slice()))))), _ => panic!("Implementation error, this should not happen."), }, Some(&Delim('.')) => { iter.next(); match iter.next() { - Some(Ident(class)) => Ok(Some(SimpleSelectorResult( - ClassSelector(Atom::from_slice(class.as_slice()))))), + Some(Ident(class)) => Ok(Some(SimpleSelectorParseResult::SimpleSelector( + SimpleSelector::ClassSelector(Atom::from_slice(class.as_slice()))))), _ => Err(()), } } Some(&SquareBracketBlock(_)) => match iter.next() { Some(SquareBracketBlock(content)) - => Ok(Some(SimpleSelectorResult(try!(parse_attribute_selector(content, namespaces))))), + => Ok(Some(SimpleSelectorParseResult::SimpleSelector(try!(parse_attribute_selector(content, namespaces))))), _ => panic!("Implementation error, this should not happen."), }, Some(&Colon) => { @@ -528,18 +563,18 @@ fn parse_one_simple_selector<I>(context: &ParserContext, match name.as_slice().to_ascii_lower().as_slice() { // Supported CSS 2.1 pseudo-elements only. // ** Do not add to this list! ** - "before" => Ok(Some(PseudoElementResult(Before))), - "after" => Ok(Some(PseudoElementResult(After))), -// "first-line" => PseudoElementResult(FirstLine), -// "first-letter" => PseudoElementResult(FirstLetter), + "before" => Ok(Some(SimpleSelectorParseResult::PseudoElement(PseudoElement::Before))), + "after" => Ok(Some(SimpleSelectorParseResult::PseudoElement(PseudoElement::After))), +// "first-line" => SimpleSelectorParseResult::PseudoElement(FirstLine), +// "first-letter" => SimpleSelectorParseResult::PseudoElement(FirstLetter), _ => Err(()) } }, - Ok(result) => Ok(Some(SimpleSelectorResult(result))), + Ok(result) => Ok(Some(SimpleSelectorParseResult::SimpleSelector(result))), }, Some(Function(name, arguments)) => { - Ok(Some(SimpleSelectorResult(try!(parse_functional_pseudo_class( + Ok(Some(SimpleSelectorParseResult::SimpleSelector(try!(parse_functional_pseudo_class( context, name, arguments, @@ -549,7 +584,7 @@ fn parse_one_simple_selector<I>(context: &ParserContext, Some(Colon) => { match iter.next() { Some(Ident(name)) - => Ok(Some(PseudoElementResult(try!(parse_pseudo_element(name))))), + => Ok(Some(SimpleSelectorParseResult::PseudoElement(try!(parse_pseudo_element(name))))), _ => Err(()), } } @@ -562,23 +597,23 @@ fn parse_one_simple_selector<I>(context: &ParserContext, fn parse_simple_pseudo_class(context: &ParserContext, name: &str) -> Result<SimpleSelector,()> { match name.to_ascii_lower().as_slice() { - "any-link" => Ok(AnyLink), - "link" => Ok(Link), - "visited" => Ok(Visited), - "hover" => Ok(Hover), - "disabled" => Ok(Disabled), - "enabled" => Ok(Enabled), - "checked" => Ok(Checked), - "indeterminate" => Ok(Indeterminate), - "first-child" => Ok(FirstChild), - "last-child" => Ok(LastChild), - "only-child" => Ok(OnlyChild), - "root" => Ok(Root), - "first-of-type" => Ok(FirstOfType), - "last-of-type" => Ok(LastOfType), - "only-of-type" => Ok(OnlyOfType), - "-servo-nonzero-border" if context.origin == UserAgentOrigin => Ok(ServoNonzeroBorder), -// "empty" => Ok(Empty), + "any-link" => Ok(SimpleSelector::AnyLink), + "link" => Ok(SimpleSelector::Link), + "visited" => Ok(SimpleSelector::Visited), + "hover" => Ok(SimpleSelector::Hover), + "disabled" => Ok(SimpleSelector::Disabled), + "enabled" => Ok(SimpleSelector::Enabled), + "checked" => Ok(SimpleSelector::Checked), + "indeterminate" => Ok(SimpleSelector::Indeterminate), + "first-child" => Ok(SimpleSelector::FirstChild), + "last-child" => Ok(SimpleSelector::LastChild), + "only-child" => Ok(SimpleSelector::OnlyChild), + "root" => Ok(SimpleSelector::Root), + "first-of-type" => Ok(SimpleSelector::FirstOfType), + "last-of-type" => Ok(SimpleSelector::LastOfType), + "only-of-type" => Ok(SimpleSelector::OnlyOfType), + "-servo-nonzero-border" if context.origin == StylesheetOrigin::UserAgent => Ok(SimpleSelector::ServoNonzeroBorder), +// "empty" => Ok(Empty), _ => Err(()) } } @@ -586,8 +621,8 @@ fn parse_simple_pseudo_class(context: &ParserContext, name: &str) -> Result<Simp fn parse_pseudo_element(name: String) -> Result<PseudoElement, ()> { match name.as_slice().to_ascii_lower().as_slice() { // All supported pseudo-elements - "before" => Ok(Before), - "after" => Ok(After), + "before" => Ok(PseudoElement::Before), + "after" => Ok(PseudoElement::After), // "first-line" => Some(FirstLine), // "first-letter" => Some(FirstLetter), _ => Err(()) @@ -634,9 +669,11 @@ mod tests { use sync::Arc; use cssparser; use namespaces::NamespaceMap; - use selector_matching::AuthorOrigin; + use selector_matching::StylesheetOrigin; use string_cache::Atom; use super::*; + use super::SimpleSelector::*; + use super::PseudoElement::*; fn parse(input: &str) -> Result<Vec<Selector>, ()> { parse_ns(input, &NamespaceMap::new()) @@ -644,7 +681,7 @@ mod tests { fn parse_ns(input: &str, namespaces: &NamespaceMap) -> Result<Vec<Selector>, ()> { let context = ParserContext { - origin: AuthorOrigin, + origin: StylesheetOrigin::Author, }; parse_selector_list(&context, cssparser::tokenize(input).map(|(v, _)| v), namespaces) } @@ -658,7 +695,7 @@ mod tests { assert!(parse("") == Err(())) assert!(parse("EeÉ") == Ok(vec!(Selector { compound_selectors: Arc::new(CompoundSelector { - simple_selectors: vec!(LocalNameSelector(LocalName { + simple_selectors: vec!(SimpleSelector::LocalNameSelector(LocalName { name: Atom::from_slice("EeÉ"), lower_name: Atom::from_slice("eeÉ") })), next: None, @@ -668,7 +705,7 @@ mod tests { }))) assert!(parse(".foo") == Ok(vec!(Selector { compound_selectors: Arc::new(CompoundSelector { - simple_selectors: vec!(ClassSelector(Atom::from_slice("foo"))), + simple_selectors: vec!(SimpleSelector::ClassSelector(Atom::from_slice("foo"))), next: None, }), pseudo_element: None, @@ -676,7 +713,7 @@ mod tests { }))) assert!(parse("#bar") == Ok(vec!(Selector { compound_selectors: Arc::new(CompoundSelector { - simple_selectors: vec!(IDSelector(Atom::from_slice("bar"))), + simple_selectors: vec!(SimpleSelector::IDSelector(Atom::from_slice("bar"))), next: None, }), pseudo_element: None, @@ -684,11 +721,11 @@ mod tests { }))) assert!(parse("e.foo#bar") == Ok(vec!(Selector { compound_selectors: Arc::new(CompoundSelector { - simple_selectors: vec!(LocalNameSelector(LocalName { + simple_selectors: vec!(SimpleSelector::LocalNameSelector(LocalName { name: Atom::from_slice("e"), lower_name: Atom::from_slice("e") }), - ClassSelector(Atom::from_slice("foo")), - IDSelector(Atom::from_slice("bar"))), + SimpleSelector::ClassSelector(Atom::from_slice("foo")), + SimpleSelector::IDSelector(Atom::from_slice("bar"))), next: None, }), pseudo_element: None, @@ -698,12 +735,12 @@ mod tests { compound_selectors: Arc::new(CompoundSelector { simple_selectors: vec!(IDSelector(Atom::from_slice("bar"))), next: Some((box CompoundSelector { - simple_selectors: vec!(LocalNameSelector(LocalName { + simple_selectors: vec!(SimpleSelector::LocalNameSelector(LocalName { name: Atom::from_slice("e"), lower_name: Atom::from_slice("e") }), - ClassSelector(Atom::from_slice("foo"))), + SimpleSelector::ClassSelector(Atom::from_slice("foo"))), next: None, - }, Descendant)), + }, Combinator::Descendant)), }), pseudo_element: None, specificity: specificity(1, 1, 1), @@ -716,7 +753,7 @@ mod tests { simple_selectors: vec!(AttrExists(AttrSelector { name: Atom::from_slice("Foo"), lower_name: Atom::from_slice("foo"), - namespace: SpecificNamespace(ns!("")), + namespace: NamespaceConstraint::Specific(ns!("")), })), next: None, }), @@ -731,7 +768,7 @@ mod tests { simple_selectors: vec!(AttrExists(AttrSelector { name: Atom::from_slice("Foo"), lower_name: Atom::from_slice("foo"), - namespace: SpecificNamespace(ns!("")), + namespace: NamespaceConstraint::Specific(ns!("")), })), next: None, }), @@ -769,7 +806,7 @@ mod tests { name: atom!("div"), lower_name: atom!("div") })), next: None, - }, Descendant)), + }, Combinator::Descendant)), }), pseudo_element: Some(After), specificity: specificity(0, 0, 2), diff --git a/components/style/stylesheets.rs b/components/style/stylesheets.rs index 824172af037..b271e4e77be 100644 --- a/components/style/stylesheets.rs +++ b/components/style/stylesheets.rs @@ -28,9 +28,9 @@ pub struct Stylesheet { pub enum CSSRule { - CSSStyleRule(StyleRule), - CSSMediaRule(MediaRule), - CSSFontFaceRule(FontFaceRule), + Style(StyleRule), + Media(MediaRule), + FontFace(FontFaceRule), } @@ -82,11 +82,11 @@ impl Stylesheet { for rule in ErrorLoggerIterator(parse_stylesheet_rules(tokenize(css))) { let next_state; // Unitialized to force each branch to set it. match rule { - QualifiedRule_(rule) => { + Rule::QualifiedRule(rule) => { next_state = STATE_BODY; parse_style_rule(&parser_context, rule, &mut rules, &namespaces, &base_url) }, - AtRule_(rule) => { + Rule::AtRule(rule) => { let lower_name = rule.name.as_slice().to_ascii_lower(); match lower_name.as_slice() { "charset" => { @@ -170,7 +170,7 @@ pub fn parse_style_rule(context: &ParserContext, // FIXME: avoid doing this for valid selectors let serialized = prelude.iter().to_css(); match selectors::parse_selector_list(context, prelude.into_iter(), namespaces) { - Ok(selectors) => parent_rules.push(CSSStyleRule(StyleRule{ + Ok(selectors) => parent_rules.push(CSSRule::Style(StyleRule{ selectors: selectors, declarations: properties::parse_property_declaration_list(block.into_iter(), base_url) })), @@ -183,11 +183,11 @@ pub fn iter_style_rules<'a>(rules: &[CSSRule], device: &media_queries::Device, callback: |&StyleRule|) { for rule in rules.iter() { match *rule { - CSSStyleRule(ref rule) => callback(rule), - CSSMediaRule(ref rule) => if rule.media_queries.evaluate(device) { + CSSRule::Style(ref rule) => callback(rule), + CSSRule::Media(ref rule) => if rule.media_queries.evaluate(device) { iter_style_rules(rule.rules.as_slice(), device, |s| callback(s)) }, - CSSFontFaceRule(_) => {}, + CSSRule::FontFace(_) => {}, } } } @@ -195,7 +195,7 @@ pub fn iter_style_rules<'a>(rules: &[CSSRule], device: &media_queries::Device, pub fn iter_stylesheet_media_rules(stylesheet: &Stylesheet, callback: |&MediaRule|) { for rule in stylesheet.rules.iter() { match *rule { - CSSMediaRule(ref rule) => callback(rule), + CSSRule::Media(ref rule) => callback(rule), _ => {} } } diff --git a/components/util/Cargo.toml b/components/util/Cargo.toml index 331fd2fb840..e7faaebee97 100644 --- a/components/util/Cargo.toml +++ b/components/util/Cargo.toml @@ -27,3 +27,6 @@ git = "https://github.com/servo/string-cache" [dependencies.url] git = "https://github.com/servo/rust-url" + +[dependencies.time] +git = "https://github.com/rust-lang/time" diff --git a/components/util/bloom.rs b/components/util/bloom.rs index fe56ac2c762..2bed80e9e13 100644 --- a/components/util/bloom.rs +++ b/components/util/bloom.rs @@ -169,6 +169,7 @@ pub trait BloomHash { } impl BloomHash for int { + #[allow(exceeding_bitshifts)] #[inline] fn bloom_hash(&self) -> u32 { ((*self >> 32) ^ *self) as u32 @@ -176,6 +177,7 @@ impl BloomHash for int { } impl BloomHash for uint { + #[allow(exceeding_bitshifts)] #[inline] fn bloom_hash(&self) -> u32 { ((*self >> 32) ^ *self) as u32 diff --git a/components/util/geometry.rs b/components/util/geometry.rs index 1dfa1fe0f9d..8be6b50dbee 100644 --- a/components/util/geometry.rs +++ b/components/util/geometry.rs @@ -10,7 +10,7 @@ use geom::size::Size2D; use serialize::{Encodable, Encoder}; use std::default::Default; use std::i32; -use std::num::{NumCast, Zero}; +use std::num::{Float, NumCast, Zero}; use std::fmt; // Units for use with geom::length and geom::scale_factor. diff --git a/components/util/memory.rs b/components/util/memory.rs index 3dd894ebcf3..ce7933714c7 100644 --- a/components/util/memory.rs +++ b/components/util/memory.rs @@ -28,9 +28,9 @@ impl MemoryProfilerChan { pub enum MemoryProfilerMsg { /// Message used to force print the memory profiling metrics. - PrintMsg, + Print, /// Tells the memory profiler to shut down. - ExitMsg, + Exit, } pub struct MemoryProfiler { @@ -47,7 +47,7 @@ impl MemoryProfiler { spawn_named("Memory profiler timer", proc() { loop { sleep(period); - if chan.send_opt(PrintMsg).is_err() { + if chan.send_opt(MemoryProfilerMsg::Print).is_err() { break; } } @@ -64,7 +64,7 @@ impl MemoryProfiler { spawn_named("Memory profiler", proc() { loop { match port.recv_opt() { - Err(_) | Ok(ExitMsg) => break, + Err(_) | Ok(MemoryProfilerMsg::Exit) => break, _ => {} } } @@ -96,11 +96,11 @@ impl MemoryProfiler { fn handle_msg(&self, msg: MemoryProfilerMsg) -> bool { match msg { - PrintMsg => { + MemoryProfilerMsg::Print => { self.handle_print_msg(); true }, - ExitMsg => false + MemoryProfilerMsg::Exit => false } } @@ -108,16 +108,16 @@ impl MemoryProfiler { match nbytes { Some(nbytes) => { let mebi = 1024f64 * 1024f64; - println!("{:16s}: {:12.2f}", path, (nbytes as f64) / mebi); + println!("{:16}: {:12.2}", path, (nbytes as f64) / mebi); } None => { - println!("{:16s}: {:>12s}", path, "???"); + println!("{:16}: {:>12}", path, "???"); } } } fn handle_print_msg(&self) { - println!("{:16s}: {:12s}", "_category_", "_size (MiB)_"); + println!("{:16}: {:12}", "_category_", "_size (MiB)_"); // Virtual and physical memory usage, as reported by the OS. MemoryProfiler::print_measurement("vsize", get_vsize()); diff --git a/components/util/opts.rs b/components/util/opts.rs index 9f19ead5f5e..1689321fa6e 100644 --- a/components/util/opts.rs +++ b/components/util/opts.rs @@ -179,7 +179,7 @@ pub fn default_opts() -> Opts { dump_flow_tree: false, validate_display_list_geometry: false, profile_tasks: false, - render_api: OpenGL, + render_api: RenderApi::OpenGL, } } @@ -298,8 +298,8 @@ pub fn from_cmdline_args(args: &[String]) -> bool { }; let render_api = match opt_match.opt_str("r").unwrap_or("gl".to_string()).as_slice() { - "mesa" => Mesa, - "gl" => OpenGL, + "mesa" => RenderApi::Mesa, + "gl" => RenderApi::OpenGL, _ => { args_fail("Unknown render api specified"); return false; diff --git a/components/util/range.rs b/components/util/range.rs index 9b2363b9967..2cdb49e27b6 100644 --- a/components/util/range.rs +++ b/components/util/range.rs @@ -6,7 +6,7 @@ use std::cmp::{max, min}; use std::iter; use std::fmt; use std::num; -use std::num::{Bounded, Zero}; +use std::num::{Int, Bounded, Zero}; /// An index type to be used by a `Range` pub trait RangeIndex: Copy @@ -52,6 +52,30 @@ macro_rules! int_range_index { } impl RangeIndex for $Self {} + impl ::std::num::Int for $Self { + fn zero() -> $Self { $Self(0) } + fn one() -> $Self { $Self(1) } + fn min_value() -> $Self { $Self(::std::num::Int::min_value()) } + fn max_value() -> $Self { $Self(::std::num::Int::max_value()) } + fn count_ones(self) -> uint { self.get().count_ones() } + fn leading_zeros(self) -> uint { self.get().leading_zeros() } + fn trailing_zeros(self) -> uint { self.get().trailing_zeros() } + fn rotate_left(self, n: uint) -> $Self { $Self(self.get().rotate_left(n)) } + fn rotate_right(self, n: uint) -> $Self { $Self(self.get().rotate_right(n)) } + fn swap_bytes(self) -> $Self { $Self(self.get().swap_bytes()) } + fn checked_add(self, other: $Self) -> Option<$Self> { + self.get().checked_add(other.get()).map($Self) + } + fn checked_sub(self, other: $Self) -> Option<$Self> { + self.get().checked_sub(other.get()).map($Self) + } + fn checked_mul(self, other: $Self) -> Option<$Self> { + self.get().checked_mul(other.get()).map($Self) + } + fn checked_div(self, other: $Self) -> Option<$Self> { + self.get().checked_div(other.get()).map($Self) + } + } impl IntRangeIndex<$T> for $Self { #[inline] @@ -108,6 +132,60 @@ macro_rules! int_range_index { Some(self.get() as u64) } } + + impl ::std::num::NumCast for $Self { + fn from<T: ToPrimitive>(n: T) -> Option<$Self> { + n.to_int().map($Self) + } + } + + impl Div<$Self, $Self> for $Self { + fn div(&self, other: &$Self) -> $Self { + $Self(self.get() / other.get()) + } + } + + impl Rem<$Self, $Self> for $Self { + fn rem(&self, other: &$Self) -> $Self { + $Self(self.get() % other.get()) + } + } + + impl Not<$Self> for $Self { + fn not(&self) -> $Self { + $Self(!self.get()) + } + } + + impl BitAnd<$Self, $Self> for $Self { + fn bitand(&self, other: &$Self) -> $Self { + $Self(self.get() & other.get()) + } + } + + impl BitOr<$Self, $Self> for $Self { + fn bitor(&self, other: &$Self) -> $Self { + $Self(self.get() | other.get()) + } + } + + impl BitXor<$Self, $Self> for $Self { + fn bitxor(&self, other: &$Self) -> $Self { + $Self(self.get() ^ other.get()) + } + } + + impl Shl<uint, $Self> for $Self { + fn shl(&self, n: &uint) -> $Self { + $Self(self.get() << *n) + } + } + + impl Shr<uint, $Self> for $Self { + fn shr(&self, n: &uint) -> $Self { + $Self(self.get() >> *n) + } + } ) } @@ -282,7 +360,7 @@ impl<I: RangeIndex> Range<I> { } /// Methods for `Range`s with indices based on integer values -impl<T: Int, I: IntRangeIndex<T>> Range<I> { +impl<T: Int+Bounded, I: IntRangeIndex<T>> Range<I> { /// Returns an iterater that increments over `[begin, end)`. #[inline] pub fn each_index(&self) -> EachIndex<T, I> { diff --git a/components/util/rtinstrument.rs b/components/util/rtinstrument.rs index 347ed09084a..7ad59bada22 100644 --- a/components/util/rtinstrument.rs +++ b/components/util/rtinstrument.rs @@ -6,11 +6,11 @@ use opts; use std::any::Any; #[cfg(not(test))] use std::io::File; -use std::mem; -use std::raw; +//use std::mem; +//use std::raw; use std::rt::Runtime; use std::rt::local::Local; -use std::rt::rtio; +//use std::rt::rtio; use std::rt::task::{Task, TaskOpts, BlockedTask}; use std_time; use sync::Mutex; @@ -28,7 +28,6 @@ pub enum Event { #[deriving(Encodable)] pub struct Message { timestamp: u64, - thread_id: uint, event: Event, } @@ -110,7 +109,7 @@ fn install() { inner: Some(rt), messages: vec!(), }; - new_rt.log(Spawn); + new_rt.log(Event::Spawn); task.put_runtime(new_rt); } @@ -119,7 +118,7 @@ fn install() { fn uninstall() -> InstrumentedRuntime { let mut task = Local::borrow(None::<Task>); let mut rt = task.maybe_take_runtime::<InstrumentedRuntime>().unwrap(); - rt.log(Death); + rt.log(Event::Death); task.put_runtime(rt.inner.take().unwrap()); *rt } @@ -142,22 +141,13 @@ impl InstrumentedRuntime { /// Logs a message into this runtime fn log(&mut self, event: Event) { - let id = self.thread_id(); self.messages.push(Message { timestamp: std_time::precise_time_ns(), event: event, - thread_id: id, }); } fn task_id(&self) -> uint { self as *const _ as uint } - - fn thread_id(&mut self) -> uint { - self.inner.as_mut().unwrap().local_io().map(|mut i| { - let i: raw::TraitObject = unsafe { mem::transmute(i.get()) }; - i.data as uint - }).unwrap_or(0) - } } impl Runtime for InstrumentedRuntime { @@ -177,9 +167,9 @@ impl Runtime for InstrumentedRuntime { fn deschedule(mut self: Box<InstrumentedRuntime>, times: uint, cur_task: Box<Task>, f: |BlockedTask| -> Result<(), BlockedTask>) { - self.log(Unschedule); + self.log(Event::Unschedule); self.inner.take().unwrap().deschedule(times, cur_task, f); - self.put(Some(Schedule)); + self.put(Some(Event::Schedule)); } fn reawaken(mut self: Box<InstrumentedRuntime>, to_wake: Box<Task>) { @@ -201,9 +191,6 @@ impl Runtime for InstrumentedRuntime { self.put(None) } - fn local_io<'a>(&'a mut self) -> Option<rtio::LocalIo<'a>> { - self.inner.as_mut().unwrap().local_io() - } fn stack_bounds(&self) -> (uint, uint) { self.inner.as_ref().unwrap().stack_bounds() } fn can_block(&self) -> bool { self.inner.as_ref().unwrap().can_block() } fn wrap(self: Box<InstrumentedRuntime>) -> Box<Any+'static> { self as Box<Any> } diff --git a/components/util/smallvec.rs b/components/util/smallvec.rs index 8897ca6b313..e77b4872d2d 100644 --- a/components/util/smallvec.rs +++ b/components/util/smallvec.rs @@ -420,8 +420,8 @@ macro_rules! def_small_vector( } } - impl<T> Extendable<T> for $name<T> { - fn extend<I: Iterator<T>>(&mut self, mut iter: I) { + impl<T> $name<T> { + pub fn extend<I: Iterator<T>>(&mut self, mut iter: I) { let (lower_size_bound, _) = iter.size_hint(); let target_len = self.len() + lower_size_bound; diff --git a/components/util/str.rs b/components/util/str.rs index 7b2cfdf5107..4ada243391c 100644 --- a/components/util/str.rs +++ b/components/util/str.rs @@ -4,11 +4,11 @@ use geometry::Au; -use cssparser::{mod, RGBA, RGBAColor}; +use cssparser::{mod, RGBA, Color}; use std::ascii::AsciiExt; -use std::from_str::FromStr; use std::iter::Filter; -use std::str::{CharEq, CharSplits}; +use std::num::Int; +use std::str::{CharEq, CharSplits, FromStr}; use unicode::char::to_lowercase; pub type DOMString = String; @@ -105,13 +105,13 @@ fn do_parse_integer<T: Iterator<char>>(input: T) -> Option<i64> { d as i64 - '0' as i64 }).fold(Some(0i64), |accumulator, d| { accumulator.and_then(|accumulator| { - accumulator.checked_mul(&10) + accumulator.checked_mul(10) }).and_then(|accumulator| { - accumulator.checked_add(&d) + accumulator.checked_add(d) }) }); - return value.and_then(|value| value.checked_mul(&sign)); + return value.and_then(|value| value.checked_mul(sign)); } /// Parse an integer according to @@ -131,23 +131,23 @@ pub fn parse_unsigned_integer<T: Iterator<char>>(input: T) -> Option<u32> { } pub enum LengthOrPercentageOrAuto { - AutoLpa, - PercentageLpa(f64), - LengthLpa(Au), + Auto, + Percentage(f64), + Length(Au), } -/// Parses a length per HTML5 § 2.4.4.4. If unparseable, `AutoLpa` is returned. +/// Parses a length per HTML5 § 2.4.4.4. If unparseable, `Auto` is returned. pub fn parse_length(mut value: &str) -> LengthOrPercentageOrAuto { value = value.trim_left_chars(Whitespace); if value.len() == 0 { - return AutoLpa + return LengthOrPercentageOrAuto::Auto } if value.starts_with("+") { value = value.slice_from(1) } value = value.trim_left_chars('0'); if value.len() == 0 { - return AutoLpa + return LengthOrPercentageOrAuto::Auto } let mut end_index = value.len(); @@ -175,14 +175,14 @@ pub fn parse_length(mut value: &str) -> LengthOrPercentageOrAuto { if found_percent { let result: Option<f64> = FromStr::from_str(value); match result { - Some(number) => return PercentageLpa((number as f64) / 100.0), - None => return AutoLpa, + Some(number) => return LengthOrPercentageOrAuto::Percentage((number as f64) / 100.0), + None => return LengthOrPercentageOrAuto::Auto, } } match FromStr::from_str(value) { - Some(number) => LengthLpa(Au::from_px(number)), - None => AutoLpa, + Some(number) => LengthOrPercentageOrAuto::Length(Au::from_px(number)), + None => LengthOrPercentageOrAuto::Auto, } } @@ -203,7 +203,7 @@ pub fn parse_legacy_color(mut input: &str) -> Result<RGBA,()> { // Step 5. match cssparser::parse_color_keyword(input) { - Ok(RGBAColor(rgba)) => return Ok(rgba), + Ok(Color::RGBA(rgba)) => return Ok(rgba), _ => {} } diff --git a/components/util/task.rs b/components/util/task.rs index 362edb6b517..5af0ce9cff0 100644 --- a/components/util/task.rs +++ b/components/util/task.rs @@ -43,13 +43,13 @@ pub fn spawn_named_with_send_on_failure<T: Send>(name: &'static str, }; let watched_name = name.to_string(); - let watcher_name = format!("{:s}Watcher", watched_name); + let watcher_name = format!("{}Watcher", watched_name); TaskBuilder::new().named(watcher_name).spawn(proc() { rtinstrument::instrument(proc() { match future_result.unwrap() { Ok(()) => (), Err(..) => { - debug!("{:s} failed, notifying constellation", name); + debug!("{} failed, notifying constellation", name); dest.send(msg); } } diff --git a/components/util/time.rs b/components/util/time.rs index 4fdc23b023d..16155710737 100644 --- a/components/util/time.rs +++ b/components/util/time.rs @@ -9,6 +9,7 @@ use std::comm::{Sender, channel, Receiver}; use std::f64; use std::io::timer::sleep; use std::iter::AdditiveIterator; +use std::num::FloatMath; use std::time::duration::Duration; use std_time::precise_time_ns; use task::{spawn_named}; @@ -60,11 +61,11 @@ impl Formatable for Option<TimerMetadata> { #[deriving(Clone)] pub enum TimeProfilerMsg { /// Normal message used for reporting time - TimeMsg((TimeProfilerCategory, Option<TimerMetadata>), f64), + Time((TimeProfilerCategory, Option<TimerMetadata>), f64), /// Message used to force print the profiling metrics - PrintMsg, + Print, /// Tells the profiler to shut down. - ExitMsg, + Exit, } #[repr(u32)] @@ -92,38 +93,38 @@ impl Formatable for TimeProfilerCategory { // and should be printed to indicate this fn format(&self) -> String { let padding = match *self { - LayoutStyleRecalcCategory | - LayoutRestyleDamagePropagation | - LayoutNonIncrementalReset | - LayoutMainCategory | - LayoutDispListBuildCategory | - LayoutShapingCategory | - LayoutDamagePropagateCategory | - PaintingPerTileCategory | - PaintingPrepBuffCategory => "+ ", - LayoutParallelWarmupCategory | - LayoutSelectorMatchCategory | - LayoutTreeBuilderCategory => "| + ", + TimeProfilerCategory::LayoutStyleRecalcCategory | + TimeProfilerCategory::LayoutRestyleDamagePropagation | + TimeProfilerCategory::LayoutNonIncrementalReset | + TimeProfilerCategory::LayoutMainCategory | + TimeProfilerCategory::LayoutDispListBuildCategory | + TimeProfilerCategory::LayoutShapingCategory | + TimeProfilerCategory::LayoutDamagePropagateCategory | + TimeProfilerCategory::PaintingPerTileCategory | + TimeProfilerCategory::PaintingPrepBuffCategory => "+ ", + TimeProfilerCategory::LayoutParallelWarmupCategory | + TimeProfilerCategory::LayoutSelectorMatchCategory | + TimeProfilerCategory::LayoutTreeBuilderCategory => "| + ", _ => "" }; let name = match *self { - CompositingCategory => "Compositing", - LayoutPerformCategory => "Layout", - LayoutStyleRecalcCategory => "Style Recalc", - LayoutRestyleDamagePropagation => "Restyle Damage Propagation", - LayoutNonIncrementalReset => "Non-incremental reset (temporary)", - LayoutSelectorMatchCategory => "Selector Matching", - LayoutTreeBuilderCategory => "Tree Building", - LayoutDamagePropagateCategory => "Damage Propagation", - LayoutMainCategory => "Primary Layout Pass", - LayoutParallelWarmupCategory => "Parallel Warmup", - LayoutShapingCategory => "Shaping", - LayoutDispListBuildCategory => "Display List Construction", - PaintingPerTileCategory => "Painting Per Tile", - PaintingPrepBuffCategory => "Buffer Prep", - PaintingCategory => "Painting", + TimeProfilerCategory::CompositingCategory => "Compositing", + TimeProfilerCategory::LayoutPerformCategory => "Layout", + TimeProfilerCategory::LayoutStyleRecalcCategory => "Style Recalc", + TimeProfilerCategory::LayoutRestyleDamagePropagation => "Restyle Damage Propagation", + TimeProfilerCategory::LayoutNonIncrementalReset => "Non-incremental reset (temporary)", + TimeProfilerCategory::LayoutSelectorMatchCategory => "Selector Matching", + TimeProfilerCategory::LayoutTreeBuilderCategory => "Tree Building", + TimeProfilerCategory::LayoutDamagePropagateCategory => "Damage Propagation", + TimeProfilerCategory::LayoutMainCategory => "Primary Layout Pass", + TimeProfilerCategory::LayoutParallelWarmupCategory => "Parallel Warmup", + TimeProfilerCategory::LayoutShapingCategory => "Shaping", + TimeProfilerCategory::LayoutDispListBuildCategory => "Display List Construction", + TimeProfilerCategory::PaintingPerTileCategory => "Painting Per Tile", + TimeProfilerCategory::PaintingPrepBuffCategory => "Buffer Prep", + TimeProfilerCategory::PaintingCategory => "Painting", }; - format!("{:s}{}", padding, name) + format!("{}{}", padding, name) } } @@ -146,7 +147,7 @@ impl TimeProfiler { spawn_named("Time profiler timer", proc() { loop { sleep(period); - if chan.send_opt(PrintMsg).is_err() { + if chan.send_opt(TimeProfilerMsg::Print).is_err() { break; } } @@ -162,7 +163,7 @@ impl TimeProfiler { spawn_named("Time profiler", proc() { loop { match port.recv_opt() { - Err(_) | Ok(ExitMsg) => break, + Err(_) | Ok(TimeProfilerMsg::Exit) => break, _ => {} } } @@ -206,20 +207,20 @@ impl TimeProfiler { fn handle_msg(&mut self, msg: TimeProfilerMsg) -> bool { match msg.clone() { - TimeMsg(k, t) => self.find_or_insert(k, t), - PrintMsg => match self.last_msg { + TimeProfilerMsg::Time(k, t) => self.find_or_insert(k, t), + TimeProfilerMsg::Print => match self.last_msg { // only print if more data has arrived since the last printout - Some(TimeMsg(..)) => self.print_buckets(), + Some(TimeProfilerMsg::Time(..)) => self.print_buckets(), _ => () }, - ExitMsg => return false, + TimeProfilerMsg::Exit => return false, }; self.last_msg = Some(msg); true } fn print_buckets(&mut self) { - println!("{:35s} {:14} {:9} {:30} {:15s} {:15s} {:-15s} {:-15s} {:-15s}", + println!("{:35} {:14} {:9} {:30} {:15} {:15} {:-15} {:-15} {:-15}", "_category_", "_incremental?_", "_iframe?_", " _url_", " _mean (ms)_", " _median (ms)_", " _min (ms)_", " _max (ms)_", " _events_"); @@ -238,7 +239,7 @@ impl TimeProfiler { data.as_slice()[data_len / 2], data.iter().fold(f64::INFINITY, |a, &b| a.min(b)), data.iter().fold(-f64::INFINITY, |a, &b| a.max(b))); - println!("{:-35s}{} {:15.4f} {:15.4f} {:15.4f} {:15.4f} {:15u}", + println!("{:-35}{} {:15.4} {:15.4} {:15.4} {:15.4} {:15}", category.format(), meta.format(), mean, median, min, max, data_len); } } @@ -248,14 +249,14 @@ impl TimeProfiler { #[deriving(Eq, PartialEq)] pub enum TimerMetadataFrameType { - TimeRootWindow, - TimeIFrame, + RootWindow, + IFrame, } #[deriving(Eq, PartialEq)] pub enum TimerMetadataReflowType { - TimeIncremental, - TimeFirstReflow, + Incremental, + FirstReflow, } pub fn profile<T>(category: TimeProfilerCategory, @@ -270,10 +271,10 @@ pub fn profile<T>(category: TimeProfilerCategory, let meta = meta.map(|(url, iframe, reflow_type)| TimerMetadata { url: url.serialize(), - iframe: iframe == TimeIFrame, - incremental: reflow_type == TimeIncremental, + iframe: iframe == TimerMetadataFrameType::IFrame, + incremental: reflow_type == TimerMetadataReflowType::Incremental, }); - time_profiler_chan.send(TimeMsg((category, meta), ms)); + time_profiler_chan.send(TimeProfilerMsg::Time((category, meta), ms)); return val; } @@ -283,7 +284,7 @@ pub fn time<T>(msg: &str, callback: || -> T) -> T{ let end_time = precise_time_ns(); let ms = (end_time - start_time) as f64 / 1000000f64; if ms >= 5f64 { - debug!("{:s} took {} ms", msg, ms); + debug!("{} took {} ms", msg, ms); } return val; } diff --git a/components/util/workqueue.rs b/components/util/workqueue.rs index 3420e47345b..8a224dd6e84 100644 --- a/components/util/workqueue.rs +++ b/components/util/workqueue.rs @@ -33,17 +33,17 @@ pub struct WorkUnit<QueueData, WorkData> { /// Messages from the supervisor to the worker. enum WorkerMsg<QueueData, WorkData> { /// Tells the worker to start work. - StartMsg(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUint, *const QueueData), - /// Tells the worker to stop. It can be restarted again with a `StartMsg`. - StopMsg, + Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUint, *const QueueData), + /// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`. + Stop, /// Tells the worker thread to terminate. - ExitMsg, + Exit, } /// Messages to the supervisor. enum SupervisorMsg<QueueData, WorkData> { - FinishedMsg, - ReturnDequeMsg(uint, Worker<WorkUnit<QueueData, WorkData>>), + Finished, + ReturnDeque(uint, Worker<WorkUnit<QueueData, WorkData>>), } /// Information that the supervisor thread keeps about the worker threads. @@ -81,9 +81,9 @@ impl<QueueData: Send, WorkData: Send> WorkerThread<QueueData, WorkData> { loop { // Wait for a start message. let (mut deque, ref_count, queue_data) = match self.port.recv() { - StartMsg(deque, ref_count, queue_data) => (deque, ref_count, queue_data), - StopMsg => panic!("unexpected stop message"), - ExitMsg => return, + WorkerMsg::Start(deque, ref_count, queue_data) => (deque, ref_count, queue_data), + WorkerMsg::Stop => panic!("unexpected stop message"), + WorkerMsg::Exit => return, }; let mut back_off_sleep = 0 as u32; @@ -125,11 +125,11 @@ impl<QueueData: Send, WorkData: Send> WorkerThread<QueueData, WorkData> { if i == SPIN_COUNT { match self.port.try_recv() { - Ok(StopMsg) => { + Ok(WorkerMsg::Stop) => { should_continue = false; break } - Ok(ExitMsg) => return, + Ok(WorkerMsg::Exit) => return, Ok(_) => panic!("unexpected message"), _ => {} } @@ -158,13 +158,13 @@ impl<QueueData: Send, WorkData: Send> WorkerThread<QueueData, WorkData> { // the last work unit in the queue, then send a message on the channel. unsafe { if (*ref_count).fetch_sub(1, SeqCst) == 1 { - self.chan.send(FinishedMsg) + self.chan.send(SupervisorMsg::Finished) } } } // Give the deque back to the supervisor. - self.chan.send(ReturnDequeMsg(self.index, deque)) + self.chan.send(SupervisorMsg::ReturnDeque(self.index, deque)) } } } @@ -283,7 +283,7 @@ impl<QueueData: Send, WorkData: Send> WorkQueue<QueueData, WorkData> { // Tell the workers to start. let mut work_count = AtomicUint::new(self.work_count); for worker in self.workers.iter_mut() { - worker.chan.send(StartMsg(worker.deque.take().unwrap(), &mut work_count, &self.data)) + worker.chan.send(WorkerMsg::Start(worker.deque.take().unwrap(), &mut work_count, &self.data)) } // Wait for the work to finish. @@ -292,21 +292,21 @@ impl<QueueData: Send, WorkData: Send> WorkQueue<QueueData, WorkData> { // Tell everyone to stop. for worker in self.workers.iter() { - worker.chan.send(StopMsg) + worker.chan.send(WorkerMsg::Stop) } // Get our deques back. for _ in range(0, self.workers.len()) { match self.port.recv() { - ReturnDequeMsg(index, deque) => self.workers[index].deque = Some(deque), - FinishedMsg => panic!("unexpected finished message!"), + SupervisorMsg::ReturnDeque(index, deque) => self.workers[index].deque = Some(deque), + SupervisorMsg::Finished => panic!("unexpected finished message!"), } } } pub fn shutdown(&mut self) { for worker in self.workers.iter() { - worker.chan.send(ExitMsg) + worker.chan.send(WorkerMsg::Exit) } } } diff --git a/ports/cef/Cargo.lock b/ports/cef/Cargo.lock index 2081d8c0bbb..c79b3716831 100644 --- a/ports/cef/Cargo.lock +++ b/ports/cef/Cargo.lock @@ -27,7 +27,7 @@ dependencies = [ [[package]] name = "azure" version = "0.1.0" -source = "git+https://github.com/servo/rust-azure#e8323588209b47a07b67f61812c75dfeb2ad6851" +source = "git+https://github.com/servo/rust-azure#fe95551ca22f2a75b0dd690a72841df39b33885d" dependencies = [ "core_foundation 0.1.0 (git+https://github.com/servo/rust-core-foundation)", "core_graphics 0.1.0 (git+https://github.com/servo/rust-core-graphics)", @@ -80,6 +80,7 @@ dependencies = [ "net 0.0.1", "png 0.1.0 (git+https://github.com/servo/rust-png)", "script_traits 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", "util 0.0.1", ] @@ -87,16 +88,17 @@ dependencies = [ [[package]] name = "cookie" version = "0.0.1" -source = "git+https://github.com/servo/cookie-rs#30520767a95b92e39265aaf6822db515b2418f1d" +source = "git+https://github.com/servo/cookie-rs#f82090b19c2738b90528167ef873d8eac0353294" dependencies = [ - "openssl 0.0.1 (git+https://github.com/servo/rust-openssl)", + "openssl 0.0.2 (git+https://github.com/servo/rust-openssl)", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", ] [[package]] name = "core_foundation" version = "0.1.0" -source = "git+https://github.com/servo/rust-core-foundation#6fa0b908f3912e20d081193e83bf5a9aa958fb83" +source = "git+https://github.com/servo/rust-core-foundation#d2dbe4fb6f6892521a37735cd7a97098d1b64808" [[package]] name = "core_graphics" @@ -118,9 +120,9 @@ dependencies = [ [[package]] name = "cssparser" version = "0.1.0" -source = "git+https://github.com/servo/rust-cssparser#3f98f1308b769b5d61efc6c133ac520df2b074ac" +source = "git+https://github.com/servo/rust-cssparser#97d8c3b20a240881573748d4eadcda610bfb888c" dependencies = [ - "encoding 0.2.0 (git+https://github.com/lifthrasiir/rust-encoding)", + "encoding 0.2.3 (git+https://github.com/lifthrasiir/rust-encoding)", ] [[package]] @@ -146,8 +148,8 @@ source = "git+https://github.com/servo/rust-egl#88f2a13812ddbce2bf2317221663a61c [[package]] name = "encoding" -version = "0.2.0" -source = "git+https://github.com/lifthrasiir/rust-encoding#a06637cc6d0da37c12c68661e2ee9ca1999764a4" +version = "0.2.3" +source = "git+https://github.com/lifthrasiir/rust-encoding#15ac0ded3ca592c31ded5b9ff6f9fe2fa4b73fc4" dependencies = [ "encoding-index-japanese 1.0.20140915 (git+https://github.com/lifthrasiir/rust-encoding)", "encoding-index-korean 1.0.20140915 (git+https://github.com/lifthrasiir/rust-encoding)", @@ -159,27 +161,47 @@ dependencies = [ [[package]] name = "encoding-index-japanese" version = "1.0.20140915" -source = "git+https://github.com/lifthrasiir/rust-encoding#a06637cc6d0da37c12c68661e2ee9ca1999764a4" +source = "git+https://github.com/lifthrasiir/rust-encoding#15ac0ded3ca592c31ded5b9ff6f9fe2fa4b73fc4" +dependencies = [ + "encoding_index_tests 0.1.0 (git+https://github.com/lifthrasiir/rust-encoding)", +] [[package]] name = "encoding-index-korean" version = "1.0.20140915" -source = "git+https://github.com/lifthrasiir/rust-encoding#a06637cc6d0da37c12c68661e2ee9ca1999764a4" +source = "git+https://github.com/lifthrasiir/rust-encoding#15ac0ded3ca592c31ded5b9ff6f9fe2fa4b73fc4" +dependencies = [ + "encoding_index_tests 0.1.0 (git+https://github.com/lifthrasiir/rust-encoding)", +] [[package]] name = "encoding-index-simpchinese" version = "1.0.20140915" -source = "git+https://github.com/lifthrasiir/rust-encoding#a06637cc6d0da37c12c68661e2ee9ca1999764a4" +source = "git+https://github.com/lifthrasiir/rust-encoding#15ac0ded3ca592c31ded5b9ff6f9fe2fa4b73fc4" +dependencies = [ + "encoding_index_tests 0.1.0 (git+https://github.com/lifthrasiir/rust-encoding)", +] [[package]] name = "encoding-index-singlebyte" version = "1.0.20140915" -source = "git+https://github.com/lifthrasiir/rust-encoding#a06637cc6d0da37c12c68661e2ee9ca1999764a4" +source = "git+https://github.com/lifthrasiir/rust-encoding#15ac0ded3ca592c31ded5b9ff6f9fe2fa4b73fc4" +dependencies = [ + "encoding_index_tests 0.1.0 (git+https://github.com/lifthrasiir/rust-encoding)", +] [[package]] name = "encoding-index-tradchinese" version = "1.0.20140915" -source = "git+https://github.com/lifthrasiir/rust-encoding#a06637cc6d0da37c12c68661e2ee9ca1999764a4" +source = "git+https://github.com/lifthrasiir/rust-encoding#15ac0ded3ca592c31ded5b9ff6f9fe2fa4b73fc4" +dependencies = [ + "encoding_index_tests 0.1.0 (git+https://github.com/lifthrasiir/rust-encoding)", +] + +[[package]] +name = "encoding_index_tests" +version = "0.1.0" +source = "git+https://github.com/lifthrasiir/rust-encoding#15ac0ded3ca592c31ded5b9ff6f9fe2fa4b73fc4" [[package]] name = "expat-sys" @@ -214,6 +236,11 @@ version = "2.4.11" source = "git+https://github.com/servo/libfreetype2#f5c49c0da1d5bc6b206c4176344012ac37524243" [[package]] +name = "gcc" +version = "0.0.2" +source = "git+https://github.com/alexcrichton/gcc-rs#903e8f8a2e3766ad3d514404d452dbaa1d3b2d79" + +[[package]] name = "geom" version = "0.1.0" source = "git+https://github.com/servo/rust-geom#95e746133b4a35b53eb259304668b63ee8de42b8" @@ -238,6 +265,7 @@ dependencies = [ "script_traits 0.0.1", "stb_image 0.1.0 (git+https://github.com/servo/rust-stb-image)", "style 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", "util 0.0.1", ] @@ -245,16 +273,16 @@ dependencies = [ [[package]] name = "gl_common" version = "0.0.1" -source = "git+https://github.com/bjz/gl-rs.git#79cd3b3f9f19aa0e39f6af572fc8673a6d9760bc" +source = "git+https://github.com/bjz/gl-rs.git#c76c23fc9a0dae824b45550d4b823cdb726f242d" [[package]] name = "gl_generator" version = "0.0.1" -source = "git+https://github.com/bjz/gl-rs.git#79cd3b3f9f19aa0e39f6af572fc8673a6d9760bc" +source = "git+https://github.com/bjz/gl-rs.git#c76c23fc9a0dae824b45550d4b823cdb726f242d" dependencies = [ "gl_common 0.0.1 (git+https://github.com/bjz/gl-rs.git)", - "khronos_api 0.0.1 (git+https://github.com/bjz/gl-rs.git)", - "rust-xml 0.1.0 (git+https://github.com/netvl/rust-xml)", + "khronos_api 0.0.2 (git+https://github.com/bjz/gl-rs.git)", + "rust-xml 0.1.2-pre (git+https://github.com/netvl/rust-xml)", ] [[package]] @@ -268,10 +296,10 @@ dependencies = [ [[package]] name = "glfw" version = "0.0.1" -source = "git+https://github.com/servo/glfw-rs?ref=servo#46f82b46589720f202ab2d4a99e4f4fd48df6469" +source = "git+https://github.com/servo/glfw-rs?ref=servo#1b05fdc7eab45e1d462758ab991065ee78593b7f" dependencies = [ "glfw-sys 3.0.4 (git+https://github.com/servo/glfw?ref=cargo-3.0.4)", - "semver 0.1.0 (git+https://github.com/rust-lang/semver)", + "semver 0.1.3 (git+https://github.com/rust-lang/semver)", ] [[package]] @@ -290,6 +318,7 @@ dependencies = [ "glfw 0.0.1 (git+https://github.com/servo/glfw-rs?ref=servo)", "layers 0.1.0 (git+https://github.com/servo/rust-layers)", "msg 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "util 0.0.1", ] @@ -309,30 +338,30 @@ source = "git+https://github.com/servo/rust-harfbuzz#8aab215463214647b7a81f66011 [[package]] name = "html5ever" version = "0.0.0" -source = "git+https://github.com/servo/html5ever?ref=servo#87c7e8b710391338b2463652be835f498923653c" +source = "git+https://github.com/servo/html5ever#e6f8d83de9fffe63a825d95d957ba6bcbc3e1632" dependencies = [ - "html5ever_macros 0.0.0 (git+https://github.com/servo/html5ever?ref=servo)", + "html5ever_macros 0.0.0 (git+https://github.com/servo/html5ever)", "phf 0.0.0 (git+https://github.com/sfackler/rust-phf)", "phf_mac 0.0.0 (git+https://github.com/sfackler/rust-phf)", "string_cache 0.0.0 (git+https://github.com/servo/string-cache)", "string_cache_macros 0.0.0 (git+https://github.com/servo/string-cache)", + "time 0.1.0 (git+https://github.com/rust-lang/time)", ] [[package]] name = "html5ever_macros" version = "0.0.0" -source = "git+https://github.com/servo/html5ever?ref=servo#87c7e8b710391338b2463652be835f498923653c" +source = "git+https://github.com/servo/html5ever#e6f8d83de9fffe63a825d95d957ba6bcbc3e1632" [[package]] name = "hyper" version = "0.0.1" -source = "git+https://github.com/servo/hyper?ref=servo#dd9d1830f35f7a8371b1b3bcb2d3e9cf2763f33f" +source = "git+https://github.com/servo/hyper?ref=servo#9c70c58e65ec80446fdb6e338f1060589b562f8c" dependencies = [ "cookie 0.0.1 (git+https://github.com/servo/cookie-rs)", "mime 0.0.1 (git+https://github.com/hyperium/mime.rs)", - "move-acceptor 0.0.1 (git+https://github.com/reem/rust-move-acceptor)", - "openssl 0.0.1 (git+https://github.com/servo/rust-openssl)", - "typeable 0.0.3 (git+https://github.com/reem/rust-typeable)", + "openssl 0.0.2 (git+https://github.com/servo/rust-openssl)", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "unsafe-any 0.1.0 (git+https://github.com/reem/rust-unsafe-any)", "url 0.1.0 (git+https://github.com/servo/rust-url)", ] @@ -351,20 +380,20 @@ dependencies = [ [[package]] name = "js" version = "0.1.0" -source = "git+https://github.com/servo/rust-mozjs#7563bbd5abf12a1f0d01661c525b1f2491f783a9" +source = "git+https://github.com/servo/rust-mozjs#e04e7307a3e52f46bc9ba3d5682188285110bc67" dependencies = [ "mozjs-sys 0.0.0 (git+https://github.com/servo/mozjs)", ] [[package]] name = "khronos_api" -version = "0.0.1" -source = "git+https://github.com/bjz/gl-rs.git#79cd3b3f9f19aa0e39f6af572fc8673a6d9760bc" +version = "0.0.2" +source = "git+https://github.com/bjz/gl-rs.git#c76c23fc9a0dae824b45550d4b823cdb726f242d" [[package]] name = "layers" version = "0.1.0" -source = "git+https://github.com/servo/rust-layers#63d1093f2a01a6fb9599ea6d932aadf79598451f" +source = "git+https://github.com/servo/rust-layers#5fbdc521b82296e325d2df13fce8026c727c01d2" dependencies = [ "cgl 0.0.1 (git+https://github.com/servo/rust-cgl)", "core_foundation 0.1.0 (git+https://github.com/servo/rust-core-foundation)", @@ -381,7 +410,7 @@ name = "layout" version = "0.0.1" dependencies = [ "cssparser 0.1.0 (git+https://github.com/servo/rust-cssparser)", - "encoding 0.2.0 (git+https://github.com/lifthrasiir/rust-encoding)", + "encoding 0.2.3 (git+https://github.com/lifthrasiir/rust-encoding)", "geom 0.1.0 (git+https://github.com/servo/rust-geom)", "gfx 0.0.1", "layout_traits 0.0.1", @@ -414,8 +443,8 @@ source = "git+https://github.com/Kimundi/lazy-static.rs#62976cb611c5396e11315ae6 [[package]] name = "libressl-pnacl-sys" -version = "2.0.2" -source = "git+https://github.com/DiamondLovesYou/libressl-pnacl-sys.git#8e9349e0280b069bfab247a2202cd10b8beae154" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "pnacl-build-helper 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -423,12 +452,7 @@ dependencies = [ [[package]] name = "mime" version = "0.0.1" -source = "git+https://github.com/hyperium/mime.rs#5264e04655974f85c8d6581395cc24597266c653" - -[[package]] -name = "move-acceptor" -version = "0.0.1" -source = "git+https://github.com/reem/rust-move-acceptor#25c5c33a83f605fdd0f3d37d2589e2b0b4e6cbd1" +source = "git+https://github.com/hyperium/mime.rs#7898f1c29c7f5d35d0c3c7aed37ebcfc95a40873" [[package]] name = "mozjs-sys" @@ -457,31 +481,32 @@ dependencies = [ "hyper 0.0.1 (git+https://github.com/servo/hyper?ref=servo)", "png 0.1.0 (git+https://github.com/servo/rust-png)", "stb_image 0.1.0 (git+https://github.com/servo/rust-stb-image)", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", "util 0.0.1", ] [[package]] name = "openssl" -version = "0.0.1" -source = "git+https://github.com/servo/rust-openssl#82b520100532dba9a4cdd4588709eaedb37c7a77" +version = "0.0.2" +source = "git+https://github.com/servo/rust-openssl#19d9b53a86d602e16ab2274813a517cfaa4a2512" dependencies = [ - "libressl-pnacl-sys 2.0.2 (git+https://github.com/DiamondLovesYou/libressl-pnacl-sys.git)", - "openssl-sys 0.0.1 (git+https://github.com/servo/rust-openssl)", + "libressl-pnacl-sys 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "openssl-sys 0.0.2 (git+https://github.com/servo/rust-openssl)", ] [[package]] name = "openssl-sys" -version = "0.0.1" -source = "git+https://github.com/servo/rust-openssl#82b520100532dba9a4cdd4588709eaedb37c7a77" +version = "0.0.2" +source = "git+https://github.com/servo/rust-openssl#19d9b53a86d602e16ab2274813a517cfaa4a2512" dependencies = [ - "pkg-config 0.1.0 (git+https://github.com/alexcrichton/pkg-config-rs)", + "pkg-config 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "phf" version = "0.0.0" -source = "git+https://github.com/sfackler/rust-phf#18a5ecc028055c3dbd650cc5a064b6fb033d82ef" +source = "git+https://github.com/sfackler/rust-phf#aa3e2d0aedea4d55c2e4cea1bdf6e89418dc1206" dependencies = [ "xxhash 0.0.1 (git+https://github.com/Jurily/rust-xxhash)", ] @@ -489,15 +514,16 @@ dependencies = [ [[package]] name = "phf_mac" version = "0.0.0" -source = "git+https://github.com/sfackler/rust-phf#18a5ecc028055c3dbd650cc5a064b6fb033d82ef" +source = "git+https://github.com/sfackler/rust-phf#aa3e2d0aedea4d55c2e4cea1bdf6e89418dc1206" dependencies = [ + "time 0.1.0 (git+https://github.com/rust-lang/time)", "xxhash 0.0.1 (git+https://github.com/Jurily/rust-xxhash)", ] [[package]] name = "pkg-config" -version = "0.1.0" -source = "git+https://github.com/alexcrichton/pkg-config-rs#9b3b44a2e1a8ccc70c3f701aeb5154ad79e665e9" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "plugins" @@ -511,7 +537,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "png" version = "0.1.0" -source = "git+https://github.com/servo/rust-png#b0b4acde0080dd475dee93615276bfc19207a21e" +source = "git+https://github.com/servo/rust-png#f060a2d9484a150de286f930eb80f9f3bff3ea38" dependencies = [ "png-sys 1.6.3 (git+https://github.com/servo/libpng?ref=servo)", ] @@ -523,8 +549,8 @@ source = "git+https://github.com/servo/libpng?ref=servo#d01f32b4eb86904695efe7fc [[package]] name = "rust-xml" -version = "0.1.0" -source = "git+https://github.com/netvl/rust-xml#d6c57380a300b94f7e7881979dbe5459dbe4ca06" +version = "0.1.2-pre" +source = "git+https://github.com/netvl/rust-xml#2d9df3267aeaa4d442e1e19a4dfed733cb1397ed" [[package]] name = "script" @@ -533,10 +559,10 @@ dependencies = [ "canvas 0.0.1", "cssparser 0.1.0 (git+https://github.com/servo/rust-cssparser)", "devtools_traits 0.0.1", - "encoding 0.2.0 (git+https://github.com/lifthrasiir/rust-encoding)", + "encoding 0.2.3 (git+https://github.com/lifthrasiir/rust-encoding)", "geom 0.1.0 (git+https://github.com/servo/rust-geom)", "gfx 0.0.1", - "html5ever 0.0.0 (git+https://github.com/servo/html5ever?ref=servo)", + "html5ever 0.0.0 (git+https://github.com/servo/html5ever)", "hyper 0.0.1 (git+https://github.com/servo/hyper?ref=servo)", "js 0.1.0 (git+https://github.com/servo/rust-mozjs)", "msg 0.0.1", @@ -546,9 +572,10 @@ dependencies = [ "string_cache 0.0.0 (git+https://github.com/servo/string-cache)", "string_cache_macros 0.0.0 (git+https://github.com/servo/string-cache)", "style 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", "util 0.0.1", - "uuid 0.0.1 (git+https://github.com/rust-lang/uuid)", + "uuid 0.0.2 (git+https://github.com/rust-lang/uuid)", ] [[package]] @@ -565,8 +592,8 @@ dependencies = [ [[package]] name = "semver" -version = "0.1.0" -source = "git+https://github.com/rust-lang/semver#7dca047a9cd40e929a4545b37a1917daff82f156" +version = "0.1.3" +source = "git+https://github.com/rust-lang/semver#29212953f839337c672d185dde74e14b5dfb1f46" [[package]] name = "servo" @@ -579,6 +606,7 @@ dependencies = [ "msg 0.0.1", "net 0.0.1", "script 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", "util 0.0.1", ] @@ -595,12 +623,12 @@ dependencies = [ [[package]] name = "stb_image" version = "0.1.0" -source = "git+https://github.com/servo/rust-stb-image#74488fef4740acf287ff5dc248d65cc74033467a" +source = "git+https://github.com/servo/rust-stb-image#97d7e440e80e41a304647363c322eab68e3700aa" [[package]] name = "string_cache" version = "0.0.0" -source = "git+https://github.com/servo/string-cache#ae950525434b642eff5f4904f5e0c76cd6ea99b9" +source = "git+https://github.com/servo/string-cache#a18a432fd274e816fc41876536f70e5380abb677" dependencies = [ "lazy_static 0.1.0 (git+https://github.com/Kimundi/lazy-static.rs)", "phf 0.0.0 (git+https://github.com/sfackler/rust-phf)", @@ -612,7 +640,7 @@ dependencies = [ [[package]] name = "string_cache_macros" version = "0.0.0" -source = "git+https://github.com/servo/string-cache#ae950525434b642eff5f4904f5e0c76cd6ea99b9" +source = "git+https://github.com/servo/string-cache#a18a432fd274e816fc41876536f70e5380abb677" dependencies = [ "lazy_static 0.1.0 (git+https://github.com/Kimundi/lazy-static.rs)", ] @@ -622,7 +650,7 @@ name = "style" version = "0.0.1" dependencies = [ "cssparser 0.1.0 (git+https://github.com/servo/rust-cssparser)", - "encoding 0.2.0 (git+https://github.com/lifthrasiir/rust-encoding)", + "encoding 0.2.3 (git+https://github.com/lifthrasiir/rust-encoding)", "geom 0.1.0 (git+https://github.com/servo/rust-geom)", "lazy_static 0.1.0 (git+https://github.com/Kimundi/lazy-static.rs)", "plugins 0.0.1", @@ -637,9 +665,12 @@ name = "task_info" version = "0.0.1" [[package]] -name = "typeable" -version = "0.0.3" -source = "git+https://github.com/reem/rust-typeable#db8975daaa3889871f67eea11baeaefd8e706eaf" +name = "time" +version = "0.1.0" +source = "git+https://github.com/rust-lang/time#afab521f3b91658a3ba2d3e877b7e01699733bef" +dependencies = [ + "gcc 0.0.2 (git+https://github.com/alexcrichton/gcc-rs)", +] [[package]] name = "unsafe-any" @@ -649,10 +680,7 @@ source = "git+https://github.com/reem/rust-unsafe-any#2863af363bbd83079b6773920b [[package]] name = "url" version = "0.1.0" -source = "git+https://github.com/servo/rust-url#8a61b7654ab5378b488225a1d8a9cbbbcbd38894" -dependencies = [ - "encoding 0.2.0 (git+https://github.com/lifthrasiir/rust-encoding)", -] +source = "git+https://github.com/servo/rust-url#46458f80e48c542b2f175e36e5b7d30782ca7dc5" [[package]] name = "util" @@ -664,13 +692,14 @@ dependencies = [ "string_cache 0.0.0 (git+https://github.com/servo/string-cache)", "string_cache_macros 0.0.0 (git+https://github.com/servo/string-cache)", "task_info 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", ] [[package]] name = "uuid" -version = "0.0.1" -source = "git+https://github.com/rust-lang/uuid#7c5af48d4f9074717199e05a1895f42b9fb1c1f0" +version = "0.0.2" +source = "git+https://github.com/rust-lang/uuid#f5d94d0043a615756edefaf9c6041f11e52b8370" [[package]] name = "xlib" @@ -680,5 +709,5 @@ source = "git+https://github.com/servo/rust-xlib#58ec3847b592aeabdcfeb6a2d02033d [[package]] name = "xxhash" version = "0.0.1" -source = "git+https://github.com/Jurily/rust-xxhash#7e4174e780af0cfb29a5e53ede0b987adca16396" +source = "git+https://github.com/Jurily/rust-xxhash#64f8d02314735f511cb4272563d0f703d575c159" diff --git a/ports/cef/browser.rs b/ports/cef/browser.rs index 2bd93ac1712..16d32658c77 100644 --- a/ports/cef/browser.rs +++ b/ports/cef/browser.rs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use browser_host::{ServoCefBrowserHost, ServoCefBrowserHostExtensions}; -use core::{mod, OffScreenGlobals, OnScreenGlobals, globals}; +use core::{mod, ServoCefGlobals, globals}; use eutil::Downcast; use frame::ServoCefFrame; use interfaces::{CefBrowser, CefBrowserHost, CefClient, CefFrame, CefRequestContext}; @@ -13,7 +13,7 @@ use servo::Browser; use types::{cef_browser_settings_t, cef_string_t, cef_window_info_t}; use window; -use compositing::windowing::{Back, Forward, NavigationWindowEvent}; +use compositing::windowing::{Back, Forward, WindowEvent}; use glfw_app; use libc::c_int; use servo_util::opts; @@ -26,11 +26,11 @@ cef_class_impl! { } fn go_back(&_this) -> () { - core::send_window_event(NavigationWindowEvent(Back)); + core::send_window_event(WindowEvent::Navigation(Back)); } fn go_forward(&_this) -> () { - core::send_window_event(NavigationWindowEvent(Forward)); + core::send_window_event(WindowEvent::Navigation(Forward)); } // Returns the main (top-level) frame for the browser window. @@ -57,8 +57,8 @@ impl ServoCefBrowser { let host = ServoCefBrowserHost::new(client.clone()).as_cef_interface(); if window_info.windowless_rendering_enabled == 0 { let glfw_window = glfw_app::create_window(); - globals.replace(Some(OnScreenGlobals(RefCell::new(glfw_window.clone()), - RefCell::new(Browser::new(Some(glfw_window)))))); + globals.replace(Some(ServoCefGlobals::OnScreenGlobals(RefCell::new(glfw_window.clone()), + RefCell::new(Browser::new(Some(glfw_window)))))); } ServoCefBrowser { @@ -80,8 +80,8 @@ impl ServoCefBrowserExtensions for CefBrowser { let window = window::Window::new(); let servo_browser = Browser::new(Some(window.clone())); window.set_browser(self.clone()); - globals.replace(Some(OffScreenGlobals(RefCell::new(window), - RefCell::new(servo_browser)))); + globals.replace(Some(ServoCefGlobals::OffScreenGlobals(RefCell::new(window), + RefCell::new(servo_browser)))); } self.downcast().host.set_browser((*self).clone()); diff --git a/ports/cef/browser_host.rs b/ports/cef/browser_host.rs index 66ec82af343..9fea6a6fa9c 100644 --- a/ports/cef/browser_host.rs +++ b/ports/cef/browser_host.rs @@ -5,12 +5,10 @@ use core; use eutil::Downcast; use interfaces::{CefBrowser, CefBrowserHost, CefClient, cef_browser_host_t, cef_client_t}; -use types::{KEYEVENT_CHAR, KEYEVENT_KEYDOWN, KEYEVENT_KEYUP, KEYEVENT_RAWKEYDOWN, cef_key_event}; -use types::{cef_mouse_button_type_t, cef_mouse_event, cef_rect_t}; +use types::{cef_mouse_button_type_t, cef_mouse_event, cef_rect_t, cef_key_event}; +use types::cef_key_event_type_t::{KEYEVENT_CHAR, KEYEVENT_KEYDOWN, KEYEVENT_KEYUP, KEYEVENT_RAWKEYDOWN}; -use compositing::windowing::{InitializeCompositingWindowEvent, KeyEvent, MouseWindowClickEvent}; -use compositing::windowing::{MouseWindowEventClass, MouseWindowMouseUpEvent, PinchZoomWindowEvent}; -use compositing::windowing::{ResizeWindowEvent, ScrollWindowEvent}; +use compositing::windowing::{WindowEvent, KeyEvent, MouseWindowEvent}; use geom::point::TypedPoint2D; use geom::size::TypedSize2D; use libc::{c_double, c_int}; @@ -36,7 +34,7 @@ cef_class_impl! { .get_render_handler() .get_backing_rect(this.downcast().browser.borrow().clone().unwrap(), &mut rect); let size = TypedSize2D(rect.width as uint, rect.height as uint); - core::send_window_event(ResizeWindowEvent(size)); + core::send_window_event(WindowEvent::Resize(size)); core::repaint_synchronously(); } @@ -45,44 +43,44 @@ cef_class_impl! { // Google working. let event: &cef_key_event = event; let key = match (*event).character as u8 { - b'a' | b'A' => constellation_msg::KeyA, - b'b' | b'B' => constellation_msg::KeyB, - b'c' | b'C' => constellation_msg::KeyC, - b'd' | b'D' => constellation_msg::KeyD, - b'e' | b'E' => constellation_msg::KeyE, - b'f' | b'F' => constellation_msg::KeyF, - b'g' | b'G' => constellation_msg::KeyG, - b'h' | b'H' => constellation_msg::KeyH, - b'i' | b'I' => constellation_msg::KeyI, - b'j' | b'J' => constellation_msg::KeyJ, - b'k' | b'K' => constellation_msg::KeyK, - b'l' | b'L' => constellation_msg::KeyL, - b'm' | b'M' => constellation_msg::KeyM, - b'n' | b'N' => constellation_msg::KeyN, - b'o' | b'O' => constellation_msg::KeyO, - b'p' | b'P' => constellation_msg::KeyP, - b'q' | b'Q' => constellation_msg::KeyQ, - b'r' | b'R' => constellation_msg::KeyR, - b's' | b'S' => constellation_msg::KeyS, - b't' | b'T' => constellation_msg::KeyT, - b'u' | b'U' => constellation_msg::KeyU, - b'v' | b'V' => constellation_msg::KeyV, - b'w' | b'W' => constellation_msg::KeyW, - b'x' | b'X' => constellation_msg::KeyX, - b'y' | b'Y' => constellation_msg::KeyY, - b'z' | b'Z' => constellation_msg::KeyZ, - b'0' => constellation_msg::Key0, - b'1' => constellation_msg::Key1, - b'2' => constellation_msg::Key2, - b'3' => constellation_msg::Key3, - b'4' => constellation_msg::Key4, - b'5' => constellation_msg::Key5, - b'6' => constellation_msg::Key6, - b'7' => constellation_msg::Key7, - b'8' => constellation_msg::Key8, - b'9' => constellation_msg::Key9, - b'\n' | b'\r' => constellation_msg::KeyEnter, - _ => constellation_msg::KeySpace, + b'a' | b'A' => constellation_msg::Key::A, + b'b' | b'B' => constellation_msg::Key::B, + b'c' | b'C' => constellation_msg::Key::C, + b'd' | b'D' => constellation_msg::Key::D, + b'e' | b'E' => constellation_msg::Key::E, + b'f' | b'F' => constellation_msg::Key::F, + b'g' | b'G' => constellation_msg::Key::G, + b'h' | b'H' => constellation_msg::Key::H, + b'i' | b'I' => constellation_msg::Key::I, + b'j' | b'J' => constellation_msg::Key::J, + b'k' | b'K' => constellation_msg::Key::K, + b'l' | b'L' => constellation_msg::Key::L, + b'm' | b'M' => constellation_msg::Key::M, + b'n' | b'N' => constellation_msg::Key::N, + b'o' | b'O' => constellation_msg::Key::O, + b'p' | b'P' => constellation_msg::Key::P, + b'q' | b'Q' => constellation_msg::Key::Q, + b'r' | b'R' => constellation_msg::Key::R, + b's' | b'S' => constellation_msg::Key::S, + b't' | b'T' => constellation_msg::Key::T, + b'u' | b'U' => constellation_msg::Key::U, + b'v' | b'V' => constellation_msg::Key::V, + b'w' | b'W' => constellation_msg::Key::W, + b'x' | b'X' => constellation_msg::Key::X, + b'y' | b'Y' => constellation_msg::Key::Y, + b'z' | b'Z' => constellation_msg::Key::Z, + b'0' => constellation_msg::Key::Num0, + b'1' => constellation_msg::Key::Num1, + b'2' => constellation_msg::Key::Num2, + b'3' => constellation_msg::Key::Num3, + b'4' => constellation_msg::Key::Num4, + b'5' => constellation_msg::Key::Num5, + b'6' => constellation_msg::Key::Num6, + b'7' => constellation_msg::Key::Num7, + b'8' => constellation_msg::Key::Num8, + b'9' => constellation_msg::Key::Num9, + b'\n' | b'\r' => constellation_msg::Key::Enter, + _ => constellation_msg::Key::Space, }; let key_state = match (*event).t { KEYEVENT_RAWKEYDOWN => Pressed, @@ -103,11 +101,11 @@ cef_class_impl! { let button_type = mouse_button_type as uint; let point = TypedPoint2D((*event).x as f32, (*event).y as f32); if mouse_up != 0 { - core::send_window_event(MouseWindowEventClass(MouseWindowClickEvent(button_type, - point))) + core::send_window_event(WindowEvent::MouseWindowEventClass( + MouseWindowEvent::MouseWindowClickEvent(button_type, point))) } else { - core::send_window_event(MouseWindowEventClass(MouseWindowMouseUpEvent(button_type, - point))) + core::send_window_event(WindowEvent::MouseWindowEventClass( + MouseWindowEvent::MouseWindowMouseUpEvent(button_type, point))) } } @@ -119,7 +117,7 @@ cef_class_impl! { let event: &cef_mouse_event = event; let delta = TypedPoint2D(delta_x as f32, delta_y as f32); let origin = TypedPoint2D((*event).x as i32, (*event).y as i32); - core::send_window_event(ScrollWindowEvent(delta, origin)) + core::send_window_event(WindowEvent::Scroll(delta, origin)) } fn get_zoom_level(&_this) -> c_double { @@ -128,11 +126,11 @@ cef_class_impl! { fn set_zoom_level(&this, new_zoom_level: c_double) -> () { let old_zoom_level = this.get_zoom_level(); - core::send_window_event(PinchZoomWindowEvent((new_zoom_level / old_zoom_level) as f32)) + core::send_window_event(WindowEvent::PinchZoom((new_zoom_level / old_zoom_level) as f32)) } fn initialize_compositing(&_this) -> () { - core::send_window_event(InitializeCompositingWindowEvent); + core::send_window_event(WindowEvent::InitializeCompositing); } } } diff --git a/ports/cef/core.rs b/ports/cef/core.rs index 8a895f76ebb..093db5188c8 100644 --- a/ports/cef/core.rs +++ b/ports/cef/core.rs @@ -7,7 +7,7 @@ use interfaces::cef_app_t; use types::{cef_main_args_t, cef_settings_t}; use window; -use compositing::windowing::{IdleWindowEvent, WindowEvent}; +use compositing::windowing::WindowEvent; use geom::size::TypedSize2D; use glfw_app; use libc::{c_char, c_int, c_void}; @@ -141,10 +141,10 @@ pub extern "C" fn cef_run_message_loop() { let mut the_globals = globals.get(); let the_globals = the_globals.as_mut().unwrap(); match **the_globals { - OnScreenGlobals(ref window, ref browser) => { + ServoCefGlobals::OnScreenGlobals(ref window, ref browser) => { while browser.borrow_mut().handle_event(window.borrow_mut().wait_events()) {} } - OffScreenGlobals(ref window, ref browser) => { + ServoCefGlobals::OffScreenGlobals(ref window, ref browser) => { while browser.borrow_mut().handle_event(window.borrow_mut().wait_events()) {} } } @@ -152,7 +152,7 @@ pub extern "C" fn cef_run_message_loop() { #[no_mangle] pub extern "C" fn cef_do_message_loop_work() { - send_window_event(IdleWindowEvent) + send_window_event(WindowEvent::Idle) } #[no_mangle] @@ -177,7 +177,7 @@ pub fn send_window_event(event: WindowEvent) { }; loop { match **the_globals { - OnScreenGlobals(_, ref browser) => { + ServoCefGlobals::OnScreenGlobals(_, ref browser) => { match browser.try_borrow_mut() { None => { // We're trying to send an event while processing another one. This will @@ -198,7 +198,7 @@ pub fn send_window_event(event: WindowEvent) { } } } - OffScreenGlobals(_, ref browser) => { + ServoCefGlobals::OffScreenGlobals(_, ref browser) => { match browser.try_borrow_mut() { None => { // We're trying to send an event while processing another one. This will @@ -233,8 +233,8 @@ macro_rules! browser_method_delegate( Some(the_globals) => the_globals, }; match **the_globals { - OnScreenGlobals(_, ref browser) => browser.borrow_mut().$method(), - OffScreenGlobals(_, ref browser) => browser.borrow_mut().$method(), + ServoCefGlobals::OnScreenGlobals(_, ref browser) => browser.borrow_mut().$method(), + ServoCefGlobals::OffScreenGlobals(_, ref browser) => browser.borrow_mut().$method(), } } )* diff --git a/ports/cef/frame.rs b/ports/cef/frame.rs index eb915fe9fe3..86651f93d64 100644 --- a/ports/cef/frame.rs +++ b/ports/cef/frame.rs @@ -7,7 +7,7 @@ use interfaces::{CefFrame, CefStringVisitor, cef_frame_t, cef_string_visitor_t}; use types::{cef_string_t, cef_string_userfree_t}; use core; -use compositing::windowing::LoadUrlWindowEvent; +use compositing::windowing::WindowEvent; use std::cell::RefCell; pub struct ServoCefFrame { @@ -29,7 +29,7 @@ cef_class_impl! { fn load_url(&this, url: *const cef_string_t) -> () { let this = this.downcast(); *this.url.borrow_mut() = String::from_utf16(url).unwrap(); - core::send_window_event(LoadUrlWindowEvent(String::from_utf16(url).unwrap())); + core::send_window_event(WindowEvent::LoadUrl(String::from_utf16(url).unwrap())); } fn get_url(&this) -> cef_string_userfree_t { let this = this.downcast(); diff --git a/ports/cef/render_handler.rs b/ports/cef/render_handler.rs index 13e277c061d..ef80b6ea881 100644 --- a/ports/cef/render_handler.rs +++ b/ports/cef/render_handler.rs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use interfaces::{CefBrowser, CefRenderHandler}; -use types::PET_VIEW; +use types::cef_paint_element_type_t::PET_VIEW; use std::ptr; diff --git a/ports/cef/window.rs b/ports/cef/window.rs index 271fc33c7af..56851533767 100644 --- a/ports/cef/window.rs +++ b/ports/cef/window.rs @@ -14,7 +14,7 @@ use types::cef_rect_t; use wrappers::Utf16Encoder; use compositing::compositor_task::{mod, CompositorProxy, CompositorReceiver}; -use compositing::windowing::{IdleWindowEvent, WindowEvent, WindowMethods}; +use compositing::windowing::{WindowEvent, WindowMethods}; use geom::scale_factor::ScaleFactor; use geom::size::TypedSize2D; use gleam::gl; @@ -85,7 +85,7 @@ impl Window { /// Currently unimplemented. pub fn wait_events(&self) -> WindowEvent { - IdleWindowEvent + WindowEvent::Idle } } diff --git a/ports/glfw/Cargo.toml b/ports/glfw/Cargo.toml index 4ecd611c198..b77d2ca306a 100644 --- a/ports/glfw/Cargo.toml +++ b/ports/glfw/Cargo.toml @@ -31,3 +31,6 @@ git = "https://github.com/servo/rust-cgl" [dependencies.gleam] git = "https://github.com/servo/gleam" + +[dependencies.time] +git = "https://github.com/rust-lang/time" diff --git a/ports/glfw/window.rs b/ports/glfw/window.rs index 450e8e371f6..05a4b68a0e0 100644 --- a/ports/glfw/window.rs +++ b/ports/glfw/window.rs @@ -8,12 +8,12 @@ use NestedEventLoopListener; use compositing::compositor_task::{mod, CompositorProxy, CompositorReceiver}; use compositing::windowing::{Forward, Back}; -use compositing::windowing::{IdleWindowEvent, ResizeWindowEvent}; +use compositing::windowing::{Idle, Resize}; use compositing::windowing::{KeyEvent, MouseWindowClickEvent, MouseWindowMouseDownEvent}; use compositing::windowing::{MouseWindowEventClass, MouseWindowMoveEventClass}; -use compositing::windowing::{MouseWindowMouseUpEvent, RefreshWindowEvent}; -use compositing::windowing::{NavigationWindowEvent, ScrollWindowEvent, ZoomWindowEvent}; -use compositing::windowing::{PinchZoomWindowEvent, QuitWindowEvent}; +use compositing::windowing::{MouseWindowMouseUpEvent, Refresh}; +use compositing::windowing::{Navigation, Scroll, Zoom}; +use compositing::windowing::{PinchZoom, Quit}; use compositing::windowing::{WindowEvent, WindowMethods}; use geom::point::{Point2D, TypedPoint2D}; use geom::scale_factor::ScaleFactor; @@ -26,9 +26,10 @@ use libc::c_int; use msg::compositor_msg::{Blank, FinishedLoading, IdlePaintState, Loading, PaintState}; use msg::compositor_msg::{PaintingPaintState, PerformingLayout, ReadyState}; use msg::constellation_msg::{mod, LoadData}; -use msg::constellation_msg::{Key, KeyModifiers, KeyEscape, KeyEqual, KeyMinus, KeyBackspace, KeyPageUp, KeyPageDown, CONTROL, SHIFT}; +use msg::constellation_msg::{Key, KeyModifiers, CONTROL, SHIFT}; use std::cell::{Cell, RefCell}; use std::comm::Receiver; +use std::num::Float; use std::rc::Rc; use time::{mod, Timespec}; use util::geometry::ScreenPx; @@ -120,9 +121,9 @@ impl Window { } if self.glfw_window.should_close() { - QuitWindowEvent + Quit } else { - self.event_queue.borrow_mut().remove(0).unwrap_or(IdleWindowEvent) + self.event_queue.borrow_mut().remove(0).unwrap_or(Idle) } } @@ -211,24 +212,24 @@ impl WindowMethods for Window { /// Helper function to handle keyboard events. fn handle_key(&self, key: Key, mods: KeyModifiers) { match key { - KeyEscape => self.glfw_window.set_should_close(true), - KeyEqual if mods.contains(CONTROL) => { // Ctrl-+ - self.event_queue.borrow_mut().push(ZoomWindowEvent(1.1)); + Key::Escape => self.glfw_window.set_should_close(true), + Key::Equal if mods.contains(CONTROL) => { // Ctrl-+ + self.event_queue.borrow_mut().push(Zoom(1.1)); } - KeyMinus if mods.contains(CONTROL) => { // Ctrl-- - self.event_queue.borrow_mut().push(ZoomWindowEvent(1.0/1.1)); + Key::Minus if mods.contains(CONTROL) => { // Ctrl-- + self.event_queue.borrow_mut().push(Zoom(1.0/1.1)); } - KeyBackspace if mods.contains(SHIFT) => { // Shift-Backspace - self.event_queue.borrow_mut().push(NavigationWindowEvent(Forward)); + Key::Backspace if mods.contains(SHIFT) => { // Shift-Backspace + self.event_queue.borrow_mut().push(Navigation(Forward)); } - KeyBackspace => { // Backspace - self.event_queue.borrow_mut().push(NavigationWindowEvent(Back)); + Key::Backspace => { // Backspace + self.event_queue.borrow_mut().push(Navigation(Back)); } - KeyPageDown => { + Key::PageDown => { let (_, height) = self.glfw_window.get_size(); self.scroll_window(0.0, -height as f32); } - KeyPageUp => { + Key::PageUp => { let (_, height) = self.glfw_window.get_size(); self.scroll_window(0.0, height as f32); } @@ -262,10 +263,10 @@ impl Window { }, glfw::FramebufferSizeEvent(width, height) => { self.event_queue.borrow_mut().push( - ResizeWindowEvent(TypedSize2D(width as uint, height as uint))); + Resize(TypedSize2D(width as uint, height as uint))); }, glfw::RefreshEvent => { - self.event_queue.borrow_mut().push(RefreshWindowEvent); + self.event_queue.borrow_mut().push(Refresh); }, glfw::MouseButtonEvent(button, action, _mods) => { let (x, y) = window.get_cursor_pos(); @@ -277,11 +278,11 @@ impl Window { let y = y as f32 * hidpi; match button { - glfw::MouseButton5 => { // Back button (might be different per platform) - self.event_queue.borrow_mut().push(NavigationWindowEvent(Back)); + glfw::MouseButton::Button5 => { // Back button (might be different per platform) + self.event_queue.borrow_mut().push(Navigation(Back)); }, - glfw::MouseButton6 => { // Forward - self.event_queue.borrow_mut().push(NavigationWindowEvent(Forward)); + glfw::MouseButton::Button6 => { // Forward + self.event_queue.borrow_mut().push(Navigation(Forward)); }, glfw::MouseButtonLeft | glfw::MouseButtonRight => { self.handle_mouse(button, action, x as i32, y as i32); @@ -294,14 +295,14 @@ impl Window { MouseWindowMoveEventClass(TypedPoint2D(xpos as f32, ypos as f32))); }, glfw::ScrollEvent(xpos, ypos) => { - match (window.get_key(glfw::KeyLeftControl), - window.get_key(glfw::KeyRightControl)) { + match (window.get_key(glfw::Key::LeftControl), + window.get_key(glfw::Key::RightControl)) { (glfw::Press, _) | (_, glfw::Press) => { // Ctrl-Scrollwheel simulates a "pinch zoom" gesture. if ypos < 0.0 { - self.event_queue.borrow_mut().push(PinchZoomWindowEvent(1.0/1.1)); + self.event_queue.borrow_mut().push(PinchZoom(1.0/1.1)); } else if ypos > 0.0 { - self.event_queue.borrow_mut().push(PinchZoomWindowEvent(1.1)); + self.event_queue.borrow_mut().push(PinchZoom(1.1)); } }, _ => { @@ -325,7 +326,7 @@ impl Window { let x = x as f32 * hidpi; let y = y as f32 * hidpi; - self.event_queue.borrow_mut().push(ScrollWindowEvent(TypedPoint2D(dx, dy), + self.event_queue.borrow_mut().push(Scroll(TypedPoint2D(dx, dy), TypedPoint2D(x as i32, y as i32))); } @@ -416,7 +417,7 @@ extern "C" fn on_refresh(_glfw_window: *mut glfw::ffi::GLFWwindow) { match g_nested_event_loop_listener { None => {} Some(listener) => { - (*listener).handle_event_from_nested_event_loop(RefreshWindowEvent); + (*listener).handle_event_from_nested_event_loop(Refresh); } } } @@ -430,7 +431,7 @@ extern "C" fn on_framebuffer_size(_glfw_window: *mut glfw::ffi::GLFWwindow, None => {} Some(listener) => { let size = TypedSize2D(width as uint, height as uint); - (*listener).handle_event_from_nested_event_loop(ResizeWindowEvent(size)); + (*listener).handle_event_from_nested_event_loop(Resize(size)); } } } @@ -456,132 +457,132 @@ fn glfw_mods_to_script_mods(mods: glfw::Modifiers) -> constellation_msg::KeyModi macro_rules! glfw_keys_to_script_keys( ($key:expr, $($name:ident),+) => ( match $key { - $(glfw::$name => constellation_msg::$name,)+ + $(glfw::Key::$name => constellation_msg::Key::$name,)+ } ); ) fn glfw_key_to_script_key(key: glfw::Key) -> constellation_msg::Key { glfw_keys_to_script_keys!(key, - KeySpace, - KeyApostrophe, - KeyComma, - KeyMinus, - KeyPeriod, - KeySlash, - Key0, - Key1, - Key2, - Key3, - Key4, - Key5, - Key6, - Key7, - Key8, - Key9, - KeySemicolon, - KeyEqual, - KeyA, - KeyB, - KeyC, - KeyD, - KeyE, - KeyF, - KeyG, - KeyH, - KeyI, - KeyJ, - KeyK, - KeyL, - KeyM, - KeyN, - KeyO, - KeyP, - KeyQ, - KeyR, - KeyS, - KeyT, - KeyU, - KeyV, - KeyW, - KeyX, - KeyY, - KeyZ, - KeyLeftBracket, - KeyBackslash, - KeyRightBracket, - KeyGraveAccent, - KeyWorld1, - KeyWorld2, - - KeyEscape, - KeyEnter, - KeyTab, - KeyBackspace, - KeyInsert, - KeyDelete, - KeyRight, - KeyLeft, - KeyDown, - KeyUp, - KeyPageUp, - KeyPageDown, - KeyHome, - KeyEnd, - KeyCapsLock, - KeyScrollLock, - KeyNumLock, - KeyPrintScreen, - KeyPause, - KeyF1, - KeyF2, - KeyF3, - KeyF4, - KeyF5, - KeyF6, - KeyF7, - KeyF8, - KeyF9, - KeyF10, - KeyF11, - KeyF12, - KeyF13, - KeyF14, - KeyF15, - KeyF16, - KeyF17, - KeyF18, - KeyF19, - KeyF20, - KeyF21, - KeyF22, - KeyF23, - KeyF24, - KeyF25, - KeyKp0, - KeyKp1, - KeyKp2, - KeyKp3, - KeyKp4, - KeyKp5, - KeyKp6, - KeyKp7, - KeyKp8, - KeyKp9, - KeyKpDecimal, - KeyKpDivide, - KeyKpMultiply, - KeyKpSubtract, - KeyKpAdd, - KeyKpEnter, - KeyKpEqual, - KeyLeftShift, - KeyLeftControl, - KeyLeftAlt, - KeyLeftSuper, - KeyRightShift, - KeyRightControl, - KeyRightAlt, - KeyRightSuper, - KeyMenu) + Space, + Apostrophe, + Comma, + Minus, + Period, + Slash, + Num0, + Num1, + Num2, + Num3, + Num4, + Num5, + Num6, + Num7, + Num8, + Num9, + Semicolon, + Equal, + A, + B, + C, + D, + E, + F, + G, + H, + I, + J, + K, + L, + M, + N, + O, + P, + Q, + R, + S, + T, + U, + V, + W, + X, + Y, + Z, + LeftBracket, + Backslash, + RightBracket, + GraveAccent, + World1, + World2, + + Escape, + Enter, + Tab, + Backspace, + Insert, + Delete, + Right, + Left, + Down, + Up, + PageUp, + PageDown, + Home, + End, + CapsLock, + ScrollLock, + NumLock, + PrintScreen, + Pause, + F1, + F2, + F3, + F4, + F5, + F6, + F7, + F8, + F9, + F10, + F11, + F12, + F13, + F14, + F15, + F16, + F17, + F18, + F19, + F20, + F21, + F22, + F23, + F24, + F25, + Kp0, + Kp1, + Kp2, + Kp3, + Kp4, + Kp5, + Kp6, + Kp7, + Kp8, + Kp9, + KpDecimal, + KpDivide, + KpMultiply, + KpSubtract, + KpAdd, + KpEnter, + KpEqual, + LeftShift, + LeftControl, + LeftAlt, + LeftSuper, + RightShift, + RightControl, + RightAlt, + RightSuper, + Menu) } diff --git a/ports/glutin/Cargo.toml b/ports/glutin/Cargo.toml index 26149522424..57d89f5949b 100644 --- a/ports/glutin/Cargo.toml +++ b/ports/glutin/Cargo.toml @@ -23,7 +23,8 @@ path = "../../components/msg" path = "../../components/util" [dependencies.glutin] -git = "https://github.com/tomaka/glutin" +git = "https://github.com/servo/glutin" +branch = "servo" features = ["window", "headless"] [dependencies.gleam] @@ -31,3 +32,6 @@ git = "https://github.com/servo/gleam" [dependencies.cgl] git = "https://github.com/servo/rust-cgl" + +[dependencies.time] +git = "https://github.com/rust-lang/time" diff --git a/ports/glutin/window.rs b/ports/glutin/window.rs index 36cdfd047c0..70ef9fcfd1b 100644 --- a/ports/glutin/window.rs +++ b/ports/glutin/window.rs @@ -6,10 +6,10 @@ use compositing::compositor_task::{mod, CompositorProxy, CompositorReceiver}; use compositing::windowing::{WindowEvent, WindowMethods, KeyEvent}; -use compositing::windowing::{IdleWindowEvent, ResizeWindowEvent}; -use compositing::windowing::{MouseWindowEventClass, MouseWindowMoveEventClass, ScrollWindowEvent}; -use compositing::windowing::{ZoomWindowEvent, PinchZoomWindowEvent, NavigationWindowEvent}; -use compositing::windowing::{QuitWindowEvent, MouseWindowClickEvent}; +use compositing::windowing::{Idle, Resize}; +use compositing::windowing::{MouseWindowEventClass, MouseWindowMoveEventClass, Scroll}; +use compositing::windowing::{Zoom, PinchZoom, Navigation}; +use compositing::windowing::{Quit, MouseWindowClickEvent}; use compositing::windowing::{MouseWindowMouseDownEvent, MouseWindowMouseUpEvent}; use compositing::windowing::{Forward, Back}; use geom::point::{Point2D, TypedPoint2D}; @@ -18,17 +18,19 @@ use geom::size::TypedSize2D; use layers::geometry::DevicePixel; use layers::platform::surface::NativeGraphicsMetadata; use msg::constellation_msg; -use msg::constellation_msg::{Key, KeyEscape, KeyEqual, KeyMinus, KeyBackspace, KeyPageUp, KeyPageDown, CONTROL, SHIFT, ALT}; +use msg::constellation_msg::{Key, CONTROL, SHIFT, ALT}; use msg::compositor_msg::{IdlePaintState, PaintState, PaintingPaintState}; use msg::compositor_msg::{FinishedLoading, Blank, Loading, PerformingLayout, ReadyState}; use msg::constellation_msg::LoadData; use std::cell::{Cell, RefCell}; +use std::num::Float; use std::rc::Rc; use time::{mod, Timespec}; use util::geometry::ScreenPx; use util::opts::{RenderApi, Mesa, OpenGL}; use gleam::gl; use glutin; +use glutin::{ElementState, Event, MouseButton, VirtualKeyCode}; use NestedEventLoopListener; #[cfg(target_os="linux")] @@ -113,7 +115,7 @@ impl Window { .unwrap(); unsafe { glutin_window.make_current() }; - Windowed(glutin_window) + WindowHandle::Windowed(glutin_window) } Mesa => { let headless_builder = glutin::HeadlessRendererBuilder::new(window_size.width, @@ -121,7 +123,7 @@ impl Window { let headless_context = headless_builder.build().unwrap(); unsafe { headless_context.make_current() }; - Headless(HeadlessContext { + WindowHandle::Headless(HeadlessContext { context: headless_context, size: size, }) @@ -157,9 +159,9 @@ impl WindowMethods for Window { /// Returns the size of the window in hardware pixels. fn framebuffer_size(&self) -> TypedSize2D<DevicePixel, uint> { let (width, height) = match self.glutin { - Windowed(ref window) => window.get_inner_size(), - Headless(ref context) => Some((context.size.to_untyped().width, - context.size.to_untyped().height)), + WindowHandle::Windowed(ref window) => window.get_inner_size(), + WindowHandle::Headless(ref context) => Some((context.size.to_untyped().width, + context.size.to_untyped().height)), }.unwrap(); TypedSize2D(width as uint, height as uint) } @@ -168,9 +170,9 @@ impl WindowMethods for Window { fn size(&self) -> TypedSize2D<ScreenPx, f32> { // TODO: Handle hidpi let (width, height) = match self.glutin { - Windowed(ref window) => window.get_inner_size(), - Headless(ref context) => Some((context.size.to_untyped().width, - context.size.to_untyped().height)), + WindowHandle::Windowed(ref window) => window.get_inner_size(), + WindowHandle::Headless(ref context) => Some((context.size.to_untyped().width, + context.size.to_untyped().height)), }.unwrap(); TypedSize2D(width as f32, height as f32) } @@ -178,8 +180,8 @@ impl WindowMethods for Window { /// Presents the window to the screen (perhaps by page flipping). fn present(&self) { match self.glutin { - Windowed(ref window) => window.swap_buffers(), - Headless(_) => {}, + WindowHandle::Windowed(ref window) => window.swap_buffers(), + WindowHandle::Headless(_) => {}, } } @@ -263,23 +265,23 @@ impl WindowMethods for Window { fn handle_key(&self, key: Key, mods: constellation_msg::KeyModifiers) { match key { // TODO(negge): handle window close event - KeyEscape => {}, - KeyEqual if mods.contains(CONTROL) => { // Ctrl-+ - self.event_queue.borrow_mut().push(ZoomWindowEvent(1.1)); + Key::Escape => {}, + Key::Equal if mods.contains(CONTROL) => { // Ctrl-+ + self.event_queue.borrow_mut().push(Zoom(1.1)); } - KeyMinus if mods.contains(CONTROL) => { // Ctrl-- - self.event_queue.borrow_mut().push(ZoomWindowEvent(1.0/1.1)); + Key::Minus if mods.contains(CONTROL) => { // Ctrl-- + self.event_queue.borrow_mut().push(Zoom(1.0/1.1)); } - KeyBackspace if mods.contains(SHIFT) => { // Shift-Backspace - self.event_queue.borrow_mut().push(NavigationWindowEvent(Forward)); + Key::Backspace if mods.contains(SHIFT) => { // Shift-Backspace + self.event_queue.borrow_mut().push(Navigation(Forward)); } - KeyBackspace => { // Backspace - self.event_queue.borrow_mut().push(NavigationWindowEvent(Back)); + Key::Backspace => { // Backspace + self.event_queue.borrow_mut().push(Navigation(Back)); } - KeyPageDown => { + Key::PageDown => { self.scroll_window(0.0, -self.framebuffer_size().as_f32().to_untyped().height); } - KeyPageUp => { + Key::PageUp => { self.scroll_window(0.0, self.framebuffer_size().as_f32().to_untyped().height); } _ => {} @@ -291,7 +293,7 @@ impl Window { /// Helper function to set the window title in accordance with the ready state. fn update_window_title(&self) { match self.glutin { - Windowed(ref window) => { + WindowHandle::Windowed(ref window) => { let now = time::get_time(); if now.sec == self.last_title_set_time.get().sec { return @@ -320,7 +322,7 @@ impl Window { } } } - Headless(_) => {}, + WindowHandle::Headless(_) => {}, } } } @@ -342,12 +344,12 @@ fn glutin_mods_to_script_mods(modifiers: KeyModifiers) -> constellation_msg::Key fn glutin_key_to_script_key(key: glutin::VirtualKeyCode) -> Result<constellation_msg::Key, ()> { // TODO(negge): add more key mappings match key { - glutin::Escape => Ok(KeyEscape), - glutin::Equals => Ok(KeyEqual), - glutin::Minus => Ok(KeyMinus), - glutin::Back => Ok(KeyBackspace), - glutin::PageDown => Ok(KeyPageDown), - glutin::PageUp => Ok(KeyPageUp), + VirtualKeyCode::Escape => Ok(Key::Escape), + VirtualKeyCode::Equals => Ok(Key::Equal), + VirtualKeyCode::Minus => Ok(Key::Minus), + VirtualKeyCode::Back => Ok(Key::Backspace), + VirtualKeyCode::PageDown => Ok(Key::PageDown), + VirtualKeyCode::PageUp => Ok(Key::PageUp), _ => Err(()), } } @@ -355,18 +357,18 @@ fn glutin_key_to_script_key(key: glutin::VirtualKeyCode) -> Result<constellation impl Window { fn handle_window_event(&self, event: glutin::Event) -> bool { match event { - glutin::KeyboardInput(element_state, _scan_code, virtual_key_code) => { + Event::KeyboardInput(element_state, _scan_code, virtual_key_code) => { if virtual_key_code.is_some() { let virtual_key_code = virtual_key_code.unwrap(); match (element_state, virtual_key_code) { - (_, glutin::LControl) => self.toggle_modifier(LEFT_CONTROL), - (_, glutin::RControl) => self.toggle_modifier(RIGHT_CONTROL), - (_, glutin::LShift) => self.toggle_modifier(LEFT_SHIFT), - (_, glutin::RShift) => self.toggle_modifier(RIGHT_SHIFT), - (_, glutin::LAlt) => self.toggle_modifier(LEFT_ALT), - (_, glutin::RAlt) => self.toggle_modifier(RIGHT_ALT), - (glutin::Pressed, key_code) => { + (_, VirtualKeyCode::LControl) => self.toggle_modifier(LEFT_CONTROL), + (_, VirtualKeyCode::RControl) => self.toggle_modifier(RIGHT_CONTROL), + (_, VirtualKeyCode::LShift) => self.toggle_modifier(LEFT_SHIFT), + (_, VirtualKeyCode::RShift) => self.toggle_modifier(RIGHT_SHIFT), + (_, VirtualKeyCode::LAlt) => self.toggle_modifier(LEFT_ALT), + (_, VirtualKeyCode::RAlt) => self.toggle_modifier(RIGHT_ALT), + (ElementState::Pressed, key_code) => { match glutin_key_to_script_key(key_code) { Ok(key) => { let state = constellation_msg::Pressed; @@ -380,28 +382,28 @@ impl Window { } } } - glutin::Resized(width, height) => { - self.event_queue.borrow_mut().push(ResizeWindowEvent(TypedSize2D(width, height))); + Event::Resized(width, height) => { + self.event_queue.borrow_mut().push(Resize(TypedSize2D(width, height))); } - glutin::MouseInput(element_state, mouse_button) => { - if mouse_button == glutin::LeftMouseButton || - mouse_button == glutin::RightMouseButton { + Event::MouseInput(element_state, mouse_button) => { + if mouse_button == MouseButton::LeftMouseButton || + mouse_button == MouseButton::RightMouseButton { let mouse_pos = self.mouse_pos.get(); self.handle_mouse(mouse_button, element_state, mouse_pos.x, mouse_pos.y); } } - glutin::MouseMoved((x, y)) => { + Event::MouseMoved((x, y)) => { self.mouse_pos.set(Point2D(x, y)); self.event_queue.borrow_mut().push( MouseWindowMoveEventClass(TypedPoint2D(x as f32, y as f32))); } - glutin::MouseWheel(delta) => { + Event::MouseWheel(delta) => { if self.ctrl_pressed() { // Ctrl-Scrollwheel simulates a "pinch zoom" gesture. if delta < 0 { - self.event_queue.borrow_mut().push(PinchZoomWindowEvent(1.0/1.1)); + self.event_queue.borrow_mut().push(PinchZoom(1.0/1.1)); } else if delta > 0 { - self.event_queue.borrow_mut().push(PinchZoomWindowEvent(1.1)); + self.event_queue.borrow_mut().push(PinchZoom(1.1)); } } else { let dx = 0.0; @@ -429,8 +431,8 @@ impl Window { /// Helper function to send a scroll event. fn scroll_window(&self, dx: f32, dy: f32) { let mouse_pos = self.mouse_pos.get(); - let event = ScrollWindowEvent(TypedPoint2D(dx as f32, dy as f32), - TypedPoint2D(mouse_pos.x as i32, mouse_pos.y as i32)); + let event = Scroll(TypedPoint2D(dx as f32, dy as f32), + TypedPoint2D(mouse_pos.x as i32, mouse_pos.y as i32)); self.event_queue.borrow_mut().push(event); } @@ -439,12 +441,12 @@ impl Window { // FIXME(tkuehn): max pixel dist should be based on pixel density let max_pixel_dist = 10f64; let event = match action { - glutin::Pressed => { + ElementState::Pressed => { self.mouse_down_point.set(Point2D(x, y)); self.mouse_down_button.set(Some(button)); MouseWindowMouseDownEvent(0, TypedPoint2D(x as f32, y as f32)) } - glutin::Released => { + ElementState::Released => { match self.mouse_down_button.get() { None => (), Some(but) if button == but => { @@ -493,7 +495,7 @@ impl Window { } match self.glutin { - Windowed(ref window) => { + WindowHandle::Windowed(ref window) => { let mut close_event = false; for event in window.wait_events() { close_event = self.handle_window_event(event); @@ -503,13 +505,13 @@ impl Window { } if close_event || window.is_closed() { - QuitWindowEvent + Quit } else { - self.event_queue.borrow_mut().remove(0).unwrap_or(IdleWindowEvent) + self.event_queue.borrow_mut().remove(0).unwrap_or(Idle) } } - Headless(_) => { - self.event_queue.borrow_mut().remove(0).unwrap_or(IdleWindowEvent) + WindowHandle::Headless(_) => { + self.event_queue.borrow_mut().remove(0).unwrap_or(Idle) } } } diff --git a/ports/gonk/Cargo.lock b/ports/gonk/Cargo.lock index 2386b9e2379..7e0c096994f 100644 --- a/ports/gonk/Cargo.lock +++ b/ports/gonk/Cargo.lock @@ -9,6 +9,7 @@ dependencies = [ "msg 0.0.1", "script 0.0.1", "servo 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "util 0.0.1", ] @@ -63,6 +64,7 @@ dependencies = [ "net 0.0.1", "png 0.1.0 (git+https://github.com/servo/rust-png)", "script_traits 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", "util 0.0.1", ] @@ -70,9 +72,10 @@ dependencies = [ [[package]] name = "cookie" version = "0.0.1" -source = "git+https://github.com/servo/cookie-rs#30520767a95b92e39265aaf6822db515b2418f1d" +source = "git+https://github.com/servo/cookie-rs#f82090b19c2738b90528167ef873d8eac0353294" dependencies = [ "openssl 0.0.1 (git+https://github.com/servo/rust-openssl)", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", ] @@ -101,7 +104,7 @@ dependencies = [ [[package]] name = "cssparser" version = "0.1.0" -source = "git+https://github.com/servo/rust-cssparser#3f98f1308b769b5d61efc6c133ac520df2b074ac" +source = "git+https://github.com/servo/rust-cssparser#97d8c3b20a240881573748d4eadcda610bfb888c" dependencies = [ "encoding 0.2.0 (git+https://github.com/lifthrasiir/rust-encoding)", ] @@ -197,6 +200,11 @@ version = "2.4.11" source = "git+https://github.com/servo/libfreetype2#5b6499164106f094937565595c7b96d07de55521" [[package]] +name = "gcc" +version = "0.1.1" +source = "git+https://github.com/alexcrichton/gcc-rs#d35c34c871dd75f97fadf04cb0ed85d997a9bc0c" + +[[package]] name = "geom" version = "0.1.0" source = "git+https://github.com/servo/rust-geom#e5e74911ac6d3201009879b72499d6c681302611" @@ -221,6 +229,7 @@ dependencies = [ "script_traits 0.0.1", "stb_image 0.1.0 (git+https://github.com/servo/rust-stb-image)", "style 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", "util 0.0.1", ] @@ -264,19 +273,20 @@ source = "git+https://github.com/servo/rust-harfbuzz#8aab215463214647b7a81f66011 [[package]] name = "html5ever" version = "0.0.0" -source = "git+https://github.com/servo/html5ever?ref=servo#87c7e8b710391338b2463652be835f498923653c" +source = "git+https://github.com/servo/html5ever#e6f8d83de9fffe63a825d95d957ba6bcbc3e1632" dependencies = [ - "html5ever_macros 0.0.0 (git+https://github.com/servo/html5ever?ref=servo)", + "html5ever_macros 0.0.0 (git+https://github.com/servo/html5ever)", "phf 0.0.0 (git+https://github.com/sfackler/rust-phf)", "phf_mac 0.0.0 (git+https://github.com/sfackler/rust-phf)", "string_cache 0.0.0 (git+https://github.com/servo/string-cache)", "string_cache_macros 0.0.0 (git+https://github.com/servo/string-cache)", + "time 0.1.0 (git+https://github.com/rust-lang/time)", ] [[package]] name = "html5ever_macros" version = "0.0.0" -source = "git+https://github.com/servo/html5ever?ref=servo#87c7e8b710391338b2463652be835f498923653c" +source = "git+https://github.com/servo/html5ever#e6f8d83de9fffe63a825d95d957ba6bcbc3e1632" [[package]] name = "hyper" @@ -412,6 +422,7 @@ dependencies = [ "hyper 0.0.1 (git+https://github.com/servo/hyper?ref=servo)", "png 0.1.0 (git+https://github.com/servo/rust-png)", "stb_image 0.1.0 (git+https://github.com/servo/rust-stb-image)", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", "util 0.0.1", ] @@ -491,7 +502,7 @@ dependencies = [ "encoding 0.2.0 (git+https://github.com/lifthrasiir/rust-encoding)", "geom 0.1.0 (git+https://github.com/servo/rust-geom)", "gfx 0.0.1", - "html5ever 0.0.0 (git+https://github.com/servo/html5ever?ref=servo)", + "html5ever 0.0.0 (git+https://github.com/servo/html5ever)", "hyper 0.0.1 (git+https://github.com/servo/hyper?ref=servo)", "js 0.1.0 (git+https://github.com/servo/rust-mozjs)", "msg 0.0.1", @@ -501,6 +512,7 @@ dependencies = [ "string_cache 0.0.0 (git+https://github.com/servo/string-cache)", "string_cache_macros 0.0.0 (git+https://github.com/servo/string-cache)", "style 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", "util 0.0.1", "uuid 0.0.1 (git+https://github.com/rust-lang/uuid)", @@ -528,6 +540,7 @@ dependencies = [ "msg 0.0.1", "net 0.0.1", "script 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", "util 0.0.1", ] @@ -586,6 +599,14 @@ name = "task_info" version = "0.0.1" [[package]] +name = "time" +version = "0.1.0" +source = "git+https://github.com/rust-lang/time#afab521f3b91658a3ba2d3e877b7e01699733bef" +dependencies = [ + "gcc 0.1.1 (git+https://github.com/alexcrichton/gcc-rs)", +] + +[[package]] name = "typeable" version = "0.0.3" source = "git+https://github.com/reem/rust-typeable#db8975daaa3889871f67eea11baeaefd8e706eaf" @@ -598,10 +619,7 @@ source = "git+https://github.com/reem/rust-unsafe-any#eb3fe87bea85f375b8fcefa0cd [[package]] name = "url" version = "0.1.0" -source = "git+https://github.com/servo/rust-url#8a61b7654ab5378b488225a1d8a9cbbbcbd38894" -dependencies = [ - "encoding 0.2.0 (git+https://github.com/lifthrasiir/rust-encoding)", -] +source = "git+https://github.com/servo/rust-url#46458f80e48c542b2f175e36e5b7d30782ca7dc5" [[package]] name = "util" @@ -613,6 +631,7 @@ dependencies = [ "string_cache 0.0.0 (git+https://github.com/servo/string-cache)", "string_cache_macros 0.0.0 (git+https://github.com/servo/string-cache)", "task_info 0.0.1", + "time 0.1.0 (git+https://github.com/rust-lang/time)", "url 0.1.0 (git+https://github.com/servo/rust-url)", ] diff --git a/ports/gonk/Cargo.toml b/ports/gonk/Cargo.toml index a1fd09e3b0d..ac0740b1ba9 100644 --- a/ports/gonk/Cargo.toml +++ b/ports/gonk/Cargo.toml @@ -29,3 +29,6 @@ path = "../../components/util" [dependencies.egl] git = "https://github.com/servo/rust-egl" + +[dependencies.time] +git = "https://github.com/rust-lang/time" diff --git a/rust-snapshot-hash b/rust-snapshot-hash index 3098d8fa57d..784693ecb7f 100644 --- a/rust-snapshot-hash +++ b/rust-snapshot-hash @@ -1 +1 @@ -b03a2755193cd756583bcf5831cf4545d75ecb8a/rust-0.13.0-dev +3dcd2157403163789aaf21a9ab3c4d30a7c6494d/rust-0.13.0-dev diff --git a/tests/reftest.rs b/tests/reftest.rs index 85a4d9c7b56..aba5847e080 100644 --- a/tests/reftest.rs +++ b/tests/reftest.rs @@ -183,8 +183,8 @@ fn parse_lists(file: &Path, servo_args: &[String], render_mode: RenderMode, id_o }; let kind = match test_line.kind { - "==" => Same, - "!=" => Different, + "==" => ReftestKind::Same, + "!=" => ReftestKind::Different, part => panic!("reftest line: '{:s}' has invalid kind '{:s}'", line, part) }; @@ -326,11 +326,11 @@ fn check_reftest(reftest: Reftest) { assert!(res.is_ok()); match (reftest.kind, reftest.is_flaky) { - (Same, true) => println!("flaky test - rendering difference: {}", output_str), - (Same, false) => panic!("rendering difference: {}", output_str), - (Different, _) => {} // Result was different and that's what was expected + (ReftestKind::Same, true) => println!("flaky test - rendering difference: {}", output_str), + (ReftestKind::Same, false) => panic!("rendering difference: {}", output_str), + (ReftestKind::Different, _) => {} // Result was different and that's what was expected } } else { - assert!(reftest.is_flaky || reftest.kind == Same); + assert!(reftest.is_flaky || reftest.kind == ReftestKind::Same); } } |