Update rustc to revision 3dcd2157403163789aaf21a9ab3c4d30a7c6494d.

This commit is contained in:
Ms2ger 2014-12-17 10:42:52 +01:00 committed by Josh Matthews
parent b8900782b0
commit 466faac2a5
223 changed files with 4414 additions and 4105 deletions

View file

@ -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,
}
}
});

View file

@ -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"

View file

@ -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,9 +499,10 @@ 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(),
let first_child = CompositorData::new_layer(
root_layer_pipeline.clone(),
layer_properties,
DoesntWantScrollEvents,
WantsScrollEventsFlag::DoesntWantScrollEvents,
opts::get().tile_size);
// Add the first child / base layer to the front of the child list, so that
@ -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();
}

View file

@ -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
}
}

View file

@ -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"),
}
}
}

View file

@ -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,7 +334,8 @@ 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,
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,7 +683,8 @@ 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,
compositor_proxy.send(CompositorMsg::SetLayerOrigin(
pipeline.id,
LayerId::null(),
rect.to_untyped().origin));
} else {
@ -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);

View file

@ -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 {

View file

@ -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,
}
}
}

View file

@ -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"),
}
}
}

View file

@ -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 {

View file

@ -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,

View file

@ -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"

View file

@ -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};

View file

@ -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);

View file

@ -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);
}

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -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};

View file

@ -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)]

View file

@ -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())
}
}

View file

@ -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,
}
}

View file

@ -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

View file

@ -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;

View file

@ -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),
}
}
}

View file

@ -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);
}

View file

@ -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,
}
}

View file

@ -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),
InlineAbsoluteHypothetical(InlineAbsoluteHypotheticalFragmentInfo),
InlineBlockFragment(InlineBlockFragmentInfo),
ScannedTextFragment(Box<ScannedTextFragmentInfo>),
TableFragment,
TableCellFragment,
TableColumnFragment(TableColumnFragmentInfo),
TableRowFragment,
TableWrapperFragment,
UnscannedTextFragment(UnscannedTextFragmentInfo),
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)
}

View file

@ -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();

View file

@ -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();

View file

@ -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 {

View file

@ -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 doesnt
/// 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)
}
}

View file

@ -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();

View file

@ -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 {

View file

@ -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 {

View file

@ -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) {

View file

@ -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;

View file

@ -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 {

View file

@ -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
}
}
}

View file

@ -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

View file

@ -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);
}

View file

@ -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(),
}

View file

@ -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

View file

@ -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,
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,
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,
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! {

View file

@ -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"

View file

@ -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

View file

@ -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 {

View file

@ -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};

View file

@ -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};

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -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);
}
}

View file

@ -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;

View file

@ -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
}
}

View file

@ -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;

View file

@ -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) => {

View file

@ -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"

View file

@ -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(),

View file

@ -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 {

View file

@ -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,
}
}

View file

@ -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([
unionStructs[name] = CGList([
CGUnionStruct(t, provider),
CGUnionConversionStruct(t, provider)
]), [], imports),
public=True)
])
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)
decl = """
#[repr(uint)]
#[deriving(PartialEq)]
#[jstraceable]
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;
#[repr(uint)]
#[deriving(PartialEq)]
#[jstraceable]
pub enum valuelist {
%s
}
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"),
])

View file

@ -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) };

View file

@ -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};

View file

@ -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

View file

@ -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
}
}

View file

@ -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
}
}

View file

@ -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
}
}

View file

@ -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)
}
}

View file

@ -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;

View file

@ -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)
}

View file

@ -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
}
}

View file

@ -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)
}

View file

@ -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),
}
}

View file

@ -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())

View file

@ -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()

View file

@ -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);
{

View file

@ -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)

View file

@ -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 {

View file

@ -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};

View file

@ -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,
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,
ElementTypeId_,
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)
},

View file

@ -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,

View file

@ -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))
}

View file

@ -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()

View file

@ -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() {

View file

@ -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)
}

View file

@ -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)));
}
}

View file

@ -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(),
}
}

View file

@ -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)
}
}

View file

@ -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(),
}
}

View file

@ -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)
}
}

View file

@ -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)
}
}

View file

@ -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),

View file

@ -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)
}
}

View file

@ -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)
}
}

View file

@ -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),

View file

@ -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))

View file

@ -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)
}
}

View file

@ -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)
}
}

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