auto merge of #2238 : mozilla/servo/rustup_20140410c, r=Ms2ger

r? @metajack 

Note that all pending submodule PRs must be landed before this should be given r+.
This commit is contained in:
bors-servo 2014-04-27 18:52:39 -04:00
commit 493aa2cdf3
226 changed files with 1478 additions and 1407 deletions

View file

@ -350,7 +350,7 @@ libservo.dummy: $(DEPS_servo)
else else
servo: $(DEPS_servo) servo: $(DEPS_servo)
@$(call E, compile: $@) @$(call E, compile: $@)
$(Q)$(RUSTC) $(RFLAGS_servo) -C gen-crate-map $< -o libservo.so --crate-type dylib $(Q)$(RUSTC) $(RFLAGS_servo) $< -o libservo.so --crate-type dylib
touch servo touch servo
endif endif

@ -1 +1 @@
Subproject commit aa39d755e3f9823b51cc57761c0c8c75759aca2e Subproject commit 5099b8c863150675450631347436b7d220f4efd3

View file

@ -1,4 +1,4 @@
# If this file is modified, then rust will be forcibly cleaned and then rebuilt. # If this file is modified, then rust will be forcibly cleaned and then rebuilt.
# The actual contents of this file do not matter, but to trigger a change on the # The actual contents of this file do not matter, but to trigger a change on the
# build bots then the contents should be changed so git updates the mtime. # build bots then the contents should be changed so git updates the mtime.
2014-03-23 2014-04-10b

View file

@ -15,7 +15,7 @@ use std::mem;
/// needs it. /// needs it.
pub struct BufferMap<T> { pub struct BufferMap<T> {
/// A HashMap that stores the Buffers. /// A HashMap that stores the Buffers.
priv map: HashMap<BufferKey, BufferValue<T>>, map: HashMap<BufferKey, BufferValue<T>>,
/// The current amount of memory stored by the BufferMap's buffers. /// The current amount of memory stored by the BufferMap's buffers.
mem: uint, mem: uint,
/// The maximum allowed memory. Unused buffers will be deleted /// The maximum allowed memory. Unused buffers will be deleted
@ -26,6 +26,7 @@ pub struct BufferMap<T> {
} }
/// A key with which to store buffers. It is based on the size of the buffer. /// A key with which to store buffers. It is based on the size of the buffer.
#[deriving(TotalEq)]
struct BufferKey([uint, ..2]); struct BufferKey([uint, ..2]);
impl Hash for BufferKey { impl Hash for BufferKey {
@ -43,12 +44,6 @@ impl Eq for BufferKey {
} }
} }
impl TotalEq for BufferKey {
fn equals(&self, other: &BufferKey) -> bool {
self.eq(other)
}
}
/// Create a key from a given size /// Create a key from a given size
impl BufferKey { impl BufferKey {
fn get(input: Size2D<uint>) -> BufferKey { fn get(input: Size2D<uint>) -> BufferKey {

View file

@ -19,11 +19,11 @@ use render_context::RenderContext;
use text::TextRun; use text::TextRun;
use geom::{Point2D, Rect, SideOffsets2D, Size2D}; use geom::{Point2D, Rect, SideOffsets2D, Size2D};
use libc::uintptr_t;
use servo_net::image::base::Image; use servo_net::image::base::Image;
use servo_util::geometry::Au; use servo_util::geometry::Au;
use servo_util::range::Range; use servo_util::range::Range;
use servo_util::smallvec::{SmallVec, SmallVec0, SmallVecIterator}; use servo_util::smallvec::{SmallVec, SmallVec0, SmallVecIterator};
use std::libc::uintptr_t;
use std::mem; use std::mem;
use std::slice::Items; use std::slice::Items;
use style::computed_values::border_style; use style::computed_values::border_style;
@ -36,7 +36,7 @@ use sync::Arc;
/// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for /// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for
/// locality reasons. Using `OpaqueNode` enforces this invariant. /// locality reasons. Using `OpaqueNode` enforces this invariant.
#[deriving(Clone, Eq)] #[deriving(Clone, Eq)]
pub struct OpaqueNode(uintptr_t); pub struct OpaqueNode(pub uintptr_t);
impl OpaqueNode { impl OpaqueNode {
/// Returns the address of this node, for debugging purposes. /// Returns the address of this node, for debugging purposes.
@ -52,20 +52,20 @@ impl OpaqueNode {
/// TODO(pcwalton): Outlines. /// TODO(pcwalton): Outlines.
pub struct StackingContext { pub struct StackingContext {
/// The border and backgrounds for the root of this stacking context: steps 1 and 2. /// The border and backgrounds for the root of this stacking context: steps 1 and 2.
background_and_borders: DisplayList, pub background_and_borders: DisplayList,
/// Borders and backgrounds for block-level descendants: step 4. /// Borders and backgrounds for block-level descendants: step 4.
block_backgrounds_and_borders: DisplayList, pub block_backgrounds_and_borders: DisplayList,
/// Floats: step 5. These are treated as pseudo-stacking contexts. /// Floats: step 5. These are treated as pseudo-stacking contexts.
floats: DisplayList, pub floats: DisplayList,
/// All other content. /// All other content.
content: DisplayList, pub content: DisplayList,
/// Positioned descendant stacking contexts, along with their `z-index` levels. /// Positioned descendant stacking contexts, along with their `z-index` levels.
/// ///
/// TODO(pcwalton): `z-index` should be the actual CSS property value in order to handle /// TODO(pcwalton): `z-index` should be the actual CSS property value in order to handle
/// `auto`, not just an integer. In this case we should store an actual stacking context, not /// `auto`, not just an integer. In this case we should store an actual stacking context, not
/// a flattened display list. /// a flattened display list.
positioned_descendants: SmallVec0<(int, DisplayList)>, pub positioned_descendants: SmallVec0<(int, DisplayList)>,
} }
impl StackingContext { impl StackingContext {
@ -143,7 +143,7 @@ pub enum BackgroundAndBorderLevel {
/// A list of rendering operations to be performed. /// A list of rendering operations to be performed.
pub struct DisplayList { pub struct DisplayList {
list: SmallVec0<DisplayItem>, pub list: SmallVec0<DisplayItem>,
} }
pub enum DisplayListIterator<'a> { pub enum DisplayListIterator<'a> {
@ -216,43 +216,43 @@ pub struct BaseDisplayItem {
/// The boundaries of the display item. /// The boundaries of the display item.
/// ///
/// TODO: Which coordinate system should this use? /// TODO: Which coordinate system should this use?
bounds: Rect<Au>, pub bounds: Rect<Au>,
/// The originating DOM node. /// The originating DOM node.
node: OpaqueNode, pub node: OpaqueNode,
} }
/// Renders a solid color. /// Renders a solid color.
pub struct SolidColorDisplayItem { pub struct SolidColorDisplayItem {
base: BaseDisplayItem, pub base: BaseDisplayItem,
color: Color, pub color: Color,
} }
/// Renders text. /// Renders text.
pub struct TextDisplayItem { pub struct TextDisplayItem {
/// Fields common to all display items. /// Fields common to all display items.
base: BaseDisplayItem, pub base: BaseDisplayItem,
/// The text run. /// The text run.
text_run: Arc<~TextRun>, pub text_run: Arc<~TextRun>,
/// The range of text within the text run. /// The range of text within the text run.
range: Range, pub range: Range,
/// The color of the text. /// The color of the text.
text_color: Color, pub text_color: Color,
/// A bitfield of flags for text display items. /// A bitfield of flags for text display items.
flags: TextDisplayItemFlags, pub flags: TextDisplayItemFlags,
/// The color of text-decorations /// The color of text-decorations
underline_color: Color, pub underline_color: Color,
overline_color: Color, pub overline_color: Color,
line_through_color: Color, pub line_through_color: Color,
} }
/// Flags for text display items. /// Flags for text display items.
pub struct TextDisplayItemFlags(u8); pub struct TextDisplayItemFlags(pub u8);
impl TextDisplayItemFlags { impl TextDisplayItemFlags {
pub fn new() -> TextDisplayItemFlags { pub fn new() -> TextDisplayItemFlags {
@ -269,44 +269,44 @@ bitfield!(TextDisplayItemFlags, override_line_through, set_override_line_through
/// Renders an image. /// Renders an image.
pub struct ImageDisplayItem { pub struct ImageDisplayItem {
base: BaseDisplayItem, pub base: BaseDisplayItem,
image: Arc<~Image>, pub image: Arc<~Image>,
/// The dimensions to which the image display item should be stretched. If this is smaller than /// The dimensions to which the image display item should be stretched. If this is smaller than
/// the bounds of this display item, then the image will be repeated in the appropriate /// the bounds of this display item, then the image will be repeated in the appropriate
/// direction to tile the entire bounds. /// direction to tile the entire bounds.
stretch_size: Size2D<Au>, pub stretch_size: Size2D<Au>,
} }
/// Renders a border. /// Renders a border.
pub struct BorderDisplayItem { pub struct BorderDisplayItem {
base: BaseDisplayItem, pub base: BaseDisplayItem,
/// The border widths /// The border widths
border: SideOffsets2D<Au>, pub border: SideOffsets2D<Au>,
/// The border colors. /// The border colors.
color: SideOffsets2D<Color>, pub color: SideOffsets2D<Color>,
/// The border styles. /// The border styles.
style: SideOffsets2D<border_style::T> pub style: SideOffsets2D<border_style::T>
} }
/// Renders a line segment. /// Renders a line segment.
pub struct LineDisplayItem { pub struct LineDisplayItem {
base: BaseDisplayItem, pub base: BaseDisplayItem,
/// The line segment color. /// The line segment color.
color: Color, pub color: Color,
/// The line segment style. /// The line segment style.
style: border_style::T pub style: border_style::T
} }
pub struct ClipDisplayItem { pub struct ClipDisplayItem {
base: BaseDisplayItem, pub base: BaseDisplayItem,
child_list: SmallVec0<DisplayItem>, pub child_list: SmallVec0<DisplayItem>,
need_clip: bool pub need_clip: bool
} }
pub enum DisplayItemIterator<'a> { pub enum DisplayItemIterator<'a> {
@ -348,7 +348,7 @@ impl DisplayItem {
debug!("Drawing text at {:?}.", text.base.bounds); debug!("Drawing text at {:?}.", text.base.bounds);
// FIXME(pcwalton): Allocating? Why? // FIXME(pcwalton): Allocating? Why?
let text_run = text.text_run.get(); let text_run = text.text_run.clone();
let font = render_context.font_ctx.get_font_by_descriptor(&text_run.font_descriptor).unwrap(); let font = render_context.font_ctx.get_font_by_descriptor(&text_run.font_descriptor).unwrap();
let font_metrics = { let font_metrics = {
@ -358,7 +358,7 @@ impl DisplayItem {
let baseline_origin = Point2D(origin.x, origin.y + font_metrics.ascent); let baseline_origin = Point2D(origin.x, origin.y + font_metrics.ascent);
{ {
font.borrow_mut().draw_text_into_context(render_context, font.borrow_mut().draw_text_into_context(render_context,
text.text_run.get(), &*text.text_run,
&text.range, &text.range,
baseline_origin, baseline_origin,
text.text_color); text.text_color);

View file

@ -77,16 +77,16 @@ pub trait FontTableMethods {
#[deriving(Clone)] #[deriving(Clone)]
pub struct FontMetrics { pub struct FontMetrics {
underline_size: Au, pub underline_size: Au,
underline_offset: Au, pub underline_offset: Au,
strikeout_size: Au, pub strikeout_size: Au,
strikeout_offset: Au, pub strikeout_offset: Au,
leading: Au, pub leading: Au,
x_height: Au, pub x_height: Au,
em_size: Au, pub em_size: Au,
ascent: Au, pub ascent: Au,
descent: Au, pub descent: Au,
max_advance: Au pub max_advance: Au
} }
// TODO(Issue #179): eventually this will be split into the specified // TODO(Issue #179): eventually this will be split into the specified
@ -97,10 +97,10 @@ pub struct FontMetrics {
// For now, the cases are differentiated with a typedef // For now, the cases are differentiated with a typedef
#[deriving(Clone, Eq)] #[deriving(Clone, Eq)]
pub struct FontStyle { pub struct FontStyle {
pt_size: f64, pub pt_size: f64,
weight: font_weight::T, pub weight: font_weight::T,
style: font_style::T, pub style: font_style::T,
families: ~[~str], pub families: ~[~str],
// TODO(Issue #198): font-stretch, text-decoration, font-variant, size-adjust // TODO(Issue #198): font-stretch, text-decoration, font-variant, size-adjust
} }
@ -115,8 +115,8 @@ pub type UsedFontStyle = FontStyle;
// and render tasks. // and render tasks.
#[deriving(Clone, Eq)] #[deriving(Clone, Eq)]
pub struct FontDescriptor { pub struct FontDescriptor {
style: UsedFontStyle, pub style: UsedFontStyle,
selector: FontSelector, pub selector: FontSelector,
} }
impl FontDescriptor { impl FontDescriptor {
@ -142,11 +142,11 @@ pub enum FontSelector {
// The ordering of font instances is mainly decided by the CSS // The ordering of font instances is mainly decided by the CSS
// 'font-family' property. The last font is a system fallback font. // 'font-family' property. The last font is a system fallback font.
pub struct FontGroup { pub struct FontGroup {
families: ~[~str], pub families: ~[~str],
// style of the first western font in group, which is // style of the first western font in group, which is
// used for purposes of calculating text run metrics. // used for purposes of calculating text run metrics.
style: UsedFontStyle, pub style: UsedFontStyle,
fonts: ~[Rc<RefCell<Font>>] pub fonts: ~[Rc<RefCell<Font>>]
} }
impl FontGroup { impl FontGroup {
@ -172,12 +172,12 @@ impl FontGroup {
pub struct RunMetrics { pub struct RunMetrics {
// may be negative due to negative width (i.e., kerning of '.' in 'P.T.') // may be negative due to negative width (i.e., kerning of '.' in 'P.T.')
advance_width: Au, pub advance_width: Au,
ascent: Au, // nonzero pub ascent: Au, // nonzero
descent: Au, // nonzero pub descent: Au, // nonzero
// this bounding box is relative to the left origin baseline. // this bounding box is relative to the left origin baseline.
// so, bounding_box.position.y = -ascent // so, bounding_box.position.y = -ascent
bounding_box: Rect<Au> pub bounding_box: Rect<Au>
} }
impl RunMetrics { impl RunMetrics {
@ -203,14 +203,14 @@ A font instance. Layout can use this to calculate glyph metrics
and the renderer can use it to render text. and the renderer can use it to render text.
*/ */
pub struct Font { pub struct Font {
priv handle: FontHandle, pub handle: FontHandle,
priv azure_font: Option<ScaledFont>, pub azure_font: Option<ScaledFont>,
priv shaper: Option<Shaper>, pub shaper: Option<Shaper>,
style: UsedFontStyle, pub style: UsedFontStyle,
metrics: FontMetrics, pub metrics: FontMetrics,
backend: BackendType, pub backend: BackendType,
shape_cache: HashCache<~str, Arc<GlyphStore>>, pub shape_cache: HashCache<~str, Arc<GlyphStore>>,
glyph_advance_cache: HashCache<u32, FractionalPixel>, pub glyph_advance_cache: HashCache<u32, FractionalPixel>,
} }
impl<'a> Font { impl<'a> Font {
@ -341,7 +341,7 @@ impl Font {
range: &Range, range: &Range,
baseline_origin: Point2D<Au>, baseline_origin: Point2D<Au>,
color: Color) { color: Color) {
use std::libc::types::common::c99::{uint16_t, uint32_t}; use libc::types::common::c99::{uint16_t, uint32_t};
use azure::{struct__AzDrawOptions, use azure::{struct__AzDrawOptions,
struct__AzGlyph, struct__AzGlyph,
struct__AzGlyphBuffer, struct__AzGlyphBuffer,

View file

@ -20,13 +20,13 @@ use std::cell::RefCell;
#[deriving(Clone)] #[deriving(Clone)]
pub struct FontContextInfo { pub struct FontContextInfo {
/// The painting backend we're using. /// The painting backend we're using.
backend: BackendType, pub backend: BackendType,
/// Whether we need a font list. /// Whether we need a font list.
needs_font_list: bool, pub needs_font_list: bool,
/// A channel up to the profiler. /// A channel up to the profiler.
profiler_chan: ProfilerChan, pub profiler_chan: ProfilerChan,
} }
pub trait FontContextHandleMethods { pub trait FontContextHandleMethods {
@ -34,13 +34,13 @@ pub trait FontContextHandleMethods {
} }
pub struct FontContext { pub struct FontContext {
instance_cache: LRUCache<FontDescriptor, Rc<RefCell<Font>>>, pub instance_cache: LRUCache<FontDescriptor, Rc<RefCell<Font>>>,
font_list: Option<FontList>, // only needed by layout pub font_list: Option<FontList>, // only needed by layout
group_cache: LRUCache<SpecifiedFontStyle, Rc<RefCell<FontGroup>>>, pub group_cache: LRUCache<SpecifiedFontStyle, Rc<RefCell<FontGroup>>>,
handle: FontContextHandle, pub handle: FontContextHandle,
backend: BackendType, pub backend: BackendType,
generic_fonts: HashMap<~str,~str>, pub generic_fonts: HashMap<~str,~str>,
profiler_chan: ProfilerChan, pub profiler_chan: ProfilerChan,
} }
impl FontContext { impl FontContext {

View file

@ -83,8 +83,8 @@ impl FontList {
// Holds a specific font family, and the various // Holds a specific font family, and the various
pub struct FontFamily { pub struct FontFamily {
family_name: ~str, pub family_name: ~str,
entries: ~[FontEntry], pub entries: ~[FontEntry],
} }
impl FontFamily { impl FontFamily {
@ -131,10 +131,10 @@ impl FontFamily {
/// In the common case, each FontFamily will have a singleton FontEntry, or it will have the /// In the common case, each FontFamily will have a singleton FontEntry, or it will have the
/// standard four faces: Normal, Bold, Italic, BoldItalic. /// standard four faces: Normal, Bold, Italic, BoldItalic.
pub struct FontEntry { pub struct FontEntry {
face_name: ~str, pub face_name: ~str,
priv weight: font_weight::T, weight: font_weight::T,
priv italic: bool, italic: bool,
handle: FontHandle, pub handle: FontHandle,
// TODO: array of OpenType features, etc. // TODO: array of OpenType features, etc.
} }

View file

@ -2,14 +2,14 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#[crate_id = "github.com/mozilla/servo#gfx:0.1"]; #![crate_id = "github.com/mozilla/servo#gfx:0.1"]
#[crate_type = "lib"]; #![crate_type = "lib"]
#[crate_type = "dylib"]; #![crate_type = "dylib"]
#[crate_type = "rlib"]; #![crate_type = "rlib"]
#[feature(globs, macro_rules, phase)]; #![feature(globs, macro_rules, phase)]
#[feature(phase)]; #![feature(phase)]
#[phase(syntax, link)] #[phase(syntax, link)]
extern crate log; extern crate log;
@ -17,6 +17,7 @@ extern crate azure;
extern crate collections; extern crate collections;
extern crate geom; extern crate geom;
extern crate layers; extern crate layers;
extern crate libc;
extern crate stb_image; extern crate stb_image;
extern crate png; extern crate png;
#[phase(syntax)] #[phase(syntax)]

View file

@ -54,9 +54,9 @@ enum FontSource {
pub struct FontHandle { pub struct FontHandle {
// The font binary. This must stay valid for the lifetime of the font, // The font binary. This must stay valid for the lifetime of the font,
// if the font is created using FT_Memory_Face. // if the font is created using FT_Memory_Face.
source: FontSource, pub source: FontSource,
face: FT_Face, pub face: FT_Face,
handle: FontContextHandle pub handle: FontContextHandle
} }
#[unsafe_destructor] #[unsafe_destructor]

View file

@ -15,12 +15,12 @@ use std::rc::Rc;
#[deriving(Clone)] #[deriving(Clone)]
pub struct FreeTypeLibraryHandle { pub struct FreeTypeLibraryHandle {
ctx: FT_Library, pub ctx: FT_Library,
} }
#[deriving(Clone)] #[deriving(Clone)]
pub struct FontContextHandle { pub struct FontContextHandle {
ctx: Rc<FreeTypeLibraryHandle>, pub ctx: Rc<FreeTypeLibraryHandle>,
} }
impl Drop for FreeTypeLibraryHandle { impl Drop for FreeTypeLibraryHandle {

View file

@ -26,13 +26,13 @@ use platform::font::FontHandle;
use platform::font_context::FontContextHandle; use platform::font_context::FontContextHandle;
use collections::HashMap; use collections::HashMap;
use std::libc; use libc;
use std::libc::{c_int, c_char}; use libc::{c_int, c_char};
use std::ptr; use std::ptr;
use std::str; use std::str;
pub struct FontListHandle { pub struct FontListHandle {
fctx: FontContextHandle, pub fctx: FontContextHandle,
} }
impl FontListHandle { impl FontListHandle {

View file

@ -54,9 +54,9 @@ pub enum FontSource {
pub struct FontHandle { pub struct FontHandle {
// The font binary. This must stay valid for the lifetime of the font, // The font binary. This must stay valid for the lifetime of the font,
// if the font is created using FT_Memory_Face. // if the font is created using FT_Memory_Face.
source: FontSource, pub source: FontSource,
face: FT_Face, pub face: FT_Face,
handle: FontContextHandle pub handle: FontContextHandle
} }
#[unsafe_destructor] #[unsafe_destructor]

View file

@ -15,12 +15,12 @@ use std::rc::Rc;
#[deriving(Clone)] #[deriving(Clone)]
pub struct FreeTypeLibraryHandle { pub struct FreeTypeLibraryHandle {
ctx: FT_Library, pub ctx: FT_Library,
} }
#[deriving(Clone)] #[deriving(Clone)]
pub struct FontContextHandle { pub struct FontContextHandle {
ctx: Rc<FreeTypeLibraryHandle>, pub ctx: Rc<FreeTypeLibraryHandle>,
} }
impl Drop for FreeTypeLibraryHandle { impl Drop for FreeTypeLibraryHandle {

View file

@ -28,13 +28,13 @@ use platform::font::FontHandle;
use platform::font_context::FontContextHandle; use platform::font_context::FontContextHandle;
use collections::HashMap; use collections::HashMap;
use std::libc; use libc;
use std::libc::{c_int, c_char}; use libc::{c_int, c_char};
use std::ptr; use std::ptr;
use std::str; use std::str;
pub struct FontListHandle { pub struct FontListHandle {
fctx: FontContextHandle, pub fctx: FontContextHandle,
} }
impl FontListHandle { impl FontListHandle {

View file

@ -52,8 +52,8 @@ impl FontTableMethods for FontTable {
} }
pub struct FontHandle { pub struct FontHandle {
priv cgfont: Option<CGFont>, cgfont: Option<CGFont>,
ctfont: CTFont, pub ctfont: CTFont,
} }
impl FontHandle { impl FontHandle {

View file

@ -13,22 +13,22 @@ use geom::point::Point2D;
use geom::rect::Rect; use geom::rect::Rect;
use geom::size::Size2D; use geom::size::Size2D;
use geom::side_offsets::SideOffsets2D; use geom::side_offsets::SideOffsets2D;
use servo_net::image::base::Image; use libc::types::common::c99::uint16_t;
use libc::size_t;
use png::{RGBA8, K8, KA8}; use png::{RGBA8, K8, KA8};
use servo_net::image::base::Image;
use servo_util::geometry::Au; use servo_util::geometry::Au;
use servo_util::opts::Opts; use servo_util::opts::Opts;
use std::libc::types::common::c99::uint16_t;
use std::libc::size_t;
use sync::Arc; use sync::Arc;
pub struct RenderContext<'a> { pub struct RenderContext<'a> {
draw_target: &'a DrawTarget, pub draw_target: &'a DrawTarget,
font_ctx: &'a mut ~FontContext, pub font_ctx: &'a mut ~FontContext,
opts: &'a Opts, pub opts: &'a Opts,
/// The rectangle that this context encompasses in page coordinates. /// The rectangle that this context encompasses in page coordinates.
page_rect: Rect<f32>, pub page_rect: Rect<f32>,
/// The rectangle that this context encompasses in screen coordinates (pixels). /// The rectangle that this context encompasses in screen coordinates (pixels).
screen_rect: Rect<uint>, pub screen_rect: Rect<uint>,
} }
enum Direction { enum Direction {
@ -94,7 +94,6 @@ impl<'a> RenderContext<'a> {
} }
pub fn draw_image(&self, bounds: Rect<Au>, image: Arc<~Image>) { pub fn draw_image(&self, bounds: Rect<Au>, image: Arc<~Image>) {
let image = image.get();
let size = Size2D(image.width as i32, image.height as i32); let size = Size2D(image.width as i32, image.height as i32);
let pixel_width = match image.color_type { let pixel_width = match image.color_type {
RGBA8 => 4, RGBA8 => 4,

View file

@ -36,15 +36,15 @@ use sync::Arc;
/// Information about a layer that layout sends to the painting task. /// Information about a layer that layout sends to the painting task.
pub struct RenderLayer { pub struct RenderLayer {
/// A per-pipeline ID describing this layer that should be stable across reflows. /// A per-pipeline ID describing this layer that should be stable across reflows.
id: LayerId, pub id: LayerId,
/// The display list describing the contents of this layer. /// The display list describing the contents of this layer.
display_list: Arc<DisplayList>, pub display_list: Arc<DisplayList>,
/// The position of the layer in pixels. /// The position of the layer in pixels.
position: Rect<uint>, pub position: Rect<uint>,
/// The color of the background in this layer. Used for unrendered content. /// The color of the background in this layer. Used for unrendered content.
background_color: Color, pub background_color: Color,
/// The scrolling policy of this layer. /// The scrolling policy of this layer.
scroll_policy: ScrollPolicy, pub scroll_policy: ScrollPolicy,
} }
pub enum Msg { pub enum Msg {
@ -75,7 +75,7 @@ pub fn BufferRequest(screen_rect: Rect<uint>, page_rect: Rect<f32>) -> BufferReq
// FIXME(#2005, pcwalton): This should be a newtype struct. // FIXME(#2005, pcwalton): This should be a newtype struct.
pub struct RenderChan { pub struct RenderChan {
chan: Sender<Msg>, pub chan: Sender<Msg>,
} }
impl Clone for RenderChan { impl Clone for RenderChan {
@ -138,7 +138,7 @@ pub struct RenderTask<C> {
epoch: Epoch, epoch: Epoch,
/// A data structure to store unused LayerBuffers /// A data structure to store unused LayerBuffers
priv buffer_map: BufferMap<~LayerBuffer>, buffer_map: BufferMap<~LayerBuffer>,
} }
// If we implement this as a function, we get borrowck errors from borrowing // If we implement this as a function, we get borrowck errors from borrowing
@ -352,7 +352,7 @@ impl<C: RenderListener + Send> RenderTask<C> {
// Draw the display list. // Draw the display list.
profile(time::RenderingDrawingCategory, self.profiler_chan.clone(), || { profile(time::RenderingDrawingCategory, self.profiler_chan.clone(), || {
render_layer.display_list.get().draw_into_context(&mut ctx); render_layer.display_list.draw_into_context(&mut ctx);
ctx.draw_target.flush(); ctx.draw_target.flush();
}); });
} }

View file

@ -500,9 +500,9 @@ impl<'a> GlyphInfo<'a> {
pub struct GlyphStore { pub struct GlyphStore {
// TODO(pcwalton): Allocation of this buffer is expensive. Consider a small-vector // TODO(pcwalton): Allocation of this buffer is expensive. Consider a small-vector
// optimization. // optimization.
priv entry_buffer: ~[GlyphEntry], entry_buffer: ~[GlyphEntry],
priv detail_store: DetailedGlyphStore, detail_store: DetailedGlyphStore,
is_whitespace: bool, is_whitespace: bool,
} }
@ -673,10 +673,10 @@ impl<'a> GlyphStore {
} }
pub struct GlyphIterator<'a> { pub struct GlyphIterator<'a> {
priv store: &'a GlyphStore, store: &'a GlyphStore,
priv char_index: uint, char_index: uint,
priv char_range: iter::Range<uint>, char_range: iter::Range<uint>,
priv glyph_range: Option<iter::Range<uint>>, glyph_range: Option<iter::Range<uint>>,
} }
impl<'a> GlyphIterator<'a> { impl<'a> GlyphIterator<'a> {

View file

@ -35,12 +35,12 @@ use harfbuzz::{hb_glyph_info_t};
use harfbuzz::{hb_glyph_position_t}; use harfbuzz::{hb_glyph_position_t};
use harfbuzz::{hb_position_t, hb_tag_t}; use harfbuzz::{hb_position_t, hb_tag_t};
use harfbuzz::{hb_shape, hb_buffer_get_glyph_infos}; use harfbuzz::{hb_shape, hb_buffer_get_glyph_infos};
use libc::{c_uint, c_int, c_void, c_char};
use servo_util::geometry::Au; use servo_util::geometry::Au;
use servo_util::range::Range; use servo_util::range::Range;
use std::cast::transmute; use std::cast::transmute;
use std::char; use std::char;
use std::cmp; use std::cmp;
use std::libc::{c_uint, c_int, c_void, c_char};
use std::ptr::null; use std::ptr::null;
use std::slice; use std::slice;
@ -133,9 +133,9 @@ impl ShapedGlyphData {
} }
pub struct Shaper { pub struct Shaper {
priv hb_face: *hb_face_t, hb_face: *hb_face_t,
priv hb_font: *hb_font_t, hb_font: *hb_font_t,
priv hb_funcs: *hb_font_funcs_t, hb_funcs: *hb_font_funcs_t,
} }
#[unsafe_destructor] #[unsafe_destructor]

View file

@ -13,18 +13,18 @@ use text::glyph::GlyphStore;
/// A text run. /// A text run.
#[deriving(Clone)] #[deriving(Clone)]
pub struct TextRun { pub struct TextRun {
text: Arc<~str>, pub text: Arc<~str>,
font_descriptor: FontDescriptor, pub font_descriptor: FontDescriptor,
font_metrics: FontMetrics, pub font_metrics: FontMetrics,
font_style: FontStyle, pub font_style: FontStyle,
decoration: text_decoration::T, pub decoration: text_decoration::T,
glyphs: Arc<~[Arc<GlyphStore>]>, pub glyphs: Arc<~[Arc<GlyphStore>]>,
} }
pub struct SliceIterator<'a> { pub struct SliceIterator<'a> {
priv glyph_iter: Items<'a, Arc<GlyphStore>>, glyph_iter: Items<'a, Arc<GlyphStore>>,
priv range: Range, range: Range,
priv offset: uint, offset: uint,
} }
impl<'a> Iterator<(&'a GlyphStore, uint, Range)> for SliceIterator<'a> { impl<'a> Iterator<(&'a GlyphStore, uint, Range)> for SliceIterator<'a> {
@ -36,7 +36,7 @@ impl<'a> Iterator<(&'a GlyphStore, uint, Range)> for SliceIterator<'a> {
if slice_glyphs.is_none() { if slice_glyphs.is_none() {
return None; return None;
} }
let slice_glyphs = slice_glyphs.unwrap().get(); let slice_glyphs = slice_glyphs.unwrap();
let slice_range = Range::new(self.offset, slice_glyphs.char_len()); let slice_range = Range::new(self.offset, slice_glyphs.char_len());
let mut char_range = self.range.intersect(&slice_range); let mut char_range = self.range.intersect(&slice_range);
@ -45,16 +45,16 @@ impl<'a> Iterator<(&'a GlyphStore, uint, Range)> for SliceIterator<'a> {
let old_offset = self.offset; let old_offset = self.offset;
self.offset += slice_glyphs.char_len(); self.offset += slice_glyphs.char_len();
if !char_range.is_empty() { if !char_range.is_empty() {
return Some((slice_glyphs, old_offset, char_range)) return Some((&**slice_glyphs, old_offset, char_range))
} }
} }
} }
} }
pub struct LineIterator<'a> { pub struct LineIterator<'a> {
priv range: Range, range: Range,
priv clump: Option<Range>, clump: Option<Range>,
priv slices: SliceIterator<'a>, slices: SliceIterator<'a>,
} }
impl<'a> Iterator<Range> for LineIterator<'a> { impl<'a> Iterator<Range> for LineIterator<'a> {
@ -169,13 +169,13 @@ impl<'a> TextRun {
} }
pub fn char_len(&self) -> uint { pub fn char_len(&self) -> uint {
self.glyphs.get().iter().fold(0u, |len, slice_glyphs| { self.glyphs.iter().fold(0u, |len, slice_glyphs| {
len + slice_glyphs.get().char_len() len + slice_glyphs.char_len()
}) })
} }
pub fn glyphs(&'a self) -> &'a ~[Arc<GlyphStore>] { pub fn glyphs(&'a self) -> &'a ~[Arc<GlyphStore>] {
self.glyphs.get() &*self.glyphs
} }
pub fn range_is_trimmable_whitespace(&self, range: &Range) -> bool { pub fn range_is_trimmable_whitespace(&self, range: &Range) -> bool {
@ -217,7 +217,7 @@ impl<'a> TextRun {
pub fn iter_slices_for_range(&'a self, range: &Range) -> SliceIterator<'a> { pub fn iter_slices_for_range(&'a self, range: &Range) -> SliceIterator<'a> {
SliceIterator { SliceIterator {
glyph_iter: self.glyphs.get().iter(), glyph_iter: self.glyphs.iter(),
range: *range, range: *range,
offset: 0, offset: 0,
} }

View file

@ -2,10 +2,12 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#[crate_id = "github.com/mozilla/servo#macros:0.1"]; #![crate_id = "github.com/mozilla/servo#macros:0.1"]
#[crate_type = "lib"]; #![crate_type = "lib"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#[feature(macro_rules)]; #![feature(macro_rules)]
#[macro_export] #[macro_export]
macro_rules! bitfield( macro_rules! bitfield(

View file

@ -43,72 +43,72 @@ use time::precise_time_s;
pub struct IOCompositor { pub struct IOCompositor {
/// The application window. /// The application window.
window: Rc<Window>, pub window: Rc<Window>,
/// The port on which we receive messages. /// The port on which we receive messages.
port: Receiver<Msg>, pub port: Receiver<Msg>,
/// The render context. /// The render context.
context: RenderContext, pub context: RenderContext,
/// The root ContainerLayer. /// The root ContainerLayer.
root_layer: Rc<ContainerLayer>, pub root_layer: Rc<ContainerLayer>,
/// The root pipeline. /// The root pipeline.
root_pipeline: Option<CompositionPipeline>, pub root_pipeline: Option<CompositionPipeline>,
/// The canvas to paint a page. /// The canvas to paint a page.
scene: Scene, pub scene: Scene,
/// The application window size. /// The application window size.
window_size: Size2D<uint>, pub window_size: Size2D<uint>,
/// The platform-specific graphics context. /// The platform-specific graphics context.
graphics_context: NativeCompositingGraphicsContext, pub graphics_context: NativeCompositingGraphicsContext,
/// Tracks whether the renderer has finished its first rendering /// Tracks whether the renderer has finished its first rendering
composite_ready: bool, pub composite_ready: bool,
/// Tracks whether we are in the process of shutting down. /// Tracks whether we are in the process of shutting down.
shutting_down: bool, pub shutting_down: bool,
/// Tracks whether we should close compositor. /// Tracks whether we should close compositor.
done: bool, pub done: bool,
/// Tracks whether we need to re-composite a page. /// Tracks whether we need to re-composite a page.
recomposite: bool, pub recomposite: bool,
/// Keeps track of the current zoom factor. /// Keeps track of the current zoom factor.
world_zoom: f32, pub world_zoom: f32,
/// Tracks whether the zoom action has happend recently. /// Tracks whether the zoom action has happend recently.
zoom_action: bool, pub zoom_action: bool,
/// The time of the last zoom action has started. /// The time of the last zoom action has started.
zoom_time: f64, pub zoom_time: f64,
/// Current display/reflow status of the page /// Current display/reflow status of the page
ready_state: ReadyState, pub ready_state: ReadyState,
/// Whether the page being rendered has loaded completely. /// Whether the page being rendered has loaded completely.
/// Differs from ReadyState because we can finish loading (ready) /// Differs from ReadyState because we can finish loading (ready)
/// many times for a single page. /// many times for a single page.
load_complete: bool, pub load_complete: bool,
/// The command line option flags. /// The command line option flags.
opts: Opts, pub opts: Opts,
/// The root CompositorLayer /// The root CompositorLayer
compositor_layer: Option<CompositorLayer>, pub compositor_layer: Option<CompositorLayer>,
/// The channel on which messages can be sent to the constellation. /// The channel on which messages can be sent to the constellation.
constellation_chan: ConstellationChan, pub constellation_chan: ConstellationChan,
/// The channel on which messages can be sent to the profiler. /// The channel on which messages can be sent to the profiler.
profiler_chan: ProfilerChan, pub profiler_chan: ProfilerChan,
/// Pending scroll to fragment event, if any /// Pending scroll to fragment event, if any
fragment_point: Option<Point2D<f32>> pub fragment_point: Option<Point2D<f32>>
} }
impl IOCompositor { impl IOCompositor {
@ -376,7 +376,7 @@ impl IOCompositor {
self.opts.tile_size, self.opts.tile_size,
self.opts.cpu_painting); self.opts.cpu_painting);
match self.root_layer.first_child.get() { match *self.root_layer.first_child.borrow() {
None => {} None => {}
Some(ref old_layer) => { Some(ref old_layer) => {
ContainerLayer::remove_child(self.root_layer.clone(), old_layer.clone()) ContainerLayer::remove_child(self.root_layer.clone(), old_layer.clone())

View file

@ -44,64 +44,64 @@ static MAX_TILE_MEMORY_PER_LAYER: uint = 10000000;
/// ultimately removed, except as a set of helper methods on `rust-layers` layers. /// ultimately removed, except as a set of helper methods on `rust-layers` layers.
pub struct CompositorLayer { pub struct CompositorLayer {
/// This layer's pipeline. BufferRequests and mouse events will be sent through this. /// This layer's pipeline. BufferRequests and mouse events will be sent through this.
pipeline: CompositionPipeline, pub pipeline: CompositionPipeline,
/// The ID of this layer within the pipeline. /// The ID of this layer within the pipeline.
id: LayerId, pub id: LayerId,
/// The bounds of this layer in terms of its parent (a.k.a. the scissor box). /// The bounds of this layer in terms of its parent (a.k.a. the scissor box).
bounds: Rect<f32>, pub bounds: Rect<f32>,
/// The size of the underlying page in page coordinates. This is an option /// The size of the underlying page in page coordinates. This is an option
/// because we may not know the size of the page until layout is finished completely. /// because we may not know the size of the page until layout is finished completely.
/// if we have no size yet, the layer is hidden until a size message is recieved. /// if we have no size yet, the layer is hidden until a size message is recieved.
page_size: Option<Size2D<f32>>, pub page_size: Option<Size2D<f32>>,
/// The offset of the page due to scrolling. (0,0) is when the window sees the /// The offset of the page due to scrolling. (0,0) is when the window sees the
/// top left corner of the page. /// top left corner of the page.
scroll_offset: Point2D<f32>, pub scroll_offset: Point2D<f32>,
/// This layer's children. These could be iframes or any element which /// This layer's children. These could be iframes or any element which
/// differs in scroll behavior from its parent. Each is associated with a /// differs in scroll behavior from its parent. Each is associated with a
/// ContainerLayer which determines its position relative to its parent and /// ContainerLayer which determines its position relative to its parent and
/// clipping rect. Children are stored in the order in which they are drawn. /// clipping rect. Children are stored in the order in which they are drawn.
children: ~[CompositorLayerChild], pub children: ~[CompositorLayerChild],
/// This layer's quadtree. This is where all buffers are stored for this layer. /// This layer's quadtree. This is where all buffers are stored for this layer.
quadtree: MaybeQuadtree, pub quadtree: MaybeQuadtree,
/// The root layer of this CompositorLayer's layer tree. Buffers are collected /// The root layer of this CompositorLayer's layer tree. Buffers are collected
/// from the quadtree and inserted here when the layer is painted to the screen. /// from the quadtree and inserted here when the layer is painted to the screen.
root_layer: Rc<ContainerLayer>, pub root_layer: Rc<ContainerLayer>,
/// When set to true, this layer is ignored by its parents. This is useful for /// When set to true, this layer is ignored by its parents. This is useful for
/// soft deletion or when waiting on a page size. /// soft deletion or when waiting on a page size.
hidden: bool, pub hidden: bool,
/// A monotonically increasing counter that keeps track of the current epoch. /// A monotonically increasing counter that keeps track of the current epoch.
/// add_buffer() calls that don't match the current epoch will be ignored. /// add_buffer() calls that don't match the current epoch will be ignored.
epoch: Epoch, pub epoch: Epoch,
/// The behavior of this layer when a scroll message is received. /// The behavior of this layer when a scroll message is received.
wants_scroll_events: WantsScrollEventsFlag, pub wants_scroll_events: WantsScrollEventsFlag,
/// Whether an ancestor layer that receives scroll events moves this layer. /// Whether an ancestor layer that receives scroll events moves this layer.
scroll_policy: ScrollPolicy, pub scroll_policy: ScrollPolicy,
/// True if CPU rendering is enabled, false if we're using GPU rendering. /// True if CPU rendering is enabled, false if we're using GPU rendering.
cpu_painting: bool, pub cpu_painting: bool,
/// The color to use for the unrendered-content void /// The color to use for the unrendered-content void
unrendered_color: Color, pub unrendered_color: Color,
} }
/// Helper struct for keeping CompositorLayer children organized. /// Helper struct for keeping CompositorLayer children organized.
pub struct CompositorLayerChild { pub struct CompositorLayerChild {
/// The child itself. /// The child itself.
child: ~CompositorLayer, pub child: ~CompositorLayer,
/// A ContainerLayer managed by the parent node. This deals with clipping and /// A ContainerLayer managed by the parent node. This deals with clipping and
/// positioning, and is added above the child's layer tree. /// positioning, and is added above the child's layer tree.
container: Rc<ContainerLayer>, pub container: Rc<ContainerLayer>,
} }
/// Helper enum for storing quadtrees. Either contains a quadtree, or contains /// Helper enum for storing quadtrees. Either contains a quadtree, or contains
@ -128,7 +128,7 @@ pub enum WantsScrollEventsFlag {
fn create_container_layer_from_rect(rect: Rect<f32>) -> Rc<ContainerLayer> { fn create_container_layer_from_rect(rect: Rect<f32>) -> Rc<ContainerLayer> {
let container = Rc::new(ContainerLayer()); let container = Rc::new(ContainerLayer());
container.scissor.set(Some(rect)); *container.scissor.borrow_mut() = Some(rect);
container.common.borrow_mut().transform = container.common.borrow_mut().transform =
identity().translate(rect.origin.x, rect.origin.y, 0f32); identity().translate(rect.origin.x, rect.origin.y, 0f32);
container container
@ -303,7 +303,7 @@ impl CompositorLayer {
// Allow children to scroll. // Allow children to scroll.
let cursor = cursor - self.scroll_offset; let cursor = cursor - self.scroll_offset;
for child in self.children.mut_iter() { for child in self.children.mut_iter() {
match child.container.scissor.get() { match *child.container.scissor.borrow() {
None => { None => {
error!("CompositorLayer: unable to perform cursor hit test for layer"); error!("CompositorLayer: unable to perform cursor hit test for layer");
} }
@ -343,7 +343,7 @@ impl CompositorLayer {
#[allow(dead_code)] #[allow(dead_code)]
fn dump_layer_tree(&self, layer: Rc<ContainerLayer>, indent: ~str) { fn dump_layer_tree(&self, layer: Rc<ContainerLayer>, indent: ~str) {
println!("{}scissor {:?}", indent, layer.scissor.get()); println!("{}scissor {:?}", indent, layer.scissor.borrow());
for kid in layer.children() { for kid in layer.children() {
match kid { match kid {
ContainerLayerKind(ref container_layer) => { ContainerLayerKind(ref container_layer) => {
@ -385,7 +385,7 @@ impl CompositorLayer {
pub fn send_mouse_event(&self, event: MouseWindowEvent, cursor: Point2D<f32>) { pub fn send_mouse_event(&self, event: MouseWindowEvent, cursor: Point2D<f32>) {
let cursor = cursor - self.scroll_offset; let cursor = cursor - self.scroll_offset;
for child in self.children.iter().filter(|&x| !x.child.hidden) { for child in self.children.iter().filter(|&x| !x.child.hidden) {
match child.container.scissor.get() { match *child.container.scissor.borrow() {
None => { None => {
error!("CompositorLayer: unable to perform cursor hit test for layer"); error!("CompositorLayer: unable to perform cursor hit test for layer");
} }
@ -450,7 +450,7 @@ impl CompositorLayer {
} }
let transform = |x: &mut CompositorLayerChild| -> bool { let transform = |x: &mut CompositorLayerChild| -> bool {
match x.container.scissor.get() { match *x.container.scissor.borrow() {
Some(scissor) => { Some(scissor) => {
let mut new_rect = window_rect; let mut new_rect = window_rect;
new_rect.origin.x = new_rect.origin.x - x.child.scroll_offset.x; new_rect.origin.x = new_rect.origin.x - x.child.scroll_offset.x;
@ -497,8 +497,8 @@ impl CompositorLayer {
let child_node = &mut self.children[i]; let child_node = &mut self.children[i];
child_node.container.common.borrow_mut().set_transform( child_node.container.common.borrow_mut().set_transform(
identity().translate(new_rect.origin.x, new_rect.origin.y, 0.0)); identity().translate(new_rect.origin.x, new_rect.origin.y, 0.0));
let old_rect = child_node.container.scissor.get().clone(); let old_rect = child_node.container.scissor.borrow().clone();
child_node.container.scissor.set(Some(new_rect)); *child_node.container.scissor.borrow_mut() = Some(new_rect);
match self.quadtree { match self.quadtree {
NoTree(..) => {} // Nothing to do NoTree(..) => {} // Nothing to do
Tree(ref mut quadtree) => { Tree(ref mut quadtree) => {
@ -665,7 +665,7 @@ impl CompositorLayer {
max_mem)) max_mem))
} }
} }
match child_node.container.scissor.get() { match *child_node.container.scissor.borrow() {
Some(scissor) => { Some(scissor) => {
// Call scroll for bounds checking if the page shrunk. Use (-1, -1) as the // Call scroll for bounds checking if the page shrunk. Use (-1, -1) as the
// cursor position to make sure the scroll isn't propagated downwards. // cursor position to make sure the scroll isn't propagated downwards.
@ -698,7 +698,7 @@ impl CompositorLayer {
// are not rebuilt directly from this method. // are not rebuilt directly from this method.
pub fn build_layer_tree(&mut self, graphics_context: &NativeCompositingGraphicsContext) { pub fn build_layer_tree(&mut self, graphics_context: &NativeCompositingGraphicsContext) {
// Iterate over the children of the container layer. // Iterate over the children of the container layer.
let mut current_layer_child = self.root_layer.first_child.get().clone(); let mut current_layer_child = self.root_layer.first_child.borrow().clone();
// Delete old layer. // Delete old layer.
while current_layer_child.is_some() { while current_layer_child.is_some() {
@ -869,7 +869,7 @@ impl CompositorLayer {
match self.quadtree { match self.quadtree {
NoTree(..) => {} // Nothing to do NoTree(..) => {} // Nothing to do
Tree(ref mut quadtree) => { Tree(ref mut quadtree) => {
match child.get_ref().container.scissor.get() { match *child.get_ref().container.scissor.borrow() {
Some(rect) => { Some(rect) => {
quadtree.set_status_page(rect, Normal, false); // Unhide this rect quadtree.set_status_page(rect, Normal, false); // Unhide this rect
} }
@ -899,7 +899,7 @@ impl CompositorLayer {
Tree(ref mut quadtree) => quadtree, Tree(ref mut quadtree) => quadtree,
}; };
for child in self.children.iter().filter(|x| !x.child.hidden) { for child in self.children.iter().filter(|x| !x.child.hidden) {
match child.container.scissor.get() { match *child.container.scissor.borrow() {
None => {} // Nothing to do None => {} // Nothing to do
Some(rect) => { Some(rect) => {
quadtree.set_status_page(rect, Hidden, false); quadtree.set_status_page(rect, Hidden, false);

View file

@ -35,7 +35,7 @@ mod headless;
#[deriving(Clone)] #[deriving(Clone)]
pub struct CompositorChan { pub struct CompositorChan {
/// A channel on which messages can be sent to the compositor. /// A channel on which messages can be sent to the compositor.
chan: Sender<Msg>, pub chan: Sender<Msg>,
} }
/// Implementation of the abstract `ScriptListener` interface. /// Implementation of the abstract `ScriptListener` interface.
@ -197,7 +197,7 @@ pub enum CompositorMode {
} }
pub struct CompositorTask { pub struct CompositorTask {
mode: CompositorMode, pub mode: CompositorMode,
} }
impl CompositorTask { impl CompositorTask {

View file

@ -16,7 +16,7 @@ use servo_util::time;
/// It's intended for headless testing. /// It's intended for headless testing.
pub struct NullCompositor { pub struct NullCompositor {
/// The port on which we receive messages. /// The port on which we receive messages.
port: Receiver<Msg>, pub port: Receiver<Msg>,
} }
impl NullCompositor { impl NullCompositor {

View file

@ -23,33 +23,33 @@ use layers::platform::surface::NativePaintingGraphicsContext;
/// at this level are in pixel coordinates. /// at this level are in pixel coordinates.
pub struct Quadtree<T> { pub struct Quadtree<T> {
// The root node of the quadtree // The root node of the quadtree
root: ~QuadtreeNode<T>, pub root: ~QuadtreeNode<T>,
// The size of the layer in pixels. Tiles will be clipped to this size. // The size of the layer in pixels. Tiles will be clipped to this size.
// Note that the underlying quadtree has a potentailly larger size, since it is rounded // Note that the underlying quadtree has a potentailly larger size, since it is rounded
// to the next highest power of two. // to the next highest power of two.
clip_size: Size2D<uint>, pub clip_size: Size2D<uint>,
// The maximum size of the tiles requested in pixels. Tiles requested will be // The maximum size of the tiles requested in pixels. Tiles requested will be
// of a size anywhere between half this value and this value. // of a size anywhere between half this value and this value.
max_tile_size: uint, pub max_tile_size: uint,
// The maximum allowed total memory of tiles in the tree. If this limit is reached, tiles // The maximum allowed total memory of tiles in the tree. If this limit is reached, tiles
// will be removed from the tree. Set this to None to prevent this behavior. // will be removed from the tree. Set this to None to prevent this behavior.
max_mem: Option<uint>, pub max_mem: Option<uint>,
} }
/// A node in the tree. All method calls at this level are in page coordinates. /// A node in the tree. All method calls at this level are in page coordinates.
struct QuadtreeNode<T> { struct QuadtreeNode<T> {
/// The tile belonging to this node. Note that parent nodes can have tiles. /// The tile belonging to this node. Note that parent nodes can have tiles.
tile: Option<T>, pub tile: Option<T>,
/// The position of the node in page coordinates. /// The position of the node in page coordinates.
origin: Point2D<f32>, pub origin: Point2D<f32>,
/// The width and height of the node in page coordinates. /// The width and height of the node in page coordinates.
size: f32, pub size: f32,
/// The node's children. /// The node's children.
quadrants: [Option<~QuadtreeNode<T>>, ..4], pub quadrants: [Option<~QuadtreeNode<T>>, ..4],
/// Combined size of self.tile and tiles of all descendants /// Combined size of self.tile and tiles of all descendants
tile_mem: uint, pub tile_mem: uint,
/// The current status of this node. See below for details. /// The current status of this node. See below for details.
status: NodeStatus, pub status: NodeStatus,
} }
/// The status of a QuadtreeNode. This determines the behavior of the node /// The status of a QuadtreeNode. This determines the behavior of the node
@ -201,12 +201,12 @@ impl<T: Tile> Quadtree<T> {
tile_mem: self.root.tile_mem, tile_mem: self.root.tile_mem,
status: Normal, status: Normal,
}; };
self.root.quadrants[TL as int] = Some(replace(&mut self.root, new_root)); self.root.quadrants[TL as uint] = Some(replace(&mut self.root, new_root));
} }
} else if difference < 0 { // halving } else if difference < 0 { // halving
let difference = difference.abs() as uint; let difference = difference.abs() as uint;
for _ in range(0, difference) { for _ in range(0, difference) {
let remove = replace(&mut self.root.quadrants[TL as int], None); let remove = replace(&mut self.root.quadrants[TL as uint], None);
match remove { match remove {
Some(child) => self.root = child, Some(child) => self.root = child,
None => { None => {
@ -318,7 +318,7 @@ impl<T: Tile> QuadtreeNode<T> {
(self.tile_mem as int - old_size as int, unused_tiles) (self.tile_mem as int - old_size as int, unused_tiles)
} else { // Send tile to children } else { // Send tile to children
let quad = self.get_quadrant(x, y); let quad = self.get_quadrant(x, y);
match self.quadrants[quad as int] { match self.quadrants[quad as uint] {
Some(ref mut child) => { Some(ref mut child) => {
let (delta, unused) = child.add_tile(x, y, tile, tile_size); let (delta, unused) = child.add_tile(x, y, tile, tile_size);
self.tile_mem = (self.tile_mem as int + delta) as uint; self.tile_mem = (self.tile_mem as int + delta) as uint;
@ -337,7 +337,7 @@ impl<T: Tile> QuadtreeNode<T> {
let mut c = ~QuadtreeNode::new_child(new_x, new_y, new_size); let mut c = ~QuadtreeNode::new_child(new_x, new_y, new_size);
let (delta, unused) = c.add_tile(x, y, tile, tile_size); let (delta, unused) = c.add_tile(x, y, tile, tile_size);
self.tile_mem = (self.tile_mem as int + delta) as uint; self.tile_mem = (self.tile_mem as int + delta) as uint;
self.quadrants[quad as int] = Some(c); self.quadrants[quad as uint] = Some(c);
(delta, unused) (delta, unused)
} }
} }
@ -365,7 +365,7 @@ impl<T: Tile> QuadtreeNode<T> {
} }
let quad = self.get_quadrant(x,y); let quad = self.get_quadrant(x,y);
match self.quadrants[quad as int] { match self.quadrants[quad as uint] {
None => { None => {
let new_size = self.size / 2.0; let new_size = self.size / 2.0;
let new_x = match quad { let new_x = match quad {
@ -378,7 +378,7 @@ impl<T: Tile> QuadtreeNode<T> {
}; };
let mut c = ~QuadtreeNode::new_child(new_x, new_y, new_size); let mut c = ~QuadtreeNode::new_child(new_x, new_y, new_size);
let result = c.get_tile_rect(x, y, clip_x, clip_y, scale, tile_size); let result = c.get_tile_rect(x, y, clip_x, clip_y, scale, tile_size);
self.quadrants[quad as int] = Some(c); self.quadrants[quad as uint] = Some(c);
result result
} }
Some(ref mut child) => child.get_tile_rect(x, y, clip_x, clip_y, scale, tile_size), Some(ref mut child) => child.get_tile_rect(x, y, clip_x, clip_y, scale, tile_size),
@ -419,7 +419,7 @@ impl<T: Tile> QuadtreeNode<T> {
let mut ret = (None, false, 0); let mut ret = (None, false, 0);
for quad in queue.iter() { for quad in queue.iter() {
match self.quadrants[*quad as int] { match self.quadrants[*quad as uint] {
Some(ref mut child) => { Some(ref mut child) => {
let (tile, flag, delta) = child.remove_tile(x, y); let (tile, flag, delta) = child.remove_tile(x, y);
match tile { match tile {
@ -443,7 +443,7 @@ impl<T: Tile> QuadtreeNode<T> {
match del_quad { match del_quad {
Some(quad) => { Some(quad) => {
self.quadrants[quad as int] = None; self.quadrants[quad as uint] = None;
let (tile, _, delta) = ret; let (tile, _, delta) = ret;
match (&self.tile, &self.quadrants) { match (&self.tile, &self.quadrants) {
(&None, &[None, None, None, None]) => (tile, true, delta), (&None, &[None, None, None, None]) => (tile, true, delta),
@ -575,7 +575,7 @@ impl<T: Tile> QuadtreeNode<T> {
let override = override || self.status == Invalid; let override = override || self.status == Invalid;
self.status = Normal; self.status = Normal;
let (c_request, c_unused, c_delta) = match self.quadrants[*quad as int] { let (c_request, c_unused, c_delta) = match self.quadrants[*quad as uint] {
Some(ref mut child) => child.get_tile_rects(new_window, clip, scale, tile_size, override), Some(ref mut child) => child.get_tile_rects(new_window, clip, scale, tile_size, override),
None => { None => {
// Create new child // Create new child
@ -590,7 +590,7 @@ impl<T: Tile> QuadtreeNode<T> {
}; };
let mut child = ~QuadtreeNode::new_child(new_x, new_y, new_size); let mut child = ~QuadtreeNode::new_child(new_x, new_y, new_size);
let ret = child.get_tile_rects(new_window, clip, scale, tile_size, override); let ret = child.get_tile_rects(new_window, clip, scale, tile_size, override);
self.quadrants[*quad as int] = Some(child); self.quadrants[*quad as uint] = Some(child);
ret ret
} }
}; };

View file

@ -8,6 +8,7 @@ use collections::hashmap::{HashMap, HashSet};
use geom::rect::Rect; use geom::rect::Rect;
use geom::size::Size2D; use geom::size::Size2D;
use gfx::render_task; use gfx::render_task;
use libc;
use pipeline::{Pipeline, CompositionPipeline}; use pipeline::{Pipeline, CompositionPipeline};
use script::script_task::{ResizeMsg, ResizeInactiveMsg, ExitPipelineMsg}; use script::script_task::{ResizeMsg, ResizeInactiveMsg, ExitPipelineMsg};
use script::layout_interface; use script::layout_interface;
@ -30,39 +31,38 @@ use servo_util::task::spawn_named;
use std::cell::RefCell; use std::cell::RefCell;
use std::mem::replace; use std::mem::replace;
use std::io; use std::io;
use std::libc;
use std::rc::Rc; use std::rc::Rc;
use url::Url; use url::Url;
/// Maintains the pipelines and navigation context and grants permission to composite /// Maintains the pipelines and navigation context and grants permission to composite
pub struct Constellation { pub struct Constellation {
chan: ConstellationChan, pub chan: ConstellationChan,
request_port: Receiver<Msg>, pub request_port: Receiver<Msg>,
compositor_chan: CompositorChan, pub compositor_chan: CompositorChan,
resource_task: ResourceTask, pub resource_task: ResourceTask,
image_cache_task: ImageCacheTask, pub image_cache_task: ImageCacheTask,
pipelines: HashMap<PipelineId, Rc<Pipeline>>, pub pipelines: HashMap<PipelineId, Rc<Pipeline>>,
priv navigation_context: NavigationContext, navigation_context: NavigationContext,
priv next_pipeline_id: PipelineId, next_pipeline_id: PipelineId,
priv pending_frames: ~[FrameChange], pending_frames: ~[FrameChange],
priv pending_sizes: HashMap<(PipelineId, SubpageId), Rect<f32>>, pending_sizes: HashMap<(PipelineId, SubpageId), Rect<f32>>,
profiler_chan: ProfilerChan, pub profiler_chan: ProfilerChan,
window_size: Size2D<uint>, pub window_size: Size2D<uint>,
opts: Opts, pub opts: Opts,
} }
/// Stores the Id of the outermost frame's pipeline, along with a vector of children frames /// Stores the Id of the outermost frame's pipeline, along with a vector of children frames
struct FrameTree { struct FrameTree {
pipeline: Rc<Pipeline>, pub pipeline: Rc<Pipeline>,
parent: RefCell<Option<Rc<Pipeline>>>, pub parent: RefCell<Option<Rc<Pipeline>>>,
children: RefCell<~[ChildFrameTree]>, pub children: RefCell<~[ChildFrameTree]>,
} }
struct ChildFrameTree { struct ChildFrameTree {
frame_tree: Rc<FrameTree>, frame_tree: Rc<FrameTree>,
/// Clipping rect representing the size and position, in page coordinates, of the visible /// Clipping rect representing the size and position, in page coordinates, of the visible
/// region of the child frame relative to the parent. /// region of the child frame relative to the parent.
rect: Option<Rect<f32>>, pub rect: Option<Rect<f32>>,
} }
impl Clone for ChildFrameTree { impl Clone for ChildFrameTree {
@ -75,13 +75,13 @@ impl Clone for ChildFrameTree {
} }
pub struct SendableFrameTree { pub struct SendableFrameTree {
pipeline: CompositionPipeline, pub pipeline: CompositionPipeline,
children: ~[SendableChildFrameTree], pub children: ~[SendableChildFrameTree],
} }
pub struct SendableChildFrameTree { pub struct SendableChildFrameTree {
frame_tree: SendableFrameTree, pub frame_tree: SendableFrameTree,
rect: Option<Rect<f32>>, pub rect: Option<Rect<f32>>,
} }
enum ReplaceResult { enum ReplaceResult {
@ -124,7 +124,7 @@ impl FrameTreeTraversal for Rc<FrameTree> {
let mut child = children.mut_iter() let mut child = children.mut_iter()
.find(|child| child.frame_tree.pipeline.id == id); .find(|child| child.frame_tree.pipeline.id == id);
for child in child.mut_iter() { for child in child.mut_iter() {
new_child.parent.set(child.frame_tree.parent.borrow().clone()); *new_child.parent.borrow_mut() = child.frame_tree.parent.borrow().clone();
return ReplacedNode(replace(&mut child.frame_tree, new_child)); return ReplacedNode(replace(&mut child.frame_tree, new_child));
} }
} }
@ -170,16 +170,16 @@ impl Iterator<Rc<FrameTree>> for FrameTreeIterator {
/// Represents the portion of a page that is changing in navigating. /// Represents the portion of a page that is changing in navigating.
struct FrameChange { struct FrameChange {
before: Option<PipelineId>, pub before: Option<PipelineId>,
after: Rc<FrameTree>, pub after: Rc<FrameTree>,
navigation_type: NavigationType, pub navigation_type: NavigationType,
} }
/// Stores the Id's of the pipelines previous and next in the browser's history /// Stores the Id's of the pipelines previous and next in the browser's history
struct NavigationContext { struct NavigationContext {
previous: ~[Rc<FrameTree>], pub previous: ~[Rc<FrameTree>],
next: ~[Rc<FrameTree>], pub next: ~[Rc<FrameTree>],
current: Option<Rc<FrameTree>>, pub current: Option<Rc<FrameTree>>,
} }
impl NavigationContext { impl NavigationContext {

View file

@ -23,12 +23,12 @@ use style::{After, Before, ComputedValues, MatchedProperty, Stylist, TElement, T
use sync::Arc; use sync::Arc;
pub struct ApplicableDeclarations { pub struct ApplicableDeclarations {
normal: SmallVec16<MatchedProperty>, pub normal: SmallVec16<MatchedProperty>,
before: SmallVec0<MatchedProperty>, pub before: SmallVec0<MatchedProperty>,
after: SmallVec0<MatchedProperty>, pub after: SmallVec0<MatchedProperty>,
/// Whether the `normal` declarations are shareable with other nodes. /// Whether the `normal` declarations are shareable with other nodes.
normal_shareable: bool, pub normal_shareable: bool,
} }
impl ApplicableDeclarations { impl ApplicableDeclarations {
@ -51,7 +51,7 @@ impl ApplicableDeclarations {
#[deriving(Clone)] #[deriving(Clone)]
pub struct ApplicableDeclarationsCacheEntry { pub struct ApplicableDeclarationsCacheEntry {
declarations: SmallVec16<MatchedProperty>, pub declarations: SmallVec16<MatchedProperty>,
} }
impl ApplicableDeclarationsCacheEntry { impl ApplicableDeclarationsCacheEntry {
@ -131,7 +131,7 @@ impl<'a> Hash for ApplicableDeclarationsCacheQuery<'a> {
static APPLICABLE_DECLARATIONS_CACHE_SIZE: uint = 32; static APPLICABLE_DECLARATIONS_CACHE_SIZE: uint = 32;
pub struct ApplicableDeclarationsCache { pub struct ApplicableDeclarationsCache {
cache: SimpleHashCache<ApplicableDeclarationsCacheEntry,Arc<ComputedValues>>, pub cache: SimpleHashCache<ApplicableDeclarationsCacheEntry,Arc<ComputedValues>>,
} }
impl ApplicableDeclarationsCache { impl ApplicableDeclarationsCache {
@ -155,18 +155,18 @@ impl ApplicableDeclarationsCache {
/// An LRU cache of the last few nodes seen, so that we can aggressively try to reuse their styles. /// An LRU cache of the last few nodes seen, so that we can aggressively try to reuse their styles.
pub struct StyleSharingCandidateCache { pub struct StyleSharingCandidateCache {
priv cache: LRUCache<StyleSharingCandidate,()>, cache: LRUCache<StyleSharingCandidate,()>,
} }
#[deriving(Clone)] #[deriving(Clone)]
pub struct StyleSharingCandidate { pub struct StyleSharingCandidate {
style: Arc<ComputedValues>, pub style: Arc<ComputedValues>,
parent_style: Arc<ComputedValues>, pub parent_style: Arc<ComputedValues>,
// TODO(pcwalton): Intern. // TODO(pcwalton): Intern.
local_name: DOMString, pub local_name: DOMString,
class: Option<DOMString>, pub class: Option<DOMString>,
} }
impl Eq for StyleSharingCandidate { impl Eq for StyleSharingCandidate {
@ -347,11 +347,11 @@ impl<'ln> PrivateMatchMethods for LayoutNode<'ln> {
let cache_entry = applicable_declarations_cache.find(applicable_declarations); let cache_entry = applicable_declarations_cache.find(applicable_declarations);
match cache_entry { match cache_entry {
None => cached_computed_values = None, None => cached_computed_values = None,
Some(ref style) => cached_computed_values = Some(style.get()), Some(ref style) => cached_computed_values = Some(&**style),
} }
let (the_style, is_cacheable) = cascade(applicable_declarations, let (the_style, is_cacheable) = cascade(applicable_declarations,
shareable, shareable,
Some(parent_style.get()), Some(&***parent_style),
initial_values, initial_values,
cached_computed_values); cached_computed_values);
cacheable = is_cacheable; cacheable = is_cacheable;
@ -492,7 +492,7 @@ impl<'ln> MatchMethods for LayoutNode<'ln> {
} }
unsafe { unsafe {
let initial_values = layout_context.initial_css_values.get(); let initial_values = &*layout_context.initial_css_values;
self.cascade_node(parent, self.cascade_node(parent,
initial_values, initial_values,
applicable_declarations, applicable_declarations,

View file

@ -42,19 +42,19 @@ use sync::Arc;
/// Information specific to floated blocks. /// Information specific to floated blocks.
pub struct FloatedBlockInfo { pub struct FloatedBlockInfo {
containing_width: Au, pub containing_width: Au,
/// Offset relative to where the parent tried to position this flow /// Offset relative to where the parent tried to position this flow
rel_pos: Point2D<Au>, pub rel_pos: Point2D<Au>,
/// Index into the box list for inline floats /// Index into the box list for inline floats
index: Option<uint>, pub index: Option<uint>,
/// Number of floated children /// Number of floated children
floated_children: uint, pub floated_children: uint,
/// Left or right? /// Left or right?
float_kind: FloatKind, pub float_kind: FloatKind,
} }
impl FloatedBlockInfo { impl FloatedBlockInfo {
@ -481,20 +481,20 @@ fn propagate_layer_flag_from_child(layers_needed_for_descendants: &mut bool, kid
// A block formatting context. // A block formatting context.
pub struct BlockFlow { pub struct BlockFlow {
/// Data common to all flows. /// Data common to all flows.
base: BaseFlow, pub base: BaseFlow,
/// The associated box. /// The associated box.
box_: Box, pub box_: Box,
/// TODO: is_root should be a bit field to conserve memory. /// TODO: is_root should be a bit field to conserve memory.
/// Whether this block flow is the root flow. /// Whether this block flow is the root flow.
is_root: bool, pub is_root: bool,
/// Static y offset of an absolute flow from its CB. /// Static y offset of an absolute flow from its CB.
static_y_offset: Au, pub static_y_offset: Au,
/// Additional floating flow members. /// Additional floating flow members.
float: Option<~FloatedBlockInfo> pub float: Option<~FloatedBlockInfo>
} }
impl BlockFlow { impl BlockFlow {
@ -780,9 +780,9 @@ impl BlockFlow {
self.base.position.size.height = self.base.position.size.height + top_margin_value + self.base.position.size.height = self.base.position.size.height + top_margin_value +
bottom_margin_value; bottom_margin_value;
let mut position = self.box_.border_box.get(); let mut position = *self.box_.border_box.borrow();
position.size.height = position.size.height + top_margin_value + bottom_margin_value; position.size.height = position.size.height + top_margin_value + bottom_margin_value;
self.box_.border_box.set(position); *self.box_.border_box.borrow_mut() = position;
} }
/// Assign height for current flow. /// Assign height for current flow.
@ -819,14 +819,14 @@ impl BlockFlow {
self.base.floats.translate(Point2D(-self.box_.left_offset(), Au(0))); self.base.floats.translate(Point2D(-self.box_.left_offset(), Au(0)));
// The sum of our top border and top padding. // The sum of our top border and top padding.
let top_offset = self.box_.border.get().top + self.box_.padding.get().top; let top_offset = self.box_.border.borrow().top + self.box_.padding.borrow().top;
translate_including_floats(&mut cur_y, top_offset, inorder, &mut self.base.floats); translate_including_floats(&mut cur_y, top_offset, inorder, &mut self.base.floats);
let can_collapse_top_margin_with_kids = let can_collapse_top_margin_with_kids =
margins_may_collapse == MarginsMayCollapse && margins_may_collapse == MarginsMayCollapse &&
!self.is_absolutely_positioned() && !self.is_absolutely_positioned() &&
self.box_.border.get().top == Au(0) && self.box_.border.borrow().top == Au(0) &&
self.box_.padding.get().top == Au(0); self.box_.padding.borrow().top == Au(0);
margin_collapse_info.initialize_top_margin(&self.box_, margin_collapse_info.initialize_top_margin(&self.box_,
can_collapse_top_margin_with_kids); can_collapse_top_margin_with_kids);
@ -940,8 +940,8 @@ impl BlockFlow {
let can_collapse_bottom_margin_with_kids = let can_collapse_bottom_margin_with_kids =
margins_may_collapse == MarginsMayCollapse && margins_may_collapse == MarginsMayCollapse &&
!self.is_absolutely_positioned() && !self.is_absolutely_positioned() &&
self.box_.border.get().bottom == Au(0) && self.box_.border.borrow().bottom == Au(0) &&
self.box_.padding.get().bottom == Au(0); self.box_.padding.borrow().bottom == Au(0);
let (collapsible_margins, delta) = let (collapsible_margins, delta) =
margin_collapse_info.finish_and_compute_collapsible_margins( margin_collapse_info.finish_and_compute_collapsible_margins(
&self.box_, &self.box_,
@ -970,9 +970,9 @@ impl BlockFlow {
// Store the content height for use in calculating the absolute flow's dimensions // Store the content height for use in calculating the absolute flow's dimensions
// later. // later.
let mut temp_position = self.box_.border_box.get(); let mut temp_position = *self.box_.border_box.borrow();
temp_position.size.height = height; temp_position.size.height = height;
self.box_.border_box.set(temp_position); *self.box_.border_box.borrow_mut() = temp_position;
return return
} }
@ -991,15 +991,15 @@ impl BlockFlow {
translate_including_floats(&mut cur_y, delta, inorder, &mut floats); translate_including_floats(&mut cur_y, delta, inorder, &mut floats);
// Compute content height and noncontent height. // Compute content height and noncontent height.
let bottom_offset = self.box_.border.get().bottom + self.box_.padding.get().bottom; let bottom_offset = self.box_.border.borrow().bottom + self.box_.padding.borrow().bottom;
translate_including_floats(&mut cur_y, bottom_offset, inorder, &mut floats); translate_including_floats(&mut cur_y, bottom_offset, inorder, &mut floats);
// Now that `cur_y` is at the bottom of the border box, compute the final border box // Now that `cur_y` is at the bottom of the border box, compute the final border box
// position. // position.
let mut border_box = self.box_.border_box.get(); let mut border_box = *self.box_.border_box.borrow();
border_box.size.height = cur_y; border_box.size.height = cur_y;
border_box.origin.y = Au(0); border_box.origin.y = Au(0);
self.box_.border_box.set(border_box); *self.box_.border_box.borrow_mut() = border_box;
self.base.position.size.height = cur_y; self.base.position.size.height = cur_y;
self.base.floats = floats.clone(); self.base.floats = floats.clone();
@ -1031,18 +1031,18 @@ impl BlockFlow {
/// Therefore, assign_height_float was already called on this kid flow by /// Therefore, assign_height_float was already called on this kid flow by
/// the traversal function. So, the values used are well-defined. /// the traversal function. So, the values used are well-defined.
pub fn assign_height_float_inorder(&mut self) { pub fn assign_height_float_inorder(&mut self) {
let height = self.box_.border_box.get().size.height; let height = self.box_.border_box.borrow().size.height;
let clearance = match self.box_.clear() { let clearance = match self.box_.clear() {
None => Au(0), None => Au(0),
Some(clear) => self.base.floats.clearance(clear), Some(clear) => self.base.floats.clearance(clear),
}; };
let noncontent_width = self.box_.padding.get().left + self.box_.padding.get().right + let noncontent_width = self.box_.padding.borrow().left + self.box_.padding.borrow().right +
self.box_.border.get().left + self.box_.border.get().right; self.box_.border.borrow().left + self.box_.border.borrow().right;
let full_noncontent_width = noncontent_width + self.box_.margin.get().left + let full_noncontent_width = noncontent_width + self.box_.margin.borrow().left +
self.box_.margin.get().right; self.box_.margin.borrow().right;
let margin_height = self.box_.margin.get().top + self.box_.margin.get().bottom; let margin_height = self.box_.margin.borrow().top + self.box_.margin.borrow().bottom;
let info = PlacementInfo { let info = PlacementInfo {
size: Size2D(self.base.position.size.width + full_noncontent_width, size: Size2D(self.base.position.size.width + full_noncontent_width,
@ -1083,7 +1083,7 @@ impl BlockFlow {
} }
let mut cur_y = Au(0); let mut cur_y = Au(0);
let top_offset = self.box_.margin.get().top + self.box_.border.get().top + self.box_.padding.get().top; let top_offset = self.box_.margin.borrow().top + self.box_.border.borrow().top + self.box_.padding.borrow().top;
cur_y = cur_y + top_offset; cur_y = cur_y + top_offset;
// cur_y is now at the top content edge // cur_y is now at the top content edge
@ -1098,13 +1098,13 @@ impl BlockFlow {
let content_height = cur_y - top_offset; let content_height = cur_y - top_offset;
let mut noncontent_height; let mut noncontent_height;
let mut position = self.box_.border_box.get(); let mut position = *self.box_.border_box.borrow();
// The associated box is the border box of this flow. // The associated box is the border box of this flow.
position.origin.y = self.box_.margin.get().top; position.origin.y = self.box_.margin.borrow().top;
noncontent_height = self.box_.padding.get().top + self.box_.padding.get().bottom + noncontent_height = self.box_.padding.borrow().top + self.box_.padding.borrow().bottom +
self.box_.border.get().top + self.box_.border.get().bottom; self.box_.border.borrow().top + self.box_.border.borrow().bottom;
// Calculate content height, taking `min-height` and `max-height` into account. // Calculate content height, taking `min-height` and `max-height` into account.
@ -1121,7 +1121,7 @@ impl BlockFlow {
debug!("assign_height_float -- height: {}", content_height + noncontent_height); debug!("assign_height_float -- height: {}", content_height + noncontent_height);
position.size.height = content_height + noncontent_height; position.size.height = content_height + noncontent_height;
self.box_.border_box.set(position); *self.box_.border_box.borrow_mut() = position;
} }
fn build_display_list_block_common(&mut self, fn build_display_list_block_common(&mut self,
@ -1232,13 +1232,13 @@ impl BlockFlow {
let static_y_offset = self.static_y_offset; let static_y_offset = self.static_y_offset;
// This is the stored content height value from assign-height // This is the stored content height value from assign-height
let content_height = self.box_.border_box.get().size.height - self.box_.noncontent_height(); let content_height = self.box_.border_box.borrow().size.height - self.box_.noncontent_height();
let style = self.box_.style(); let style = self.box_.style();
// Non-auto margin-top and margin-bottom values have already been // Non-auto margin-top and margin-bottom values have already been
// calculated during assign-width. // calculated during assign-width.
let margin = self.box_.margin.get(); let mut margin = self.box_.margin.borrow_mut();
let margin_top = match MaybeAuto::from_style(style.Margin.get().margin_top, Au(0)) { let margin_top = match MaybeAuto::from_style(style.Margin.get().margin_top, Au(0)) {
Auto => Auto, Auto => Auto,
_ => Specified(margin.top) _ => Specified(margin.top)
@ -1262,7 +1262,7 @@ impl BlockFlow {
// TODO: Right now, this content height value includes the // TODO: Right now, this content height value includes the
// margin because of erroneous height calculation in Box_. // margin because of erroneous height calculation in Box_.
// Check this when that has been fixed. // Check this when that has been fixed.
let height_used_val = self.box_.border_box.get().size.height; let height_used_val = self.box_.border_box.borrow().size.height;
solution = Some(HeightConstraintSolution::solve_vertical_constraints_abs_replaced( solution = Some(HeightConstraintSolution::solve_vertical_constraints_abs_replaced(
height_used_val, height_used_val,
margin_top, margin_top,
@ -1294,17 +1294,14 @@ impl BlockFlow {
let solution = solution.unwrap(); let solution = solution.unwrap();
let mut margin = self.box_.margin.get();
margin.top = solution.margin_top; margin.top = solution.margin_top;
margin.bottom = solution.margin_bottom; margin.bottom = solution.margin_bottom;
self.box_.margin.set(margin);
let mut position = self.box_.border_box.get(); let mut position = self.box_.border_box.borrow_mut();
position.origin.y = Au(0); position.origin.y = Au(0);
// Border box height // Border box height
let border_and_padding = self.box_.noncontent_height(); let border_and_padding = self.box_.noncontent_height();
position.size.height = solution.height + border_and_padding; position.size.height = solution.height + border_and_padding;
self.box_.border_box.set(position);
self.base.position.origin.y = solution.top + margin.top; self.base.position.origin.y = solution.top + margin.top;
self.base.position.size.height = solution.height + border_and_padding; self.base.position.size.height = solution.height + border_and_padding;
@ -1403,7 +1400,7 @@ impl BlockFlow {
// Pass yourself as a new Containing Block // Pass yourself as a new Containing Block
// The static x offset for any immediate kid flows will be the // The static x offset for any immediate kid flows will be the
// left padding // left padding
kid_abs_cb_x_offset = self.box_.padding.get().left; kid_abs_cb_x_offset = self.box_.padding.borrow().left;
} else { } else {
// For kids, the left margin edge will be at our left content edge. // For kids, the left margin edge will be at our left content edge.
// The current static offset is at our left margin // The current static offset is at our left margin
@ -1570,11 +1567,11 @@ impl Flow for BlockFlow {
self.base.clear = self.box_.style().Box.get().clear; self.base.clear = self.box_.style().Box.get().clear;
// Move in from the left border edge // Move in from the left border edge
let left_content_edge = self.box_.border_box.get().origin.x let left_content_edge = self.box_.border_box.borrow().origin.x
+ self.box_.padding.get().left + self.box_.border.get().left; + self.box_.padding.borrow().left + self.box_.border.borrow().left;
let padding_and_borders = self.box_.padding.get().left + self.box_.padding.get().right + let padding_and_borders = self.box_.padding.borrow().left + self.box_.padding.borrow().right +
self.box_.border.get().left + self.box_.border.get().right; self.box_.border.borrow().left + self.box_.border.borrow().right;
let content_width = self.box_.border_box.get().size.width - padding_and_borders; let content_width = self.box_.border_box.borrow().size.width - padding_and_borders;
if self.is_float() { if self.is_float() {
self.base.position.size.width = content_width; self.base.position.size.width = content_width;
@ -1637,7 +1634,7 @@ impl Flow for BlockFlow {
/// The 'position' property of this flow. /// The 'position' property of this flow.
fn positioning(&self) -> position::T { fn positioning(&self) -> position::T {
self.box_.style.get().Box.get().position self.box_.style.Box.get().position
} }
/// Return true if this is the root of an Absolute flow tree. /// Return true if this is the root of an Absolute flow tree.
@ -1657,7 +1654,7 @@ impl Flow for BlockFlow {
/// Return position of the CB generated by this flow from the start of this flow. /// Return position of the CB generated by this flow from the start of this flow.
fn generated_cb_position(&self) -> Point2D<Au> { fn generated_cb_position(&self) -> Point2D<Au> {
// Border box y coordinate + border top // Border box y coordinate + border top
self.box_.border_box.get().origin + Point2D(self.box_.border.get().left, self.box_.border.get().top) self.box_.border_box.borrow().origin + Point2D(self.box_.border.borrow().left, self.box_.border.borrow().top)
} }
fn layer_id(&self, fragment_index: uint) -> LayerId { fn layer_id(&self, fragment_index: uint) -> LayerId {
@ -1685,13 +1682,13 @@ impl Flow for BlockFlow {
/// The inputs for the widths-and-margins constraint equation. /// The inputs for the widths-and-margins constraint equation.
pub struct WidthConstraintInput { pub struct WidthConstraintInput {
computed_width: MaybeAuto, pub computed_width: MaybeAuto,
left_margin: MaybeAuto, pub left_margin: MaybeAuto,
right_margin: MaybeAuto, pub right_margin: MaybeAuto,
left: MaybeAuto, pub left: MaybeAuto,
right: MaybeAuto, pub right: MaybeAuto,
available_width: Au, pub available_width: Au,
static_x_offset: Au, pub static_x_offset: Au,
} }
impl WidthConstraintInput { impl WidthConstraintInput {
@ -1717,11 +1714,11 @@ impl WidthConstraintInput {
/// The solutions for the widths-and-margins constraint equation. /// The solutions for the widths-and-margins constraint equation.
pub struct WidthConstraintSolution { pub struct WidthConstraintSolution {
left: Au, pub left: Au,
right: Au, pub right: Au,
width: Au, pub width: Au,
margin_left: Au, pub margin_left: Au,
margin_right: Au pub margin_right: Au
} }
impl WidthConstraintSolution { impl WidthConstraintSolution {
@ -1807,15 +1804,14 @@ pub trait WidthAndMarginsComputer {
block: &mut BlockFlow, block: &mut BlockFlow,
solution: WidthConstraintSolution) { solution: WidthConstraintSolution) {
let box_ = block.box_(); let box_ = block.box_();
let mut margin = box_.margin.get(); let mut margin = box_.margin.borrow_mut();
margin.left = solution.margin_left; margin.left = solution.margin_left;
margin.right = solution.margin_right; margin.right = solution.margin_right;
box_.margin.set(margin);
// The associated box is the border box of this flow. // The associated box is the border box of this flow.
let mut position_ref = box_.border_box.borrow_mut(); let mut position_ref = box_.border_box.borrow_mut();
// Left border edge. // Left border edge.
position_ref.origin.x = box_.margin.borrow().left; position_ref.origin.x = margin.left;
// Border box width // Border box width
position_ref.size.width = solution.width + box_.noncontent_width(); position_ref.size.width = solution.width + box_.noncontent_width();

View file

@ -16,7 +16,7 @@ use layout::model;
use layout::util::OpaqueNodeMethods; use layout::util::OpaqueNodeMethods;
use layout::wrapper::{TLayoutNode, ThreadSafeLayoutNode}; use layout::wrapper::{TLayoutNode, ThreadSafeLayoutNode};
use sync::{MutexArc, Arc}; use sync::{Arc, Mutex};
use geom::{Point2D, Rect, Size2D, SideOffsets2D}; use geom::{Point2D, Rect, Size2D, SideOffsets2D};
use geom::approxeq::ApproxEq; use geom::approxeq::ApproxEq;
use gfx::color::rgb; use gfx::color::rgb;
@ -30,7 +30,6 @@ use gfx::font::FontStyle;
use gfx::text::text_run::TextRun; use gfx::text::text_run::TextRun;
use servo_msg::constellation_msg::{ConstellationChan, FrameRectMsg, PipelineId, SubpageId}; use servo_msg::constellation_msg::{ConstellationChan, FrameRectMsg, PipelineId, SubpageId};
use servo_net::image::holder::ImageHolder; use servo_net::image::holder::ImageHolder;
use servo_net::local_image_cache::LocalImageCache;
use servo_util::geometry::Au; use servo_util::geometry::Au;
use servo_util::geometry; use servo_util::geometry;
use servo_util::range::*; use servo_util::range::*;
@ -71,37 +70,37 @@ use url::Url;
#[deriving(Clone)] #[deriving(Clone)]
pub struct Box { pub struct Box {
/// An opaque reference to the DOM node that this `Box` originates from. /// An opaque reference to the DOM node that this `Box` originates from.
node: OpaqueNode, pub node: OpaqueNode,
/// The CSS style of this box. /// The CSS style of this box.
style: Arc<ComputedValues>, pub style: Arc<ComputedValues>,
/// The position of this box relative to its owning flow. /// The position of this box relative to its owning flow.
/// The size includes padding and border, but not margin. /// The size includes padding and border, but not margin.
border_box: RefCell<Rect<Au>>, pub border_box: RefCell<Rect<Au>>,
/// The border of the content box. /// The border of the content box.
/// ///
/// FIXME(pcwalton): This need not be stored in the box. /// FIXME(pcwalton): This need not be stored in the box.
border: RefCell<SideOffsets2D<Au>>, pub border: RefCell<SideOffsets2D<Au>>,
/// The padding of the content box. /// The padding of the content box.
padding: RefCell<SideOffsets2D<Au>>, pub padding: RefCell<SideOffsets2D<Au>>,
/// The margin of the content box. /// The margin of the content box.
margin: RefCell<SideOffsets2D<Au>>, pub margin: RefCell<SideOffsets2D<Au>>,
/// Info specific to the kind of box. Keep this enum small. /// Info specific to the kind of box. Keep this enum small.
specific: SpecificBoxInfo, pub specific: SpecificBoxInfo,
/// positioned box offsets /// positioned box offsets
position_offsets: RefCell<SideOffsets2D<Au>>, pub position_offsets: RefCell<SideOffsets2D<Au>>,
/// Inline data /// Inline data
inline_info: RefCell<Option<InlineInfo>>, pub inline_info: RefCell<Option<InlineInfo>>,
/// New-line chracter(\n)'s positions(relative, not absolute) /// New-line chracter(\n)'s positions(relative, not absolute)
new_line_pos: ~[uint], pub new_line_pos: ~[uint],
} }
/// Info specific to the kind of box. Keep this enum small. /// Info specific to the kind of box. Keep this enum small.
@ -123,11 +122,11 @@ pub enum SpecificBoxInfo {
#[deriving(Clone)] #[deriving(Clone)]
pub struct ImageBoxInfo { pub struct ImageBoxInfo {
/// The image held within this box. /// The image held within this box.
image: RefCell<ImageHolder>, pub image: RefCell<ImageHolder>,
computed_width: RefCell<Option<Au>>, pub computed_width: RefCell<Option<Au>>,
computed_height: RefCell<Option<Au>>, pub computed_height: RefCell<Option<Au>>,
dom_width: Option<Au>, pub dom_width: Option<Au>,
dom_height: Option<Au>, pub dom_height: Option<Au>,
} }
impl ImageBoxInfo { impl ImageBoxInfo {
@ -137,7 +136,7 @@ impl ImageBoxInfo {
/// me. /// me.
pub fn new(node: &ThreadSafeLayoutNode, pub fn new(node: &ThreadSafeLayoutNode,
image_url: Url, image_url: Url,
local_image_cache: MutexArc<LocalImageCache>) local_image_cache: Arc<Mutex<*()>>)
-> ImageBoxInfo { -> ImageBoxInfo {
fn convert_length(node: &ThreadSafeLayoutNode, name: &str) -> Option<Au> { fn convert_length(node: &ThreadSafeLayoutNode, name: &str) -> Option<Au> {
let element = node.as_element(); let element = node.as_element();
@ -216,9 +215,9 @@ impl ImageBoxInfo {
#[deriving(Clone)] #[deriving(Clone)]
pub struct IframeBoxInfo { pub struct IframeBoxInfo {
/// The pipeline ID of this iframe. /// The pipeline ID of this iframe.
pipeline_id: PipelineId, pub pipeline_id: PipelineId,
/// The subpage ID of this iframe. /// The subpage ID of this iframe.
subpage_id: SubpageId, pub subpage_id: SubpageId,
} }
impl IframeBoxInfo { impl IframeBoxInfo {
@ -239,10 +238,10 @@ impl IframeBoxInfo {
#[deriving(Clone)] #[deriving(Clone)]
pub struct ScannedTextBoxInfo { pub struct ScannedTextBoxInfo {
/// The text run that this represents. /// The text run that this represents.
run: Arc<~TextRun>, pub run: Arc<~TextRun>,
/// The range within the above text run that this represents. /// The range within the above text run that this represents.
range: Range, pub range: Range,
} }
impl ScannedTextBoxInfo { impl ScannedTextBoxInfo {
@ -260,7 +259,7 @@ impl ScannedTextBoxInfo {
#[deriving(Clone)] #[deriving(Clone)]
pub struct UnscannedTextBoxInfo { pub struct UnscannedTextBoxInfo {
/// The text inside the box. /// The text inside the box.
text: ~str, pub text: ~str,
} }
impl UnscannedTextBoxInfo { impl UnscannedTextBoxInfo {
@ -297,8 +296,8 @@ pub enum SplitBoxResult {
/// Use atomic reference counting instead. /// Use atomic reference counting instead.
#[deriving(Clone)] #[deriving(Clone)]
pub struct InlineInfo { pub struct InlineInfo {
parent_info: SmallVec0<InlineParentInfo>, pub parent_info: SmallVec0<InlineParentInfo>,
baseline: Au, pub baseline: Au,
} }
impl InlineInfo { impl InlineInfo {
@ -312,20 +311,20 @@ impl InlineInfo {
#[deriving(Clone)] #[deriving(Clone)]
pub struct InlineParentInfo { pub struct InlineParentInfo {
padding: SideOffsets2D<Au>, pub padding: SideOffsets2D<Au>,
border: SideOffsets2D<Au>, pub border: SideOffsets2D<Au>,
margin: SideOffsets2D<Au>, pub margin: SideOffsets2D<Au>,
style: Arc<ComputedValues>, pub style: Arc<ComputedValues>,
font_ascent: Au, pub font_ascent: Au,
font_descent: Au, pub font_descent: Au,
node: OpaqueNode, pub node: OpaqueNode,
} }
/// A box that represents a table column. /// A box that represents a table column.
#[deriving(Clone)] #[deriving(Clone)]
pub struct TableColumnBoxInfo { pub struct TableColumnBoxInfo {
/// the number of columns a <col> element should span /// the number of columns a <col> element should span
span: Option<int>, pub span: Option<int>,
} }
impl TableColumnBoxInfo { impl TableColumnBoxInfo {
@ -348,7 +347,7 @@ impl TableColumnBoxInfo {
macro_rules! def_noncontent( ($side:ident, $get:ident, $inline_get:ident) => ( macro_rules! def_noncontent( ($side:ident, $get:ident, $inline_get:ident) => (
impl Box { impl Box {
pub fn $get(&self) -> Au { pub fn $get(&self) -> Au {
self.border.get().$side + self.padding.get().$side self.border.borrow().$side + self.padding.borrow().$side
} }
pub fn $inline_get(&self) -> Au { pub fn $inline_get(&self) -> Au {
@ -469,7 +468,7 @@ impl Box {
// //
// Anonymous table boxes, TableRowBox and TableCellBox, are generated around `Foo`, but it shouldn't inherit the border. // Anonymous table boxes, TableRowBox and TableCellBox, are generated around `Foo`, but it shouldn't inherit the border.
let (node_style, _) = cascade(&[], false, Some(node.style().get()), let (node_style, _) = cascade(&[], false, Some(&**node.style()),
&initial_values(), None); &initial_values(), None);
Box { Box {
node: OpaqueNodeMethods::from_thread_safe_layout_node(node), node: OpaqueNodeMethods::from_thread_safe_layout_node(node),
@ -518,10 +517,10 @@ impl Box {
Box { Box {
node: self.node, node: self.node,
style: self.style.clone(), style: self.style.clone(),
border_box: RefCell::new(Rect(self.border_box.get().origin, size)), border_box: RefCell::new(Rect(self.border_box.borrow().origin, size)),
border: RefCell::new(self.border.get()), border: RefCell::new(*self.border.borrow()),
padding: RefCell::new(self.padding.get()), padding: RefCell::new(*self.padding.borrow()),
margin: RefCell::new(self.margin.get()), margin: RefCell::new(*self.margin.borrow()),
specific: specific, specific: specific,
position_offsets: RefCell::new(Zero::zero()), position_offsets: RefCell::new(Zero::zero()),
inline_info: self.inline_info.clone(), inline_info: self.inline_info.clone(),
@ -561,7 +560,7 @@ impl Box {
}; };
let surround_width = margin_left + margin_right + padding_left + padding_right + let surround_width = margin_left + margin_right + padding_left + padding_right +
self.border.get().left + self.border.get().right; self.border.borrow().left + self.border.borrow().right;
IntrinsicWidths { IntrinsicWidths {
minimum_width: width, minimum_width: width,
@ -608,11 +607,11 @@ impl Box {
style.Border.get().border_left_style)) style.Border.get().border_left_style))
} }
}; };
self.border.set(border) *self.border.borrow_mut() = border;
} }
pub fn compute_positioned_offsets(&self, style: &ComputedValues, containing_width: Au, containing_height: Au) { pub fn compute_positioned_offsets(&self, style: &ComputedValues, containing_width: Au, containing_height: Au) {
self.position_offsets.set(SideOffsets2D::new( *self.position_offsets.borrow_mut() = SideOffsets2D::new(
MaybeAuto::from_style(style.PositionOffsets.get().top, containing_height) MaybeAuto::from_style(style.PositionOffsets.get().top, containing_height)
.specified_or_zero(), .specified_or_zero(),
MaybeAuto::from_style(style.PositionOffsets.get().right, containing_width) MaybeAuto::from_style(style.PositionOffsets.get().right, containing_width)
@ -620,7 +619,7 @@ impl Box {
MaybeAuto::from_style(style.PositionOffsets.get().bottom, containing_height) MaybeAuto::from_style(style.PositionOffsets.get().bottom, containing_height)
.specified_or_zero(), .specified_or_zero(),
MaybeAuto::from_style(style.PositionOffsets.get().left, containing_width) MaybeAuto::from_style(style.PositionOffsets.get().left, containing_width)
.specified_or_zero())); .specified_or_zero());
} }
/// Compute and set margin-top and margin-bottom values. /// Compute and set margin-top and margin-bottom values.
@ -631,7 +630,7 @@ impl Box {
pub fn compute_margin_top_bottom(&self, containing_block_width: Au) { pub fn compute_margin_top_bottom(&self, containing_block_width: Au) {
match self.specific { match self.specific {
TableBox | TableCellBox | TableRowBox | TableColumnBox(_) => { TableBox | TableCellBox | TableRowBox | TableColumnBox(_) => {
self.margin.set(SideOffsets2D::new(Au(0), Au(0), Au(0), Au(0))) *self.margin.borrow_mut() = SideOffsets2D::new(Au(0), Au(0), Au(0), Au(0));
}, },
_ => { _ => {
let style = self.style(); let style = self.style();
@ -640,10 +639,10 @@ impl Box {
containing_block_width).specified_or_zero(); containing_block_width).specified_or_zero();
let margin_bottom = MaybeAuto::from_style(style.Margin.get().margin_bottom, let margin_bottom = MaybeAuto::from_style(style.Margin.get().margin_bottom,
containing_block_width).specified_or_zero(); containing_block_width).specified_or_zero();
let mut margin = self.margin.get(); let mut margin = *self.margin.borrow();
margin.top = margin_top; margin.top = margin_top;
margin.bottom = margin_bottom; margin.bottom = margin_bottom;
self.margin.set(margin); *self.margin.borrow_mut() = margin;
} }
} }
} }
@ -674,7 +673,7 @@ impl Box {
containing_block_width)) containing_block_width))
} }
}; };
self.padding.set(padding) *self.padding.borrow_mut() = padding;
} }
fn compute_padding_length(&self, padding: LengthOrPercentage, content_box_width: Au) -> Au { fn compute_padding_length(&self, padding: LengthOrPercentage, content_box_width: Au) -> Au {
@ -682,9 +681,9 @@ impl Box {
} }
pub fn padding_box_size(&self) -> Size2D<Au> { pub fn padding_box_size(&self) -> Size2D<Au> {
let border_box_size = self.border_box.get().size; let border_box_size = self.border_box.borrow().size;
Size2D(border_box_size.width - self.border.get().left - self.border.get().right, Size2D(border_box_size.width - self.border.borrow().left - self.border.borrow().right,
border_box_size.height - self.border.get().top - self.border.get().bottom) border_box_size.height - self.border.borrow().top - self.border.borrow().bottom)
} }
pub fn noncontent_width(&self) -> Au { pub fn noncontent_width(&self) -> Au {
@ -739,10 +738,10 @@ impl Box {
match &*info { match &*info {
&Some(ref info) => { &Some(ref info) => {
for info in info.parent_info.iter() { for info in info.parent_info.iter() {
if info.style.get().Box.get().position == position::relative { if info.style.Box.get().position == position::relative {
rel_pos.x = rel_pos.x + left_right(info.style.get(), rel_pos.x = rel_pos.x + left_right(&*info.style,
container_block_size.width); container_block_size.width);
rel_pos.y = rel_pos.y + top_bottom(info.style.get(), rel_pos.y = rel_pos.y + top_bottom(&*info.style,
container_block_size.height); container_block_size.height);
} }
} }
@ -776,11 +775,11 @@ impl Box {
debug!("(font style) start"); debug!("(font style) start");
// FIXME: Too much allocation here. // FIXME: Too much allocation here.
let font_families = my_style.Font.get().font_family.map(|family| { let font_families = my_style.Font.get().font_family.iter().map(|family| {
match *family { match *family {
font_family::FamilyName(ref name) => (*name).clone(), font_family::FamilyName(ref name) => (*name).clone(),
} }
}); }).collect();
debug!("(font style) font families: `{:?}`", font_families); debug!("(font style) font families: `{:?}`", font_families);
let font_size = my_style.Font.get().font_size.to_f64().unwrap() / 60.0; let font_size = my_style.Font.get().font_size.to_f64().unwrap() / 60.0;
@ -796,7 +795,7 @@ impl Box {
#[inline(always)] #[inline(always)]
pub fn style<'a>(&'a self) -> &'a ComputedValues { pub fn style<'a>(&'a self) -> &'a ComputedValues {
self.style.get() &*self.style
} }
/// Returns the text alignment of the computed style of the nearest ancestor-or-self `Element` /// Returns the text alignment of the computed style of the nearest ancestor-or-self `Element`
@ -827,33 +826,33 @@ impl Box {
/// Returns the left offset from margin edge to content edge. /// Returns the left offset from margin edge to content edge.
pub fn left_offset(&self) -> Au { pub fn left_offset(&self) -> Au {
match self.specific { match self.specific {
TableWrapperBox => self.margin.get().left, TableWrapperBox => self.margin.borrow().left,
TableBox | TableCellBox => self.border.get().left + self.padding.get().left, TableBox | TableCellBox => self.border.borrow().left + self.padding.borrow().left,
TableRowBox => self.border.get().left, TableRowBox => self.border.borrow().left,
TableColumnBox(_) => Au(0), TableColumnBox(_) => Au(0),
_ => self.margin.get().left + self.border.get().left + self.padding.get().left _ => self.margin.borrow().left + self.border.borrow().left + self.padding.borrow().left
} }
} }
/// Returns the top offset from margin edge to content edge. /// Returns the top offset from margin edge to content edge.
pub fn top_offset(&self) -> Au { pub fn top_offset(&self) -> Au {
match self.specific { match self.specific {
TableWrapperBox => self.margin.get().top, TableWrapperBox => self.margin.borrow().top,
TableBox | TableCellBox => self.border.get().top + self.padding.get().top, TableBox | TableCellBox => self.border.borrow().top + self.padding.borrow().top,
TableRowBox => self.border.get().top, TableRowBox => self.border.borrow().top,
TableColumnBox(_) => Au(0), TableColumnBox(_) => Au(0),
_ => self.margin.get().top + self.border.get().top + self.padding.get().top _ => self.margin.borrow().top + self.border.borrow().top + self.padding.borrow().top
} }
} }
/// Returns the bottom offset from margin edge to content edge. /// Returns the bottom offset from margin edge to content edge.
pub fn bottom_offset(&self) -> Au { pub fn bottom_offset(&self) -> Au {
match self.specific { match self.specific {
TableWrapperBox => self.margin.get().bottom, TableWrapperBox => self.margin.borrow().bottom,
TableBox | TableCellBox => self.border.get().bottom + self.padding.get().bottom, TableBox | TableCellBox => self.border.borrow().bottom + self.padding.borrow().bottom,
TableRowBox => self.border.get().bottom, TableRowBox => self.border.borrow().bottom,
TableColumnBox(_) => Au(0), TableColumnBox(_) => Au(0),
_ => self.margin.get().bottom + self.border.get().bottom + self.padding.get().bottom _ => self.margin.borrow().bottom + self.border.borrow().bottom + self.padding.borrow().bottom
} }
} }
@ -895,8 +894,8 @@ impl Box {
// TODO (ksh8281) compute vertical-align, line-height // TODO (ksh8281) compute vertical-align, line-height
bg_rect.origin.y = box_info.baseline + offset.y - info.font_ascent; bg_rect.origin.y = box_info.baseline + offset.y - info.font_ascent;
bg_rect.size.height = info.font_ascent + info.font_descent; bg_rect.size.height = info.font_ascent + info.font_descent;
let background_color = info.style.get().resolve_color( let background_color = info.style.resolve_color(
info.style.get().Background.get().background_color); info.style.Background.get().background_color);
if !background_color.alpha.approx_eq(&0.0) { if !background_color.alpha.approx_eq(&0.0) {
let solid_color_display_item = ~SolidColorDisplayItem { let solid_color_display_item = ~SolidColorDisplayItem {
@ -920,7 +919,7 @@ impl Box {
bg_rect.origin.y = bg_rect.origin.y - border.top; bg_rect.origin.y = bg_rect.origin.y - border.top;
bg_rect.size.height = bg_rect.size.height + border.top + border.bottom; bg_rect.size.height = bg_rect.size.height + border.top + border.bottom;
let style = info.style.get(); let style = &info.style;
let top_color = style.resolve_color(style.Border.get().border_top_color); let top_color = style.resolve_color(style.Border.get().border_top_color);
let right_color = style.resolve_color(style.Border.get().border_right_color); let right_color = style.resolve_color(style.Border.get().border_right_color);
let bottom_color = style.resolve_color(style.Border.get().border_bottom_color); let bottom_color = style.resolve_color(style.Border.get().border_bottom_color);
@ -1025,14 +1024,14 @@ impl Box {
// Adjust sizes for `background-repeat`. // Adjust sizes for `background-repeat`.
match style.Background.get().background_repeat { match style.Background.get().background_repeat {
background_repeat::no_repeat => { background_repeat::no_repeat => {
bounds.size.width = Au::from_px(image.get().width as int); bounds.size.width = Au::from_px(image.width as int);
bounds.size.height = Au::from_px(image.get().height as int) bounds.size.height = Au::from_px(image.height as int)
} }
background_repeat::repeat_x => { background_repeat::repeat_x => {
bounds.size.height = Au::from_px(image.get().height as int) bounds.size.height = Au::from_px(image.height as int)
} }
background_repeat::repeat_y => { background_repeat::repeat_y => {
bounds.size.width = Au::from_px(image.get().width as int) bounds.size.width = Au::from_px(image.width as int)
} }
background_repeat::repeat => {} background_repeat::repeat => {}
}; };
@ -1045,8 +1044,8 @@ impl Box {
node: self.node, node: self.node,
}, },
image: image.clone(), image: image.clone(),
stretch_size: Size2D(Au::from_px(image.get().width as int), stretch_size: Size2D(Au::from_px(image.width as int),
Au::from_px(image.get().height as int)), Au::from_px(image.height as int)),
}); });
match clip_display_item { match clip_display_item {
@ -1073,7 +1072,7 @@ impl Box {
/// necessary. /// necessary.
pub fn paint_borders_if_applicable(&self, list: &mut DisplayList, abs_bounds: &Rect<Au>) { pub fn paint_borders_if_applicable(&self, list: &mut DisplayList, abs_bounds: &Rect<Au>) {
// Fast path. // Fast path.
let border = self.border.get(); let border = self.border.borrow();
if border.is_zero() { if border.is_zero() {
return return
} }
@ -1099,7 +1098,7 @@ impl Box {
bounds: abs_bounds, bounds: abs_bounds,
node: self.node, node: self.node,
}, },
border: border, border: *border,
color: SideOffsets2D::new(top_color.to_gfx_color(), color: SideOffsets2D::new(top_color.to_gfx_color(),
right_color.to_gfx_color(), right_color.to_gfx_color(),
bottom_color.to_gfx_color(), bottom_color.to_gfx_color(),
@ -1117,7 +1116,7 @@ impl Box {
stacking_context: &mut StackingContext, stacking_context: &mut StackingContext,
flow_origin: Point2D<Au>, flow_origin: Point2D<Au>,
text_box: &ScannedTextBoxInfo) { text_box: &ScannedTextBoxInfo) {
let box_bounds = self.border_box.get(); let box_bounds = self.border_box.borrow();
let absolute_box_bounds = box_bounds.translate(&flow_origin); let absolute_box_bounds = box_bounds.translate(&flow_origin);
// Compute the text box bounds and draw a border surrounding them. // Compute the text box bounds and draw a border surrounding them.
@ -1136,7 +1135,7 @@ impl Box {
stacking_context.content.push(BorderDisplayItemClass(border_display_item)); stacking_context.content.push(BorderDisplayItemClass(border_display_item));
// Draw a rectangle representing the baselines. // Draw a rectangle representing the baselines.
let ascent = text_box.run.get().metrics_for_range(&text_box.range).ascent; let ascent = text_box.run.metrics_for_range(&text_box.range).ascent;
let baseline = Rect(absolute_box_bounds.origin + Point2D(Au(0), ascent), let baseline = Rect(absolute_box_bounds.origin + Point2D(Au(0), ascent),
Size2D(absolute_box_bounds.size.width, Au(0))); Size2D(absolute_box_bounds.size.width, Au(0)));
@ -1155,7 +1154,7 @@ impl Box {
fn build_debug_borders_around_box(&self, fn build_debug_borders_around_box(&self,
stacking_context: &mut StackingContext, stacking_context: &mut StackingContext,
flow_origin: Point2D<Au>) { flow_origin: Point2D<Au>) {
let box_bounds = self.border_box.get(); let box_bounds = self.border_box.borrow();
let absolute_box_bounds = box_bounds.translate(&flow_origin); let absolute_box_bounds = box_bounds.translate(&flow_origin);
// This prints a debug border around the border of this box. // This prints a debug border around the border of this box.
@ -1192,7 +1191,7 @@ impl Box {
flow: &Flow, flow: &Flow,
background_and_border_level: BackgroundAndBorderLevel) { background_and_border_level: BackgroundAndBorderLevel) {
// Box position wrt to the owning flow. // Box position wrt to the owning flow.
let box_bounds = self.border_box.get(); let box_bounds = *self.border_box.borrow();
let absolute_box_bounds = box_bounds.translate(&flow_origin); let absolute_box_bounds = box_bounds.translate(&flow_origin);
debug!("Box::build_display_list at rel={}, abs={}: {:s}", debug!("Box::build_display_list at rel={}, abs={}: {:s}",
box_bounds, box_bounds,
@ -1244,7 +1243,7 @@ impl Box {
match &*inline_info { match &*inline_info {
&Some(ref info) => { &Some(ref info) => {
for data in info.parent_info.as_slice().rev_iter() { for data in info.parent_info.as_slice().rev_iter() {
let parent_info = FlowFlagsInfo::new(data.style.get()); let parent_info = FlowFlagsInfo::new(&*data.style);
flow_flags.propagate_text_decoration_from_parent(&parent_info); flow_flags.propagate_text_decoration_from_parent(&parent_info);
} }
}, },
@ -1374,11 +1373,11 @@ impl Box {
} }
ScannedTextBox(ref text_box_info) => { ScannedTextBox(ref text_box_info) => {
let range = &text_box_info.range; let range = &text_box_info.range;
let min_line_width = text_box_info.run.get().min_width_for_range(range); let min_line_width = text_box_info.run.min_width_for_range(range);
let mut max_line_width = Au::new(0); let mut max_line_width = Au::new(0);
for line_range in text_box_info.run.get().iter_natural_lines_for_range(range) { for line_range in text_box_info.run.iter_natural_lines_for_range(range) {
let line_metrics = text_box_info.run.get().metrics_for_range(&line_range); let line_metrics = text_box_info.run.metrics_for_range(&line_range);
max_line_width = Au::max(max_line_width, line_metrics.advance_width); max_line_width = Au::max(max_line_width, line_metrics.advance_width);
} }
@ -1389,8 +1388,7 @@ impl Box {
} }
// Take borders and padding for parent inline boxes into account. // Take borders and padding for parent inline boxes into account.
let inline_info = self.inline_info.get(); match *self.inline_info.borrow() {
match inline_info {
None => {} None => {}
Some(ref inline_info) => { Some(ref inline_info) => {
for inline_parent_info in inline_info.parent_info.iter() { for inline_parent_info in inline_info.parent_info.iter() {
@ -1418,7 +1416,7 @@ impl Box {
} }
ScannedTextBox(ref text_box_info) => { ScannedTextBox(ref text_box_info) => {
let (range, run) = (&text_box_info.range, &text_box_info.run); let (range, run) = (&text_box_info.range, &text_box_info.run);
let text_bounds = run.get().metrics_for_range(range).bounding_box; let text_bounds = run.metrics_for_range(range).bounding_box;
text_bounds.size.width text_bounds.size.width
} }
TableColumnBox(_) => fail!("Table column boxes do not have width"), TableColumnBox(_) => fail!("Table column boxes do not have width"),
@ -1437,7 +1435,7 @@ impl Box {
ScannedTextBox(ref text_box_info) => { ScannedTextBox(ref text_box_info) => {
// Compute the height based on the line-height and font size. // Compute the height based on the line-height and font size.
let (range, run) = (&text_box_info.range, &text_box_info.run); let (range, run) = (&text_box_info.range, &text_box_info.run);
let text_bounds = run.get().metrics_for_range(range).bounding_box; let text_bounds = run.metrics_for_range(range).bounding_box;
let em_size = text_bounds.size.height; let em_size = text_bounds.size.height;
self.calculate_line_height(em_size) self.calculate_line_height(em_size)
} }
@ -1448,7 +1446,7 @@ impl Box {
/// Return the size of the content box. /// Return the size of the content box.
pub fn content_box_size(&self) -> Size2D<Au> { pub fn content_box_size(&self) -> Size2D<Au> {
let border_box_size = self.border_box.get().size; let border_box_size = self.border_box.borrow().size;
Size2D(border_box_size.width - self.noncontent_width(), Size2D(border_box_size.width - self.noncontent_width(),
border_box_size.height - self.noncontent_height()) border_box_size.height - self.noncontent_height())
} }
@ -1470,7 +1468,7 @@ impl Box {
// Left box is for left text of first founded new-line character. // Left box is for left text of first founded new-line character.
let left_box = { let left_box = {
let new_text_box_info = ScannedTextBoxInfo::new(text_box_info.run.clone(), left_range); let new_text_box_info = ScannedTextBoxInfo::new(text_box_info.run.clone(), left_range);
let new_metrics = new_text_box_info.run.get().metrics_for_range(&left_range); let new_metrics = new_text_box_info.run.metrics_for_range(&left_range);
let mut new_box = self.transform(new_metrics.bounding_box.size, ScannedTextBox(new_text_box_info)); let mut new_box = self.transform(new_metrics.bounding_box.size, ScannedTextBox(new_text_box_info));
new_box.new_line_pos = ~[]; new_box.new_line_pos = ~[];
Some(new_box) Some(new_box)
@ -1479,7 +1477,7 @@ impl Box {
// Right box is for right text of first founded new-line character. // Right box is for right text of first founded new-line character.
let right_box = if right_range.length() > 0 { let right_box = if right_range.length() > 0 {
let new_text_box_info = ScannedTextBoxInfo::new(text_box_info.run.clone(), right_range); let new_text_box_info = ScannedTextBoxInfo::new(text_box_info.run.clone(), right_range);
let new_metrics = new_text_box_info.run.get().metrics_for_range(&right_range); let new_metrics = new_text_box_info.run.metrics_for_range(&right_range);
let mut new_box = self.transform(new_metrics.bounding_box.size, ScannedTextBox(new_text_box_info)); let mut new_box = self.transform(new_metrics.bounding_box.size, ScannedTextBox(new_text_box_info));
new_box.new_line_pos = new_line_pos; new_box.new_line_pos = new_line_pos;
Some(new_box) Some(new_box)
@ -1507,11 +1505,11 @@ impl Box {
debug!("split_to_width: splitting text box (strlen={:u}, range={}, \ debug!("split_to_width: splitting text box (strlen={:u}, range={}, \
avail_width={})", avail_width={})",
text_box_info.run.get().text.get().len(), text_box_info.run.text.len(),
text_box_info.range, text_box_info.range,
max_width); max_width);
for (glyphs, offset, slice_range) in text_box_info.run.get().iter_slices_for_range( for (glyphs, offset, slice_range) in text_box_info.run.iter_slices_for_range(
&text_box_info.range) { &text_box_info.range) {
debug!("split_to_width: considering slice (offset={}, range={}, \ debug!("split_to_width: considering slice (offset={}, range={}, \
remain_width={})", remain_width={})",
@ -1519,7 +1517,7 @@ impl Box {
slice_range, slice_range,
remaining_width); remaining_width);
let metrics = text_box_info.run.get().metrics_for_slice(glyphs, &slice_range); let metrics = text_box_info.run.metrics_for_slice(glyphs, &slice_range);
let advance = metrics.advance_width; let advance = metrics.advance_width;
let should_continue; let should_continue;
@ -1571,8 +1569,8 @@ impl Box {
let left_box = if left_range.length() > 0 { let left_box = if left_range.length() > 0 {
let new_text_box_info = ScannedTextBoxInfo::new(text_box_info.run.clone(), left_range); let new_text_box_info = ScannedTextBoxInfo::new(text_box_info.run.clone(), left_range);
let mut new_metrics = new_text_box_info.run.get().metrics_for_range(&left_range); let mut new_metrics = new_text_box_info.run.metrics_for_range(&left_range);
new_metrics.bounding_box.size.height = self.border_box.get().size.height; new_metrics.bounding_box.size.height = self.border_box.borrow().size.height;
Some(self.transform(new_metrics.bounding_box.size, Some(self.transform(new_metrics.bounding_box.size,
ScannedTextBox(new_text_box_info))) ScannedTextBox(new_text_box_info)))
} else { } else {
@ -1581,8 +1579,8 @@ impl Box {
let right_box = right_range.map_or(None, |range: Range| { let right_box = right_range.map_or(None, |range: Range| {
let new_text_box_info = ScannedTextBoxInfo::new(text_box_info.run.clone(), range); let new_text_box_info = ScannedTextBoxInfo::new(text_box_info.run.clone(), range);
let mut new_metrics = new_text_box_info.run.get().metrics_for_range(&range); let mut new_metrics = new_text_box_info.run.metrics_for_range(&range);
new_metrics.bounding_box.size.height = self.border_box.get().size.height; new_metrics.bounding_box.size.height = self.border_box.borrow().size.height;
Some(self.transform(new_metrics.bounding_box.size, Some(self.transform(new_metrics.bounding_box.size,
ScannedTextBox(new_text_box_info))) ScannedTextBox(new_text_box_info)))
}); });
@ -1647,7 +1645,7 @@ impl Box {
let mut position = self.border_box.borrow_mut(); let mut position = self.border_box.borrow_mut();
position.size.width = width + self.noncontent_width() + position.size.width = width + self.noncontent_width() +
self.noncontent_inline_left() + self.noncontent_inline_right(); self.noncontent_inline_left() + self.noncontent_inline_right();
image_box_info.computed_width.set(Some(width)); *image_box_info.computed_width.borrow_mut() = Some(width);
} }
ScannedTextBox(_) => { ScannedTextBox(_) => {
// Scanned text boxes will have already had their // Scanned text boxes will have already had their
@ -1694,7 +1692,7 @@ impl Box {
}; };
let mut position = self.border_box.borrow_mut(); let mut position = self.border_box.borrow_mut();
image_box_info.computed_height.set(Some(height)); *image_box_info.computed_height.borrow_mut() = Some(height);
position.size.height = height + self.noncontent_height() position.size.height = height + self.noncontent_height()
} }
ScannedTextBox(_) => { ScannedTextBox(_) => {
@ -1724,7 +1722,7 @@ impl Box {
/// Cleans up all the memory associated with this box. /// Cleans up all the memory associated with this box.
pub fn teardown(&self) { pub fn teardown(&self) {
match self.specific { match self.specific {
ScannedTextBox(ref text_box_info) => text_box_info.run.get().teardown(), ScannedTextBox(ref text_box_info) => text_box_info.run.teardown(),
_ => {} _ => {}
} }
} }
@ -1751,9 +1749,9 @@ impl Box {
format!("({}{}{}{})", format!("({}{}{}{})",
class_name, class_name,
self.side_offsets_debug_string("b", self.border.get()), self.side_offsets_debug_string("b", *self.border.borrow()),
self.side_offsets_debug_string("p", self.padding.get()), self.side_offsets_debug_string("p", *self.padding.borrow()),
self.side_offsets_debug_string("m", self.margin.get())) self.side_offsets_debug_string("m", *self.margin.borrow()))
} }
/// A helper function to return a debug string describing the side offsets for one of the rect /// A helper function to return a debug string describing the side offsets for one of the rect
@ -1778,12 +1776,12 @@ impl Box {
iframe_box: &IframeBoxInfo, iframe_box: &IframeBoxInfo,
offset: Point2D<Au>, offset: Point2D<Au>,
layout_context: &LayoutContext) { layout_context: &LayoutContext) {
let left = offset.x + self.margin.get().left + self.border.get().left + let left = offset.x + self.margin.borrow().left + self.border.borrow().left +
self.padding.get().left; self.padding.borrow().left;
let top = offset.y + self.margin.get().top + self.border.get().top + let top = offset.y + self.margin.borrow().top + self.border.borrow().top +
self.padding.get().top; self.padding.borrow().top;
let width = self.border_box.get().size.width - self.noncontent_width(); let width = self.border_box.borrow().size.width - self.noncontent_width();
let height = self.border_box.get().size.height - self.noncontent_height(); let height = self.border_box.borrow().size.height - self.noncontent_height();
let origin = Point2D(geometry::to_frac_px(left) as f32, geometry::to_frac_px(top) as f32); let origin = Point2D(geometry::to_frac_px(left) as f32, geometry::to_frac_px(top) as f32);
let size = Size2D(geometry::to_frac_px(width) as f32, geometry::to_frac_px(height) as f32); let size = Size2D(geometry::to_frac_px(width) as f32, geometry::to_frac_px(height) as f32);
let rect = Rect(origin, size); let rect = Rect(origin, size);

View file

@ -128,13 +128,13 @@ pub struct InlineBoxesConstructionResult {
/// Any {ib} splits that we're bubbling up. /// Any {ib} splits that we're bubbling up.
/// ///
/// TODO(pcwalton): Small vector optimization. /// TODO(pcwalton): Small vector optimization.
splits: Option<~[InlineBlockSplit]>, pub splits: Option<~[InlineBlockSplit]>,
/// Any boxes that succeed the {ib} splits. /// Any boxes that succeed the {ib} splits.
boxes: ~[Box], pub boxes: ~[Box],
/// Any absolute descendants that we're bubbling up. /// Any absolute descendants that we're bubbling up.
abs_descendants: AbsDescendants, pub abs_descendants: AbsDescendants,
} }
/// Represents an {ib} split that has not yet found the containing block that it belongs to. This /// Represents an {ib} split that has not yet found the containing block that it belongs to. This
@ -163,10 +163,10 @@ pub struct InlineBlockSplit {
/// The inline boxes that precede the flow. /// The inline boxes that precede the flow.
/// ///
/// TODO(pcwalton): Small vector optimization. /// TODO(pcwalton): Small vector optimization.
predecessor_boxes: ~[Box], pub predecessor_boxes: ~[Box],
/// The flow that caused this {ib} split. /// The flow that caused this {ib} split.
flow: ~Flow, pub flow: ~Flow,
} }
impl InlineBlockSplit { impl InlineBlockSplit {
@ -241,14 +241,14 @@ impl<T> OptVector<T> for Option<~[T]> {
/// An object that knows how to create flows. /// An object that knows how to create flows.
pub struct FlowConstructor<'a> { pub struct FlowConstructor<'a> {
/// The layout context. /// The layout context.
layout_context: &'a mut LayoutContext, pub layout_context: &'a mut LayoutContext,
/// An optional font context. If this is `None`, then we fetch the font context from the /// An optional font context. If this is `None`, then we fetch the font context from the
/// layout context. /// layout context.
/// ///
/// FIXME(pcwalton): This is pretty bogus and is basically just a workaround for libgreen /// FIXME(pcwalton): This is pretty bogus and is basically just a workaround for libgreen
/// having slow TLS. /// having slow TLS.
font_context: Option<~FontContext>, pub font_context: Option<~FontContext>,
} }
impl<'a> FlowConstructor<'a> { impl<'a> FlowConstructor<'a> {
@ -705,8 +705,8 @@ impl<'a> FlowConstructor<'a> {
*info = Some(InlineInfo::new()); *info = Some(InlineInfo::new());
} }
let mut border = parent_box.border.get(); let mut border = *parent_box.border.borrow();
let mut padding = parent_box.padding.get(); let mut padding = *parent_box.padding.borrow();
if i != 0 { if i != 0 {
border.left = Zero::zero(); border.left = Zero::zero();
padding.left = Zero::zero() padding.left = Zero::zero()
@ -957,11 +957,11 @@ impl<'a> PostorderNodeMutTraversal for FlowConstructor<'a> {
let (display, float, positioning) = match node.type_id() { let (display, float, positioning) = match node.type_id() {
None => { None => {
// Pseudo-element. // Pseudo-element.
let style = node.style().get(); let style = node.style();
(display::inline, style.Box.get().float, style.Box.get().position) (display::inline, style.Box.get().float, style.Box.get().position)
} }
Some(ElementNodeTypeId(_)) => { Some(ElementNodeTypeId(_)) => {
let style = node.style().get(); let style = node.style();
(style.Box.get().display, style.Box.get().float, style.Box.get().position) (style.Box.get().display, style.Box.get().float, style.Box.get().position)
} }
Some(TextNodeTypeId) => (display::inline, float::none, position::static_), Some(TextNodeTypeId) => (display::inline, float::none, position::static_),
@ -1112,7 +1112,7 @@ impl<'ln> NodeUtils for ThreadSafeLayoutNode<'ln> {
// //
// If you implement other values for this property, you will almost certainly // If you implement other values for this property, you will almost certainly
// want to update this check. // want to update this check.
match self.style().get().InheritedText.get().white_space { match self.style().InheritedText.get().white_space {
white_space::normal => true, white_space::normal => true,
_ => false, _ => false,
} }

View file

@ -13,20 +13,17 @@ use gfx::font_context::{FontContext, FontContextInfo};
use green::task::GreenTask; use green::task::GreenTask;
use script::layout_interface::LayoutChan; use script::layout_interface::LayoutChan;
use servo_msg::constellation_msg::ConstellationChan; use servo_msg::constellation_msg::ConstellationChan;
use servo_net::local_image_cache::LocalImageCache;
use servo_util::geometry::Au; use servo_util::geometry::Au;
use servo_util::opts::Opts; use servo_util::opts::Opts;
use std::cast; use std::cast;
#[cfg(not(target_os="android"))] #[cfg(not(target_os="android"))]
use std::ptr; use std::ptr;
#[cfg(not(target_os="android"))] #[cfg(not(target_os="android"))]
use std::rt::Runtime;
#[cfg(not(target_os="android"))]
use std::rt::local::Local; use std::rt::local::Local;
#[cfg(not(target_os="android"))] #[cfg(not(target_os="android"))]
use std::rt::task::Task; use std::rt::task::Task;
use style::{ComputedValues, Stylist}; use style::{ComputedValues, Stylist};
use sync::{Arc, MutexArc}; use sync::{Arc, Mutex};
use url::Url; use url::Url;
#[cfg(target_os="android")] #[cfg(target_os="android")]
@ -59,36 +56,37 @@ local_data_key!(style_sharing_candidate_cache: *mut StyleSharingCandidateCache)
#[deriving(Clone)] #[deriving(Clone)]
pub struct LayoutContext { pub struct LayoutContext {
/// The local image cache. /// The local image cache.
image_cache: MutexArc<LocalImageCache>, // FIXME(rust#13125): Remove the *() for the real type.
pub image_cache: Arc<Mutex<*()>>,
/// The current screen size. /// The current screen size.
screen_size: Size2D<Au>, pub screen_size: Size2D<Au>,
/// A channel up to the constellation. /// A channel up to the constellation.
constellation_chan: ConstellationChan, pub constellation_chan: ConstellationChan,
/// A channel up to the layout task. /// A channel up to the layout task.
layout_chan: LayoutChan, pub layout_chan: LayoutChan,
/// Information needed to construct a font context. /// Information needed to construct a font context.
font_context_info: FontContextInfo, pub font_context_info: FontContextInfo,
/// The CSS selector stylist. /// The CSS selector stylist.
/// ///
/// FIXME(pcwalton): Make this no longer an unsafe pointer once we have fast `RWArc`s. /// FIXME(pcwalton): Make this no longer an unsafe pointer once we have fast `RWArc`s.
stylist: *Stylist, pub stylist: *Stylist,
/// The initial set of CSS properties. /// The initial set of CSS properties.
initial_css_values: Arc<ComputedValues>, pub initial_css_values: Arc<ComputedValues>,
/// The root node at which we're starting the layout. /// The root node at which we're starting the layout.
reflow_root: OpaqueNode, pub reflow_root: OpaqueNode,
/// The URL. /// The URL.
url: Url, pub url: Url,
/// The command line options. /// The command line options.
opts: Opts, pub opts: Opts,
} }
#[cfg(not(target_os="android"))] #[cfg(not(target_os="android"))]
@ -99,7 +97,7 @@ impl LayoutContext {
let mut task = Local::borrow(None::<Task>); let mut task = Local::borrow(None::<Task>);
match task.get().maybe_take_runtime::<GreenTask>() { match task.get().maybe_take_runtime::<GreenTask>() {
Some(green) => { Some(green) => {
task.get().put_runtime(green as ~Runtime); task.get().put_runtime(green);
fail!("can't call this on a green task!") fail!("can't call this on a green task!")
} }
None => {} None => {}
@ -121,7 +119,7 @@ impl LayoutContext {
let mut task = Local::borrow(None::<Task>); let mut task = Local::borrow(None::<Task>);
match task.get().maybe_take_runtime::<GreenTask>() { match task.get().maybe_take_runtime::<GreenTask>() {
Some(green) => { Some(green) => {
task.get().put_runtime(green as ~Runtime); task.get().put_runtime(green);
fail!("can't call this on a green task!") fail!("can't call this on a green task!")
} }
None => {} None => {}
@ -143,7 +141,7 @@ impl LayoutContext {
let mut task = Local::borrow(None::<Task>); let mut task = Local::borrow(None::<Task>);
match task.get().maybe_take_runtime::<GreenTask>() { match task.get().maybe_take_runtime::<GreenTask>() {
Some(green) => { Some(green) => {
task.get().put_runtime(green as ~Runtime); task.get().put_runtime(green);
fail!("can't call this on a green task!") fail!("can't call this on a green task!")
} }
None => {} None => {}

View file

@ -15,23 +15,23 @@ use style;
/// Manages the information needed to construct the display list. /// Manages the information needed to construct the display list.
pub struct DisplayListBuilder<'a> { pub struct DisplayListBuilder<'a> {
ctx: &'a LayoutContext, pub ctx: &'a LayoutContext,
/// A list of render layers that we've built up, root layer not included. /// A list of render layers that we've built up, root layer not included.
layers: SmallVec0<RenderLayer>, pub layers: SmallVec0<RenderLayer>,
/// The dirty rect. /// The dirty rect.
dirty: Rect<Au>, pub dirty: Rect<Au>,
} }
/// Information needed at each step of the display list building traversal. /// Information needed at each step of the display list building traversal.
pub struct DisplayListBuildingInfo { pub struct DisplayListBuildingInfo {
/// The size of the containing block for relatively-positioned descendants. /// The size of the containing block for relatively-positioned descendants.
relative_containing_block_size: Size2D<Au>, pub relative_containing_block_size: Size2D<Au>,
/// The position and size of the absolute containing block. /// The position and size of the absolute containing block.
absolute_containing_block_position: Point2D<Au>, pub absolute_containing_block_position: Point2D<Au>,
/// Whether the absolute containing block forces positioned descendants to be layerized. /// Whether the absolute containing block forces positioned descendants to be layerized.
layers_needed_for_positioned_flows: bool, pub layers_needed_for_positioned_flows: bool,
} }
// //

View file

@ -105,13 +105,13 @@ impl FloatListRef {
/// All the information necessary to place a float. /// All the information necessary to place a float.
pub struct PlacementInfo { pub struct PlacementInfo {
/// The dimensions of the float. /// The dimensions of the float.
size: Size2D<Au>, pub size: Size2D<Au>,
/// The minimum top of the float, as determined by earlier elements. /// The minimum top of the float, as determined by earlier elements.
ceiling: Au, pub ceiling: Au,
/// The maximum right position of the float, generally determined by the containing block. /// The maximum right position of the float, generally determined by the containing block.
max_width: Au, pub max_width: Au,
/// The kind of float. /// The kind of float.
kind: FloatKind pub kind: FloatKind
} }
fn range_intersect(top_1: Au, bottom_1: Au, top_2: Au, bottom_2: Au) -> (Au, Au) { fn range_intersect(top_1: Au, bottom_1: Au, top_2: Au, bottom_2: Au) -> (Au, Au) {
@ -123,9 +123,9 @@ fn range_intersect(top_1: Au, bottom_1: Au, top_2: Au, bottom_2: Au) -> (Au, Au)
#[deriving(Clone)] #[deriving(Clone)]
pub struct Floats { pub struct Floats {
/// The list of floats. /// The list of floats.
priv list: FloatListRef, list: FloatListRef,
/// The offset of the flow relative to the first float. /// The offset of the flow relative to the first float.
priv offset: Point2D<Au>, offset: Point2D<Au>,
} }
impl Floats { impl Floats {

View file

@ -441,22 +441,22 @@ pub trait PostorderFlowTraversal {
#[deriving(Clone)] #[deriving(Clone)]
pub struct FlowFlagsInfo { pub struct FlowFlagsInfo {
flags: FlowFlags, pub flags: FlowFlags,
/// text-decoration colors /// text-decoration colors
rare_flow_flags: Option<~RareFlowFlags>, pub rare_flow_flags: Option<~RareFlowFlags>,
} }
#[deriving(Clone)] #[deriving(Clone)]
pub struct RareFlowFlags { pub struct RareFlowFlags {
underline_color: Color, pub underline_color: Color,
overline_color: Color, pub overline_color: Color,
line_through_color: Color, pub line_through_color: Color,
} }
/// Flags used in flows, tightly packed to save space. /// Flags used in flows, tightly packed to save space.
#[deriving(Clone)] #[deriving(Clone)]
pub struct FlowFlags(u8); pub struct FlowFlags(pub u8);
/// The bitmask of flags that represent text decoration fields that get propagated downward. /// The bitmask of flags that represent text decoration fields that get propagated downward.
/// ///
@ -674,9 +674,9 @@ impl FlowFlags {
/// FIXME: This should use @pcwalton's reference counting scheme (Coming Soon). /// FIXME: This should use @pcwalton's reference counting scheme (Coming Soon).
pub struct Descendants { pub struct Descendants {
/// Links to every Descendant. /// Links to every Descendant.
descendant_links: SmallVec0<Rawlink>, pub descendant_links: SmallVec0<Rawlink>,
/// Static y offsets of all descendants from the start of this flow box. /// Static y offsets of all descendants from the start of this flow box.
static_y_offsets: SmallVec0<Au>, pub static_y_offsets: SmallVec0<Au>,
} }
impl Descendants { impl Descendants {
@ -724,17 +724,17 @@ pub type DescendantOffsetIter<'a> = Zip<MutItems<'a, Rawlink>, MutItems<'a, Au>>
/// Data common to all flows. /// Data common to all flows.
pub struct BaseFlow { pub struct BaseFlow {
restyle_damage: RestyleDamage, pub restyle_damage: RestyleDamage,
/// The children of this flow. /// The children of this flow.
children: FlowList, pub children: FlowList,
next_sibling: Link, pub next_sibling: Link,
prev_sibling: Rawlink, pub prev_sibling: Rawlink,
/* layout computations */ /* layout computations */
// TODO: min/pref and position are used during disjoint phases of // TODO: min/pref and position are used during disjoint phases of
// layout; maybe combine into a single enum to save space. // layout; maybe combine into a single enum to save space.
intrinsic_widths: IntrinsicWidths, pub intrinsic_widths: IntrinsicWidths,
/// The upper left corner of the box representing this flow, relative to the box representing /// The upper left corner of the box representing this flow, relative to the box representing
/// its parent flow. /// its parent flow.
@ -744,59 +744,60 @@ pub struct BaseFlow {
/// This does not include margins in the block flow direction, because those can collapse. So /// This does not include margins in the block flow direction, because those can collapse. So
/// for the block direction (usually vertical), this represents the *border box*. For the /// for the block direction (usually vertical), this represents the *border box*. For the
/// inline direction (usually horizontal), this represents the *margin box*. /// inline direction (usually horizontal), this represents the *margin box*.
position: Rect<Au>, pub position: Rect<Au>,
/// The amount of overflow of this flow, relative to the containing block. Must include all the /// The amount of overflow of this flow, relative to the containing block. Must include all the
/// pixels of all the display list items for correct invalidation. /// pixels of all the display list items for correct invalidation.
overflow: Rect<Au>, pub overflow: Rect<Au>,
/// Data used during parallel traversals. /// Data used during parallel traversals.
/// ///
/// TODO(pcwalton): Group with other transient data to save space. /// TODO(pcwalton): Group with other transient data to save space.
parallel: FlowParallelInfo, pub parallel: FlowParallelInfo,
/// The floats next to this flow. /// The floats next to this flow.
floats: Floats, pub floats: Floats,
/// The value of this flow's `clear` property, if any. /// The value of this flow's `clear` property, if any.
clear: clear::T, pub clear: clear::T,
/// For normal flows, this is the number of floated descendants that are /// For normal flows, this is the number of floated descendants that are
/// not contained within any other floated descendant of this flow. For /// not contained within any other floated descendant of this flow. For
/// floats, it is 1. /// floats, it is 1.
/// It is used to allocate float data if necessary and to /// It is used to allocate float data if necessary and to
/// decide whether to do an in-order traversal for assign_height. /// decide whether to do an in-order traversal for assign_height.
num_floats: uint, pub num_floats: uint,
/// The collapsible margins for this flow, if any. /// The collapsible margins for this flow, if any.
collapsible_margins: CollapsibleMargins, pub collapsible_margins: CollapsibleMargins,
/// The position of this flow in page coordinates, computed during display list construction. /// The position of this flow in page coordinates, computed during display list construction.
abs_position: Point2D<Au>, pub abs_position: Point2D<Au>,
/// Details about descendants with position 'absolute' or 'fixed' for which we are the /// Details about descendants with position 'absolute' or 'fixed' for which we are the
/// containing block. This is in tree order. This includes any direct children. /// containing block. This is in tree order. This includes any direct children.
abs_descendants: AbsDescendants, pub abs_descendants: AbsDescendants,
/// Offset wrt the nearest positioned ancestor - aka the Containing Block /// Offset wrt the nearest positioned ancestor - aka the Containing Block
/// for any absolutely positioned elements. /// for any absolutely positioned elements.
absolute_static_x_offset: Au, pub absolute_static_x_offset: Au,
/// Offset wrt the Initial Containing Block. /// Offset wrt the Initial Containing Block.
fixed_static_x_offset: Au, pub fixed_static_x_offset: Au,
/// Reference to the Containing Block, if this flow is absolutely positioned. /// Reference to the Containing Block, if this flow is absolutely positioned.
absolute_cb: Rawlink, pub absolute_cb: Rawlink,
/// Whether this flow has been destroyed. /// Whether this flow has been destroyed.
/// ///
/// TODO(pcwalton): Pack this into the flags? Need to be careful because manipulation of this /// TODO(pcwalton): Pack this into the flags? Need to be careful because manipulation of this
/// flag can have memory safety implications. /// flag can have memory safety implications.
priv destroyed: bool, destroyed: bool,
/// Various flags for flows and some info /// Various flags for flows and some info
flags_info: FlowFlagsInfo, pub flags_info: FlowFlagsInfo,
} }
#[unsafe_destructor]
impl Drop for BaseFlow { impl Drop for BaseFlow {
fn drop(&mut self) { fn drop(&mut self) {
if !self.destroyed { if !self.destroyed {
@ -834,7 +835,7 @@ impl BaseFlow {
destroyed: false, destroyed: false,
flags_info: FlowFlagsInfo::new(style.get()), flags_info: FlowFlagsInfo::new(&**style),
} }
} }

View file

@ -15,8 +15,8 @@ pub type Link = Option<~Flow>;
#[deriving(Clone)] #[deriving(Clone)]
pub struct Rawlink { pub struct Rawlink {
priv vtable: *(), vtable: *(),
priv obj: *mut (), obj: *mut (),
} }
/// Doubly-linked list of Flows. /// Doubly-linked list of Flows.
@ -24,24 +24,24 @@ pub struct Rawlink {
/// The forward links are strong references. /// The forward links are strong references.
/// The backward links are weak references. /// The backward links are weak references.
pub struct FlowList { pub struct FlowList {
priv length: uint, length: uint,
priv list_head: Link, list_head: Link,
priv list_tail: Rawlink, list_tail: Rawlink,
} }
/// Double-ended FlowList iterator /// Double-ended FlowList iterator
pub struct FlowListIterator<'a> { pub struct FlowListIterator<'a> {
priv head: &'a Link, head: &'a Link,
priv tail: Rawlink, tail: Rawlink,
priv nelem: uint, nelem: uint,
} }
/// Double-ended mutable FlowList iterator /// Double-ended mutable FlowList iterator
pub struct MutFlowListIterator<'a> { pub struct MutFlowListIterator<'a> {
priv list: &'a mut FlowList, list: &'a mut FlowList,
priv head: Rawlink, head: Rawlink,
priv tail: Rawlink, tail: Rawlink,
priv nelem: uint, nelem: uint,
} }
impl Rawlink { impl Rawlink {

View file

@ -28,7 +28,7 @@ pub enum RestyleEffect {
// FIXME: Switch to librustc/util/enum_set.rs if that gets moved into // FIXME: Switch to librustc/util/enum_set.rs if that gets moved into
// libextra (Rust #8054) // libextra (Rust #8054)
pub struct RestyleDamage { pub struct RestyleDamage {
priv bits: int bits: int
} }
// Provide literal syntax of the form restyle_damage!(Repaint, Reflow) // Provide literal syntax of the form restyle_damage!(Repaint, Reflow)

View file

@ -51,18 +51,18 @@ use style::computed_values::{text_align, vertical_align, white_space};
/// left corner of the green zone is the same as that of the line, but /// left corner of the green zone is the same as that of the line, but
/// the green zone can be taller and wider than the line itself. /// the green zone can be taller and wider than the line itself.
pub struct LineBox { pub struct LineBox {
range: Range, pub range: Range,
bounds: Rect<Au>, pub bounds: Rect<Au>,
green_zone: Size2D<Au> pub green_zone: Size2D<Au>
} }
struct LineboxScanner { struct LineboxScanner {
floats: Floats, pub floats: Floats,
new_boxes: ~[Box], pub new_boxes: ~[Box],
work_list: RingBuf<Box>, pub work_list: RingBuf<Box>,
pending_line: LineBox, pub pending_line: LineBox,
lines: ~[LineBox], pub lines: ~[LineBox],
cur_y: Au, pub cur_y: Au,
} }
impl LineboxScanner { impl LineboxScanner {
@ -179,7 +179,7 @@ impl LineboxScanner {
-> (Rect<Au>, Au) { -> (Rect<Au>, Au) {
debug!("LineboxScanner: Trying to place first box of line {}", self.lines.len()); debug!("LineboxScanner: Trying to place first box of line {}", self.lines.len());
let first_box_size = first_box.border_box.get().size; let first_box_size = first_box.border_box.borrow().size;
let splittable = first_box.can_split(); let splittable = first_box.can_split();
debug!("LineboxScanner: box size: {}, splittable: {}", first_box_size, splittable); debug!("LineboxScanner: box size: {}, splittable: {}", first_box_size, splittable);
let line_is_empty: bool = self.pending_line.range.length() == 0; let line_is_empty: bool = self.pending_line.range.length() == 0;
@ -233,9 +233,9 @@ impl LineboxScanner {
debug!("LineboxScanner: case=box split and fit"); debug!("LineboxScanner: case=box split and fit");
let actual_box_width = match (left, right) { let actual_box_width = match (left, right) {
(Some(l_box), Some(_)) => l_box.border_box.get().size.width, (Some(l_box), Some(_)) => l_box.border_box.borrow().size.width,
(Some(l_box), None) => l_box.border_box.get().size.width, (Some(l_box), None) => l_box.border_box.borrow().size.width,
(None, Some(r_box)) => r_box.border_box.get().size.width, (None, Some(r_box)) => r_box.border_box.borrow().size.width,
(None, None) => fail!("This case makes no sense.") (None, None) => fail!("This case makes no sense.")
}; };
return (line_bounds, actual_box_width); return (line_bounds, actual_box_width);
@ -247,9 +247,9 @@ impl LineboxScanner {
debug!("LineboxScanner: case=box split and fit didn't fit; trying to push it down"); debug!("LineboxScanner: case=box split and fit didn't fit; trying to push it down");
let actual_box_width = match (left, right) { let actual_box_width = match (left, right) {
(Some(l_box), Some(_)) => l_box.border_box.get().size.width, (Some(l_box), Some(_)) => l_box.border_box.borrow().size.width,
(Some(l_box), None) => l_box.border_box.get().size.width, (Some(l_box), None) => l_box.border_box.borrow().size.width,
(None, Some(r_box)) => r_box.border_box.get().size.width, (None, Some(r_box)) => r_box.border_box.borrow().size.width,
(None, None) => fail!("This case makes no sense.") (None, None) => fail!("This case makes no sense.")
}; };
@ -348,7 +348,7 @@ impl LineboxScanner {
debug!("LineboxScanner: Trying to append box to line {:u} (box size: {}, green zone: \ debug!("LineboxScanner: Trying to append box to line {:u} (box size: {}, green zone: \
{}): {:s}", {}): {:s}",
self.lines.len(), self.lines.len(),
in_box.border_box.get().size, in_box.border_box.borrow().size,
self.pending_line.green_zone, self.pending_line.green_zone,
in_box.debug_str()); in_box.debug_str());
@ -368,7 +368,7 @@ impl LineboxScanner {
// horizontally. We'll try to place the whole box on this line and break somewhere if it // horizontally. We'll try to place the whole box on this line and break somewhere if it
// doesn't fit. // doesn't fit.
let new_width = self.pending_line.bounds.size.width + in_box.border_box.get().size.width; let new_width = self.pending_line.bounds.size.width + in_box.border_box.borrow().size.width;
if new_width <= green_zone.width { if new_width <= green_zone.width {
debug!("LineboxScanner: case=box fits without splitting"); debug!("LineboxScanner: case=box fits without splitting");
self.push_box_to_line(in_box); self.push_box_to_line(in_box);
@ -439,29 +439,29 @@ impl LineboxScanner {
} }
self.pending_line.range.extend_by(1); self.pending_line.range.extend_by(1);
self.pending_line.bounds.size.width = self.pending_line.bounds.size.width + self.pending_line.bounds.size.width = self.pending_line.bounds.size.width +
box_.border_box.get().size.width; box_.border_box.borrow().size.width;
self.pending_line.bounds.size.height = Au::max(self.pending_line.bounds.size.height, self.pending_line.bounds.size.height = Au::max(self.pending_line.bounds.size.height,
box_.border_box.get().size.height); box_.border_box.borrow().size.height);
self.new_boxes.push(box_); self.new_boxes.push(box_);
} }
} }
pub struct InlineFlow { pub struct InlineFlow {
/// Data common to all flows. /// Data common to all flows.
base: BaseFlow, pub base: BaseFlow,
/// A vector of all inline render boxes. Several boxes may correspond to one node/element. /// A vector of all inline render boxes. Several boxes may correspond to one node/element.
boxes: ~[Box], pub boxes: ~[Box],
// vec of ranges into boxes that represents line positions. // vec of ranges into boxes that represents line positions.
// these ranges are disjoint, and are the result of inline layout. // these ranges are disjoint, and are the result of inline layout.
// also some metadata used for positioning lines // also some metadata used for positioning lines
lines: ~[LineBox], pub lines: ~[LineBox],
// vec of ranges into boxes that represent elements. These ranges // vec of ranges into boxes that represent elements. These ranges
// must be well-nested, and are only related to the content of // must be well-nested, and are only related to the content of
// boxes (not lines). Ranges are only kept for non-leaf elements. // boxes (not lines). Ranges are only kept for non-leaf elements.
elems: ElementMapping, pub elems: ElementMapping,
} }
impl InlineFlow { impl InlineFlow {
@ -600,8 +600,9 @@ impl InlineFlow {
for i in line.range.eachi() { for i in line.range.eachi() {
let box_ = &boxes[i]; let box_ = &boxes[i];
let size = box_.border_box.get().size; let mut border_box = box_.border_box.borrow_mut();
box_.border_box.set(Rect(Point2D(offset_x, box_.border_box.get().origin.y), size)); let size = border_box.size;
*border_box = Rect(Point2D(offset_x, border_box.origin.y), size);
offset_x = offset_x + size.width; offset_x = offset_x + size.width;
} }
} }
@ -749,23 +750,23 @@ impl Flow for InlineFlow {
let run = &text_box.run; let run = &text_box.run;
// Compute the height based on the line-height and font size // Compute the height based on the line-height and font size
let text_bounds = run.get().metrics_for_range(range).bounding_box; let text_bounds = run.metrics_for_range(range).bounding_box;
let em_size = text_bounds.size.height; let em_size = text_bounds.size.height;
let line_height = cur_box.calculate_line_height(em_size); let line_height = cur_box.calculate_line_height(em_size);
// Find the top and bottom of the content area. // Find the top and bottom of the content area.
// Those are used in text-top and text-bottom value of 'vertical-align' // Those are used in text-top and text-bottom value of 'vertical-align'
let text_ascent = text_box.run.get().font_metrics.ascent; let text_ascent = text_box.run.font_metrics.ascent;
// Offset from the top of the box is 1/2 of the leading + ascent // Offset from the top of the box is 1/2 of the leading + ascent
let text_offset = text_ascent + (line_height - em_size).scale_by(0.5); let text_offset = text_ascent + (line_height - em_size).scale_by(0.5);
text_bounds.translate(&Point2D(cur_box.border_box.get().origin.x, Au(0))); text_bounds.translate(&Point2D(cur_box.border_box.borrow().origin.x, Au(0)));
(text_offset, line_height - text_offset, text_ascent) (text_offset, line_height - text_offset, text_ascent)
}, },
GenericBox | IframeBox(_) | TableBox | TableCellBox | TableRowBox | GenericBox | IframeBox(_) | TableBox | TableCellBox | TableRowBox |
TableWrapperBox => { TableWrapperBox => {
let height = cur_box.border_box.get().size.height; let height = cur_box.border_box.borrow().size.height;
(height, Au::new(0), height) (height, Au::new(0), height)
}, },
TableColumnBox(_) => fail!("Table column boxes do not have height"), TableColumnBox(_) => fail!("Table column boxes do not have height"),
@ -850,8 +851,8 @@ impl Flow for InlineFlow {
_ => baseline_offset, _ => baseline_offset,
}; };
cur_box.border_box.borrow_mut().origin.y = cur_box.border_box.get().origin.y + let mut border_box = cur_box.border_box.borrow_mut();
adjust_offset; border_box.origin.y = border_box.origin.y + adjust_offset;
let mut info = cur_box.inline_info.borrow_mut(); let mut info = cur_box.inline_info.borrow_mut();
if info.is_none() { if info.is_none() {
@ -884,6 +885,8 @@ impl Flow for InlineFlow {
} }
fn debug_str(&self) -> ~str { fn debug_str(&self) -> ~str {
~"InlineFlow: " + self.boxes.map(|s| s.debug_str()).connect(", ") let val: ~[~str] = self.boxes.iter().map(|s| s.debug_str()).collect();
let toprint = val.connect(",");
format!("InlineFlow: {}", toprint)
} }
} }

View file

@ -60,53 +60,54 @@ use std::ptr;
use std::task; use std::task;
use style::{AuthorOrigin, ComputedValues, Stylesheet, Stylist}; use style::{AuthorOrigin, ComputedValues, Stylesheet, Stylist};
use style; use style;
use sync::{Arc, MutexArc}; use sync::{Arc, Mutex};
use url::Url; use url::Url;
/// Information needed by the layout task. /// Information needed by the layout task.
pub struct LayoutTask { pub struct LayoutTask {
/// The ID of the pipeline that we belong to. /// The ID of the pipeline that we belong to.
id: PipelineId, pub id: PipelineId,
/// The port on which we receive messages. /// The port on which we receive messages.
port: Receiver<Msg>, pub port: Receiver<Msg>,
//// The channel to send messages to ourself. //// The channel to send messages to ourself.
chan: LayoutChan, pub chan: LayoutChan,
/// The channel on which messages can be sent to the constellation. /// The channel on which messages can be sent to the constellation.
constellation_chan: ConstellationChan, pub constellation_chan: ConstellationChan,
/// The channel on which messages can be sent to the script task. /// The channel on which messages can be sent to the script task.
script_chan: ScriptChan, pub script_chan: ScriptChan,
/// The channel on which messages can be sent to the painting task. /// The channel on which messages can be sent to the painting task.
render_chan: RenderChan, pub render_chan: RenderChan,
/// The channel on which messages can be sent to the image cache. /// The channel on which messages can be sent to the image cache.
image_cache_task: ImageCacheTask, pub image_cache_task: ImageCacheTask,
/// The local image cache. /// The local image cache.
local_image_cache: MutexArc<LocalImageCache>, // FIXME(rust#13125): Remove the *() for the real type.
pub local_image_cache: Arc<Mutex<*()>>,
/// The size of the viewport. /// The size of the viewport.
screen_size: Size2D<Au>, pub screen_size: Size2D<Au>,
/// A cached display list. /// A cached display list.
display_list: Option<Arc<DisplayList>>, pub display_list: Option<Arc<DisplayList>>,
stylist: ~Stylist, pub stylist: ~Stylist,
/// The initial set of CSS values. /// The initial set of CSS values.
initial_css_values: Arc<ComputedValues>, pub initial_css_values: Arc<ComputedValues>,
/// The workers that we use for parallel operation. /// The workers that we use for parallel operation.
parallel_traversal: Option<WorkQueue<*mut LayoutContext,PaddedUnsafeFlow>>, pub parallel_traversal: Option<WorkQueue<*mut LayoutContext,PaddedUnsafeFlow>>,
/// The channel on which messages can be sent to the profiler. /// The channel on which messages can be sent to the profiler.
profiler_chan: ProfilerChan, pub profiler_chan: ProfilerChan,
opts: Opts pub opts: Opts
} }
/// The damage computation traversal. /// The damage computation traversal.
@ -171,7 +172,7 @@ impl PreorderFlowTraversal for FlowTreeVerificationTraversal {
/// The bubble-widths traversal, the first part of layout computation. This computes preferred /// The bubble-widths traversal, the first part of layout computation. This computes preferred
/// and intrinsic widths and bubbles them up the tree. /// and intrinsic widths and bubbles them up the tree.
pub struct BubbleWidthsTraversal<'a> { pub struct BubbleWidthsTraversal<'a> {
layout_context: &'a mut LayoutContext, pub layout_context: &'a mut LayoutContext,
} }
impl<'a> PostorderFlowTraversal for BubbleWidthsTraversal<'a> { impl<'a> PostorderFlowTraversal for BubbleWidthsTraversal<'a> {
@ -192,7 +193,7 @@ impl<'a> PostorderFlowTraversal for BubbleWidthsTraversal<'a> {
/// The assign-widths traversal. In Gecko this corresponds to `Reflow`. /// The assign-widths traversal. In Gecko this corresponds to `Reflow`.
pub struct AssignWidthsTraversal<'a> { pub struct AssignWidthsTraversal<'a> {
layout_context: &'a mut LayoutContext, pub layout_context: &'a mut LayoutContext,
} }
impl<'a> PreorderFlowTraversal for AssignWidthsTraversal<'a> { impl<'a> PreorderFlowTraversal for AssignWidthsTraversal<'a> {
@ -207,7 +208,7 @@ impl<'a> PreorderFlowTraversal for AssignWidthsTraversal<'a> {
/// computation. Determines the final heights for all layout objects, computes positions, and /// computation. Determines the final heights for all layout objects, computes positions, and
/// computes overflow regions. In Gecko this corresponds to `FinishAndStoreOverflow`. /// computes overflow regions. In Gecko this corresponds to `FinishAndStoreOverflow`.
pub struct AssignHeightsAndStoreOverflowTraversal<'a> { pub struct AssignHeightsAndStoreOverflowTraversal<'a> {
layout_context: &'a mut LayoutContext, pub layout_context: &'a mut LayoutContext,
} }
impl<'a> PostorderFlowTraversal for AssignHeightsAndStoreOverflowTraversal<'a> { impl<'a> PostorderFlowTraversal for AssignHeightsAndStoreOverflowTraversal<'a> {
@ -234,10 +235,10 @@ struct LayoutImageResponder {
} }
impl ImageResponder for LayoutImageResponder { impl ImageResponder for LayoutImageResponder {
fn respond(&self) -> proc(ImageResponseMsg) { fn respond(&self) -> proc(ImageResponseMsg):Send {
let id = self.id.clone(); let id = self.id.clone();
let script_chan = self.script_chan.clone(); let script_chan = self.script_chan.clone();
let f: proc(ImageResponseMsg) = proc(_) { let f: proc(ImageResponseMsg):Send = proc(_) {
let ScriptChan(chan) = script_chan; let ScriptChan(chan) = script_chan;
drop(chan.try_send(SendEventMsg(id.clone(), ReflowEvent))) drop(chan.try_send(SendEventMsg(id.clone(), ReflowEvent)))
}; };
@ -289,7 +290,10 @@ impl LayoutTask {
opts: &Opts, opts: &Opts,
profiler_chan: ProfilerChan) profiler_chan: ProfilerChan)
-> LayoutTask { -> LayoutTask {
let local_image_cache = MutexArc::new(LocalImageCache(image_cache_task.clone())); let local_image_cache = ~LocalImageCache(image_cache_task.clone());
let local_image_cache = Arc::new(Mutex::new(unsafe {
cast::transmute::<~LocalImageCache, *()>(local_image_cache)
}));
let screen_size = Size2D(Au(0), Au(0)); let screen_size = Size2D(Au(0), Au(0));
let parallel_traversal = if opts.layout_threads != 1 { let parallel_traversal = if opts.layout_threads != 1 {
Some(WorkQueue::new("LayoutWorker", opts.layout_threads, ptr::mut_null())) Some(WorkQueue::new("LayoutWorker", opts.layout_threads, ptr::mut_null()))
@ -539,10 +543,14 @@ impl LayoutTask {
debug!("layout: parsed Node tree"); debug!("layout: parsed Node tree");
debug!("{:?}", node.dump()); debug!("{:?}", node.dump());
// Reset the image cache. {
self.local_image_cache.access(|local_image_cache| { // Reset the image cache.
local_image_cache.next_round(self.make_on_image_available_cb()) let val = self.local_image_cache.lock();
}); let mut local_image_cache = unsafe {
cast::transmute::<*(), &mut LocalImageCache>(*val)
};
local_image_cache.next_round(self.make_on_image_available_cb());
}
// true => Do the reflow with full style damage, because content // true => Do the reflow with full style damage, because content
// changed or the window was resized. // changed or the window was resized.
@ -654,9 +662,7 @@ impl LayoutTask {
let element_bg_color = { let element_bg_color = {
let thread_safe_child = ThreadSafeLayoutNode::new(&child); let thread_safe_child = ThreadSafeLayoutNode::new(&child);
thread_safe_child.style() thread_safe_child.style()
.get()
.resolve_color(thread_safe_child.style() .resolve_color(thread_safe_child.style()
.get()
.Background .Background
.get() .get()
.background_color) .background_color)
@ -740,7 +746,7 @@ impl LayoutTask {
match self.display_list { match self.display_list {
None => fail!("no display list!"), None => fail!("no display list!"),
Some(ref display_list) => { Some(ref display_list) => {
union_boxes_for_node(&mut rect, display_list.get().iter(), node) union_boxes_for_node(&mut rect, display_list.iter(), node)
} }
} }
reply_chan.send(ContentBoxResponse(rect.unwrap_or(Au::zero_rect()))) reply_chan.send(ContentBoxResponse(rect.unwrap_or(Au::zero_rect())))
@ -763,7 +769,7 @@ impl LayoutTask {
match self.display_list { match self.display_list {
None => fail!("no display list!"), None => fail!("no display list!"),
Some(ref display_list) => { Some(ref display_list) => {
add_boxes_for_node(&mut boxes, display_list.get().iter(), node) add_boxes_for_node(&mut boxes, display_list.iter(), node)
} }
} }
reply_chan.send(ContentBoxesResponse(boxes)) reply_chan.send(ContentBoxesResponse(boxes))
@ -811,7 +817,7 @@ impl LayoutTask {
Au::from_frac_px(point.y as f64)); Au::from_frac_px(point.y as f64));
let resp = match self.display_list { let resp = match self.display_list {
None => fail!("no display list!"), None => fail!("no display list!"),
Some(ref display_list) => hit_test(x, y, display_list.get().list.as_slice()), Some(ref display_list) => hit_test(x, y, display_list.list.as_slice()),
}; };
if resp.is_some() { if resp.is_some() {
reply_chan.send(Ok(resp.unwrap())); reply_chan.send(Ok(resp.unwrap()));
@ -858,7 +864,7 @@ impl LayoutTask {
Some(ref display_list) => { Some(ref display_list) => {
mouse_over_test(x, mouse_over_test(x,
y, y,
display_list.get().list.as_slice(), display_list.list.as_slice(),
&mut mouse_over_list); &mut mouse_over_list);
} }
}; };

View file

@ -14,11 +14,11 @@ use servo_util::geometry;
/// A collapsible margin. See CSS 2.1 § 8.3.1. /// A collapsible margin. See CSS 2.1 § 8.3.1.
pub struct AdjoiningMargins { pub struct AdjoiningMargins {
/// The value of the greatest positive margin. /// The value of the greatest positive margin.
most_positive: Au, pub most_positive: Au,
/// The actual value (not the absolute value) of the negative margin with the largest absolute /// The actual value (not the absolute value) of the negative margin with the largest absolute
/// value. Since this is not the absolute value, this is always zero or negative. /// value. Since this is not the absolute value, this is always zero or negative.
most_negative: Au, pub most_negative: Au,
} }
impl AdjoiningMargins { impl AdjoiningMargins {
@ -79,9 +79,9 @@ enum FinalMarginState {
} }
pub struct MarginCollapseInfo { pub struct MarginCollapseInfo {
state: MarginCollapseState, pub state: MarginCollapseState,
top_margin: AdjoiningMargins, pub top_margin: AdjoiningMargins,
margin_in: AdjoiningMargins, pub margin_in: AdjoiningMargins,
} }
impl MarginCollapseInfo { impl MarginCollapseInfo {
@ -101,7 +101,7 @@ impl MarginCollapseInfo {
self.state = AccumulatingMarginIn self.state = AccumulatingMarginIn
} }
self.top_margin = AdjoiningMargins::from_margin(fragment.margin.get().top) self.top_margin = AdjoiningMargins::from_margin(fragment.margin.borrow().top)
} }
pub fn finish_and_compute_collapsible_margins(mut self, pub fn finish_and_compute_collapsible_margins(mut self,
@ -135,7 +135,7 @@ impl MarginCollapseInfo {
// Different logic is needed here depending on whether this flow can collapse its bottom // Different logic is needed here depending on whether this flow can collapse its bottom
// margin with its children. // margin with its children.
let bottom_margin = fragment.margin.get().bottom; let bottom_margin = fragment.margin.borrow().bottom;
if !can_collapse_bottom_margin_with_kids { if !can_collapse_bottom_margin_with_kids {
match state { match state {
MarginsCollapseThroughFinalMarginState => { MarginsCollapseThroughFinalMarginState => {
@ -239,12 +239,12 @@ pub enum MarginCollapseState {
/// Intrinsic widths, which consist of minimum and preferred. /// Intrinsic widths, which consist of minimum and preferred.
pub struct IntrinsicWidths { pub struct IntrinsicWidths {
/// The *minimum width* of the content. /// The *minimum width* of the content.
minimum_width: Au, pub minimum_width: Au,
/// The *preferred width* of the content. /// The *preferred width* of the content.
preferred_width: Au, pub preferred_width: Au,
/// The estimated sum of borders, padding, and margins. Some calculations use this information /// The estimated sum of borders, padding, and margins. Some calculations use this information
/// when computing intrinsic widths. /// when computing intrinsic widths.
surround_width: Au, pub surround_width: Au,
} }
impl IntrinsicWidths { impl IntrinsicWidths {

View file

@ -90,7 +90,7 @@ pub fn mut_borrowed_flow_to_unsafe_flow(flow: &mut Flow) -> UnsafeFlow {
/// Information that we need stored in each DOM node. /// Information that we need stored in each DOM node.
pub struct DomParallelInfo { pub struct DomParallelInfo {
/// The number of children that still need work done. /// The number of children that still need work done.
children_count: AtomicInt, pub children_count: AtomicInt,
} }
impl DomParallelInfo { impl DomParallelInfo {
@ -104,9 +104,9 @@ impl DomParallelInfo {
/// Information that we need stored in each flow. /// Information that we need stored in each flow.
pub struct FlowParallelInfo { pub struct FlowParallelInfo {
/// The number of children that still need work done. /// The number of children that still need work done.
children_count: AtomicInt, pub children_count: AtomicInt,
/// The address of the parent flow. /// The address of the parent flow.
parent: UnsafeFlow, pub parent: UnsafeFlow,
} }
impl FlowParallelInfo { impl FlowParallelInfo {
@ -270,7 +270,7 @@ fn recalc_style_for_node(unsafe_layout_node: UnsafeLayoutNode,
// Perform the CSS cascade. // Perform the CSS cascade.
node.cascade_node(parent_opt, node.cascade_node(parent_opt,
layout_context.initial_css_values.get(), &*layout_context.initial_css_values,
&applicable_declarations, &applicable_declarations,
layout_context.applicable_declarations_cache()); layout_context.applicable_declarations_cache());

View file

@ -25,19 +25,19 @@ use style::computed_values::table_layout;
/// The properties `position`, `float`, and `margin-*` are used on the table wrapper box, /// The properties `position`, `float`, and `margin-*` are used on the table wrapper box,
/// not table box per CSS 2.1 § 10.5. /// not table box per CSS 2.1 § 10.5.
pub struct TableFlow { pub struct TableFlow {
block_flow: BlockFlow, pub block_flow: BlockFlow,
/// Column widths /// Column widths
col_widths: ~[Au], pub col_widths: ~[Au],
/// Column min widths. /// Column min widths.
col_min_widths: ~[Au], pub col_min_widths: ~[Au],
/// Column pref widths. /// Column pref widths.
col_pref_widths: ~[Au], pub col_pref_widths: ~[Au],
/// Table-layout property /// Table-layout property
table_layout: TableLayout, pub table_layout: TableLayout,
} }
impl TableFlow { impl TableFlow {
@ -268,10 +268,10 @@ impl Flow for TableFlow {
let width_computer = InternalTable; let width_computer = InternalTable;
width_computer.compute_used_width(&mut self.block_flow, ctx, containing_block_width); width_computer.compute_used_width(&mut self.block_flow, ctx, containing_block_width);
let left_content_edge = self.block_flow.box_.padding.get().left + self.block_flow.box_.border.get().left; let left_content_edge = self.block_flow.box_.padding.borrow().left + self.block_flow.box_.border.borrow().left;
let padding_and_borders = self.block_flow.box_.padding.get().left + self.block_flow.box_.padding.get().right + let padding_and_borders = self.block_flow.box_.padding.borrow().left + self.block_flow.box_.padding.borrow().right +
self.block_flow.box_.border.get().left + self.block_flow.box_.border.get().right; self.block_flow.box_.border.borrow().left + self.block_flow.box_.border.borrow().right;
let content_width = self.block_flow.box_.border_box.get().size.width - padding_and_borders; let content_width = self.block_flow.box_.border_box.borrow().size.width - padding_and_borders;
match self.table_layout { match self.table_layout {
FixedLayout => { FixedLayout => {

View file

@ -15,7 +15,7 @@ use gfx::display_list::StackingContext;
/// A table formatting context. /// A table formatting context.
pub struct TableCaptionFlow { pub struct TableCaptionFlow {
block_flow: BlockFlow, pub block_flow: BlockFlow,
} }
impl TableCaptionFlow { impl TableCaptionFlow {

View file

@ -19,7 +19,7 @@ use servo_util::geometry::Au;
/// A table formatting context. /// A table formatting context.
pub struct TableCellFlow { pub struct TableCellFlow {
/// Data common to all flows. /// Data common to all flows.
block_flow: BlockFlow, pub block_flow: BlockFlow,
} }
impl TableCellFlow { impl TableCellFlow {
@ -100,10 +100,10 @@ impl Flow for TableCellFlow {
let width_computer = InternalTable; let width_computer = InternalTable;
width_computer.compute_used_width(&mut self.block_flow, ctx, containing_block_width); width_computer.compute_used_width(&mut self.block_flow, ctx, containing_block_width);
let left_content_edge = self.block_flow.box_.border_box.get().origin.x + self.block_flow.box_.padding.get().left + self.block_flow.box_.border.get().left; let left_content_edge = self.block_flow.box_.border_box.borrow().origin.x + self.block_flow.box_.padding.borrow().left + self.block_flow.box_.border.borrow().left;
let padding_and_borders = self.block_flow.box_.padding.get().left + self.block_flow.box_.padding.get().right + let padding_and_borders = self.block_flow.box_.padding.borrow().left + self.block_flow.box_.padding.borrow().right +
self.block_flow.box_.border.get().left + self.block_flow.box_.border.get().right; self.block_flow.box_.border.borrow().left + self.block_flow.box_.border.borrow().right;
let content_width = self.block_flow.box_.border_box.get().size.width - padding_and_borders; let content_width = self.block_flow.box_.border_box.borrow().size.width - padding_and_borders;
self.block_flow.propagate_assigned_width_to_children(left_content_edge, content_width, None); self.block_flow.propagate_assigned_width_to_children(left_content_edge, content_width, None);
} }

View file

@ -14,16 +14,16 @@ use servo_util::geometry::Au;
/// A table formatting context. /// A table formatting context.
pub struct TableColGroupFlow { pub struct TableColGroupFlow {
/// Data common to all flows. /// Data common to all flows.
base: BaseFlow, pub base: BaseFlow,
/// The associated box. /// The associated box.
box_: Option<Box>, pub box_: Option<Box>,
/// The table column boxes /// The table column boxes
cols: ~[Box], pub cols: ~[Box],
/// The specified widths of table columns /// The specified widths of table columns
widths: ~[Au], pub widths: ~[Au],
} }
impl TableColGroupFlow { impl TableColGroupFlow {

View file

@ -22,16 +22,16 @@ use servo_util::geometry;
/// A table formatting context. /// A table formatting context.
pub struct TableRowFlow { pub struct TableRowFlow {
block_flow: BlockFlow, pub block_flow: BlockFlow,
/// Column widths. /// Column widths.
col_widths: ~[Au], pub col_widths: ~[Au],
/// Column min widths. /// Column min widths.
col_min_widths: ~[Au], pub col_min_widths: ~[Au],
/// Column pref widths. /// Column pref widths.
col_pref_widths: ~[Au], pub col_pref_widths: ~[Au],
} }
impl TableRowFlow { impl TableRowFlow {
@ -116,18 +116,18 @@ impl TableRowFlow {
// Assign the height of own box // Assign the height of own box
// //
// FIXME(pcwalton): Take `cur_y` into account. // FIXME(pcwalton): Take `cur_y` into account.
let mut position = self.block_flow.box_.border_box.get(); let mut position = *self.block_flow.box_.border_box.borrow();
position.size.height = height; position.size.height = height;
self.block_flow.box_.border_box.set(position); *self.block_flow.box_.border_box.borrow_mut() = position;
self.block_flow.base.position.size.height = height; self.block_flow.base.position.size.height = height;
// Assign the height of kid boxes, which is the same value as own height. // Assign the height of kid boxes, which is the same value as own height.
for kid in self.block_flow.base.child_iter() { for kid in self.block_flow.base.child_iter() {
{ {
let kid_box_ = kid.as_table_cell().box_(); let kid_box_ = kid.as_table_cell().box_();
let mut position = kid_box_.border_box.get(); let mut position = *kid_box_.border_box.borrow();
position.size.height = height; position.size.height = height;
kid_box_.border_box.set(position); *kid_box_.border_box.borrow_mut() = position;
} }
let child_node = flow::mut_base(kid); let child_node = flow::mut_base(kid);
child_node.position.size.height = height; child_node.position.size.height = height;

View file

@ -21,16 +21,16 @@ use servo_util::geometry;
/// A table formatting context. /// A table formatting context.
pub struct TableRowGroupFlow { pub struct TableRowGroupFlow {
block_flow: BlockFlow, pub block_flow: BlockFlow,
/// Column widths /// Column widths
col_widths: ~[Au], pub col_widths: ~[Au],
/// Column min widths. /// Column min widths.
col_min_widths: ~[Au], pub col_min_widths: ~[Au],
/// Column pref widths. /// Column pref widths.
col_pref_widths: ~[Au], pub col_pref_widths: ~[Au],
} }
impl TableRowGroupFlow { impl TableRowGroupFlow {
@ -93,9 +93,9 @@ impl TableRowGroupFlow {
let height = cur_y - top_offset; let height = cur_y - top_offset;
let mut position = self.block_flow.box_.border_box.get(); let mut position = *self.block_flow.box_.border_box.borrow();
position.size.height = height; position.size.height = height;
self.block_flow.box_.border_box.set(position); *self.block_flow.box_.border_box.borrow_mut() = position;
self.block_flow.base.position.size.height = height; self.block_flow.base.position.size.height = height;
} }

View file

@ -27,13 +27,13 @@ pub enum TableLayout {
/// A table wrapper flow based on a block formatting context. /// A table wrapper flow based on a block formatting context.
pub struct TableWrapperFlow { pub struct TableWrapperFlow {
block_flow: BlockFlow, pub block_flow: BlockFlow,
/// Column widths /// Column widths
col_widths: ~[Au], pub col_widths: ~[Au],
/// Table-layout property /// Table-layout property
table_layout: TableLayout, pub table_layout: TableLayout,
} }
impl TableWrapperFlow { impl TableWrapperFlow {
@ -170,8 +170,8 @@ impl Flow for TableWrapperFlow {
let width_computer = TableWrapper; let width_computer = TableWrapper;
width_computer.compute_used_width_table_wrapper(self, ctx, containing_block_width); width_computer.compute_used_width_table_wrapper(self, ctx, containing_block_width);
let left_content_edge = self.block_flow.box_.border_box.get().origin.x; let left_content_edge = self.block_flow.box_.border_box.borrow().origin.x;
let content_width = self.block_flow.box_.border_box.get().size.width; let content_width = self.block_flow.box_.border_box.borrow().size.width;
match self.table_layout { match self.table_layout {
FixedLayout | _ if self.is_float() => FixedLayout | _ if self.is_float() =>
@ -320,9 +320,9 @@ impl TableWrapper {
// The extra width is distributed over the columns // The extra width is distributed over the columns
if extra_width > Au(0) { if extra_width > Au(0) {
let cell_len = table_wrapper.col_widths.len() as f64; let cell_len = table_wrapper.col_widths.len() as f64;
table_wrapper.col_widths = col_min_widths.map(|width| { table_wrapper.col_widths = col_min_widths.iter().map(|width| {
width + extra_width.scale_by(1.0 / cell_len) width + extra_width.scale_by(1.0 / cell_len)
}); }).collect();
} }
width width
} }

View file

@ -17,7 +17,7 @@ use sync::Arc;
/// A stack-allocated object for scanning an inline flow into `TextRun`-containing `TextBox`es. /// A stack-allocated object for scanning an inline flow into `TextRun`-containing `TextBox`es.
pub struct TextRunScanner { pub struct TextRunScanner {
clump: Range, pub clump: Range,
} }
impl TextRunScanner { impl TextRunScanner {
@ -244,7 +244,7 @@ impl TextRunScanner {
} }
let new_text_box_info = ScannedTextBoxInfo::new(run.get_ref().clone(), range); let new_text_box_info = ScannedTextBoxInfo::new(run.get_ref().clone(), range);
let new_metrics = new_text_box_info.run.get().metrics_for_range(&range); let new_metrics = new_text_box_info.run.metrics_for_range(&range);
let mut new_box = in_boxes[i].transform(new_metrics.bounding_box.size, let mut new_box = in_boxes[i].transform(new_metrics.bounding_box.size,
ScannedTextBox(new_text_box_info)); ScannedTextBox(new_text_box_info));
new_box.new_line_pos = new_line_positions[logical_offset].new_line_pos.clone(); new_box.new_line_pos = new_line_positions[logical_offset].new_line_pos.clone();

View file

@ -8,6 +8,7 @@ use layout::parallel::DomParallelInfo;
use layout::wrapper::{LayoutNode, TLayoutNode, ThreadSafeLayoutNode}; use layout::wrapper::{LayoutNode, TLayoutNode, ThreadSafeLayoutNode};
use gfx::display_list::OpaqueNode; use gfx::display_list::OpaqueNode;
use libc::uintptr_t;
use script::dom::bindings::js::JS; use script::dom::bindings::js::JS;
use script::dom::bindings::utils::Reflectable; use script::dom::bindings::utils::Reflectable;
use script::dom::node::Node; use script::dom::node::Node;
@ -16,15 +17,14 @@ use servo_util::range::Range;
use std::cast; use std::cast;
use std::cell::{Ref, RefMut}; use std::cell::{Ref, RefMut};
use std::iter::Enumerate; use std::iter::Enumerate;
use std::libc::uintptr_t;
use std::slice::Items; use std::slice::Items;
use style::ComputedValues; use style::ComputedValues;
use sync::Arc; use sync::Arc;
/// A range of nodes. /// A range of nodes.
pub struct NodeRange { pub struct NodeRange {
node: OpaqueNode, pub node: OpaqueNode,
range: Range, pub range: Range,
} }
impl NodeRange { impl NodeRange {
@ -37,7 +37,7 @@ impl NodeRange {
} }
pub struct ElementMapping { pub struct ElementMapping {
priv entries: ~[NodeRange], entries: ~[NodeRange],
} }
impl ElementMapping { impl ElementMapping {
@ -132,27 +132,27 @@ impl ElementMapping {
/// Data that layout associates with a node. /// Data that layout associates with a node.
pub struct PrivateLayoutData { pub struct PrivateLayoutData {
/// The results of CSS styling for this node. /// The results of CSS styling for this node.
style: Option<Arc<ComputedValues>>, pub style: Option<Arc<ComputedValues>>,
/// The results of CSS styling for this node's `before` pseudo-element, if any. /// The results of CSS styling for this node's `before` pseudo-element, if any.
before_style: Option<Arc<ComputedValues>>, pub before_style: Option<Arc<ComputedValues>>,
/// The results of CSS styling for this node's `after` pseudo-element, if any. /// The results of CSS styling for this node's `after` pseudo-element, if any.
after_style: Option<Arc<ComputedValues>>, pub after_style: Option<Arc<ComputedValues>>,
/// Description of how to account for recent style changes. /// Description of how to account for recent style changes.
restyle_damage: Option<int>, pub restyle_damage: Option<int>,
/// The current results of flow construction for this node. This is either a flow or a /// The current results of flow construction for this node. This is either a flow or a
/// `ConstructionItem`. See comments in `construct.rs` for more details. /// `ConstructionItem`. See comments in `construct.rs` for more details.
flow_construction_result: ConstructionResult, pub flow_construction_result: ConstructionResult,
before_flow_construction_result: ConstructionResult, pub before_flow_construction_result: ConstructionResult,
after_flow_construction_result: ConstructionResult, pub after_flow_construction_result: ConstructionResult,
/// Information needed during parallel traversals. /// Information needed during parallel traversals.
parallel: DomParallelInfo, pub parallel: DomParallelInfo,
} }
impl PrivateLayoutData { impl PrivateLayoutData {
@ -172,8 +172,8 @@ impl PrivateLayoutData {
} }
pub struct LayoutDataWrapper { pub struct LayoutDataWrapper {
chan: Option<LayoutChan>, pub chan: Option<LayoutChan>,
data: ~PrivateLayoutData, pub data: ~PrivateLayoutData,
} }
/// A trait that allows access to the layout data of a DOM node. /// A trait that allows access to the layout data of a DOM node.

View file

@ -130,10 +130,10 @@ pub trait TLayoutNode {
/// only ever see these and must never see instances of `JS`. /// only ever see these and must never see instances of `JS`.
pub struct LayoutNode<'a> { pub struct LayoutNode<'a> {
/// The wrapped node. /// The wrapped node.
priv node: JS<Node>, node: JS<Node>,
/// Being chained to a value prevents `LayoutNode`s from escaping. /// Being chained to a value prevents `LayoutNode`s from escaping.
chain: &'a (), pub chain: &'a (),
} }
impl<'ln> Clone for LayoutNode<'ln> { impl<'ln> Clone for LayoutNode<'ln> {
@ -278,7 +278,7 @@ impl<'ln> TNode<LayoutElement<'ln>> for LayoutNode<'ln> {
} }
pub struct LayoutNodeChildrenIterator<'a> { pub struct LayoutNodeChildrenIterator<'a> {
priv current_node: Option<LayoutNode<'a>>, current_node: Option<LayoutNode<'a>>,
} }
impl<'a> Iterator<LayoutNode<'a>> for LayoutNodeChildrenIterator<'a> { impl<'a> Iterator<LayoutNode<'a>> for LayoutNodeChildrenIterator<'a> {
@ -296,8 +296,8 @@ impl<'a> Iterator<LayoutNode<'a>> for LayoutNodeChildrenIterator<'a> {
// //
// FIXME(pcwalton): Parallelism! Eventually this should just be nuked. // FIXME(pcwalton): Parallelism! Eventually this should just be nuked.
pub struct LayoutTreeIterator<'a> { pub struct LayoutTreeIterator<'a> {
priv nodes: ~[LayoutNode<'a>], nodes: ~[LayoutNode<'a>],
priv index: uint, index: uint,
} }
impl<'a> LayoutTreeIterator<'a> { impl<'a> LayoutTreeIterator<'a> {
@ -336,7 +336,7 @@ fn gather_layout_nodes<'a>(cur: &LayoutNode<'a>, refs: &mut ~[LayoutNode<'a>], p
/// A wrapper around elements that ensures layout can only ever access safe properties. /// A wrapper around elements that ensures layout can only ever access safe properties.
pub struct LayoutElement<'le> { pub struct LayoutElement<'le> {
priv element: &'le Element, element: &'le Element,
} }
impl<'le> LayoutElement<'le> { impl<'le> LayoutElement<'le> {
@ -409,9 +409,9 @@ pub enum PseudoElementType {
#[deriving(Clone)] #[deriving(Clone)]
pub struct ThreadSafeLayoutNode<'ln> { pub struct ThreadSafeLayoutNode<'ln> {
/// The wrapped node. /// The wrapped node.
priv node: LayoutNode<'ln>, node: LayoutNode<'ln>,
priv pseudo: PseudoElementType, pseudo: PseudoElementType,
} }
impl<'ln> TLayoutNode for ThreadSafeLayoutNode<'ln> { impl<'ln> TLayoutNode for ThreadSafeLayoutNode<'ln> {
@ -470,10 +470,10 @@ impl<'ln> TLayoutNode for ThreadSafeLayoutNode<'ln> {
if self.pseudo == Before { if self.pseudo == Before {
let before_style = node_layout_data_wrapper.data.before_style.get_ref(); let before_style = node_layout_data_wrapper.data.before_style.get_ref();
return get_content(&before_style.get().Box.get().content) return get_content(&before_style.Box.get().content)
} else { } else {
let after_style = node_layout_data_wrapper.data.after_style.get_ref(); let after_style = node_layout_data_wrapper.data.after_style.get_ref();
return get_content(&after_style.get().Box.get().content) return get_content(&after_style.Box.get().content)
} }
} }
@ -548,15 +548,15 @@ impl<'ln> ThreadSafeLayoutNode<'ln> {
let display = match kind { let display = match kind {
Before | BeforeBlock => { Before | BeforeBlock => {
let before_style = node_layout_data_wrapper.data.before_style.get_ref(); let before_style = node_layout_data_wrapper.data.before_style.get_ref();
before_style.get().Box.get().display before_style.Box.get().display
} }
After | AfterBlock => { After | AfterBlock => {
let after_style = node_layout_data_wrapper.data.after_style.get_ref(); let after_style = node_layout_data_wrapper.data.after_style.get_ref();
after_style.get().Box.get().display after_style.Box.get().display
} }
Normal => { Normal => {
let after_style = node_layout_data_wrapper.data.style.get_ref(); let after_style = node_layout_data_wrapper.data.style.get_ref();
after_style.get().Box.get().display after_style.Box.get().display
} }
}; };
@ -620,8 +620,8 @@ impl<'ln> ThreadSafeLayoutNode<'ln> {
} }
pub struct ThreadSafeLayoutNodeChildrenIterator<'a> { pub struct ThreadSafeLayoutNodeChildrenIterator<'a> {
priv current_node: Option<ThreadSafeLayoutNode<'a>>, current_node: Option<ThreadSafeLayoutNode<'a>>,
priv parent_node: Option<ThreadSafeLayoutNode<'a>>, parent_node: Option<ThreadSafeLayoutNode<'a>>,
} }
impl<'a> Iterator<ThreadSafeLayoutNode<'a>> for ThreadSafeLayoutNodeChildrenIterator<'a> { impl<'a> Iterator<ThreadSafeLayoutNode<'a>> for ThreadSafeLayoutNodeChildrenIterator<'a> {
@ -678,7 +678,7 @@ impl<'a> Iterator<ThreadSafeLayoutNode<'a>> for ThreadSafeLayoutNodeChildrenIter
/// A wrapper around elements that ensures layout can only ever access safe properties and cannot /// A wrapper around elements that ensures layout can only ever access safe properties and cannot
/// race on elements. /// race on elements.
pub struct ThreadSafeLayoutElement<'le> { pub struct ThreadSafeLayoutElement<'le> {
priv element: &'le Element, element: &'le Element,
} }
impl<'le> ThreadSafeLayoutElement<'le> { impl<'le> ThreadSafeLayoutElement<'le> {

View file

@ -23,23 +23,23 @@ use url::Url;
/// A uniquely-identifiable pipeline of script task, layout task, and render task. /// A uniquely-identifiable pipeline of script task, layout task, and render task.
pub struct Pipeline { pub struct Pipeline {
id: PipelineId, pub id: PipelineId,
subpage_id: Option<SubpageId>, pub subpage_id: Option<SubpageId>,
script_chan: ScriptChan, pub script_chan: ScriptChan,
layout_chan: LayoutChan, pub layout_chan: LayoutChan,
render_chan: RenderChan, pub render_chan: RenderChan,
layout_shutdown_port: Receiver<()>, pub layout_shutdown_port: Receiver<()>,
render_shutdown_port: Receiver<()>, pub render_shutdown_port: Receiver<()>,
/// The most recently loaded url /// The most recently loaded url
url: RefCell<Option<Url>>, pub url: RefCell<Option<Url>>,
} }
/// The subset of the pipeline that is needed for layer composition. /// The subset of the pipeline that is needed for layer composition.
#[deriving(Clone)] #[deriving(Clone)]
pub struct CompositionPipeline { pub struct CompositionPipeline {
id: PipelineId, pub id: PipelineId,
script_chan: ScriptChan, pub script_chan: ScriptChan,
render_chan: RenderChan, pub render_chan: RenderChan,
} }
impl Pipeline { impl Pipeline {
@ -187,7 +187,7 @@ impl Pipeline {
} }
pub fn load(&self, url: Url) { pub fn load(&self, url: Url) {
self.url.set(Some(url.clone())); *self.url.borrow_mut() = Some(url.clone());
let ScriptChan(ref chan) = self.script_chan; let ScriptChan(ref chan) = self.script_chan;
chan.send(LoadMsg(self.id, url)); chan.send(LoadMsg(self.id, url));
} }

View file

@ -12,10 +12,11 @@ use windowing::RefreshWindowEvent;
use windowing::{Forward, Back}; use windowing::{Forward, Back};
use alert::{Alert, AlertMethods}; use alert::{Alert, AlertMethods};
use libc::{exit, c_int};
use time; use time;
use time::Timespec; use time::Timespec;
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
use std::libc::{exit, c_int}; use std::comm::Receiver;
use std::rc::Rc; use std::rc::Rc;
use geom::point::Point2D; use geom::point::Point2D;
@ -24,24 +25,27 @@ use servo_msg::compositor_msg::{IdleRenderState, RenderState, RenderingRenderSta
use servo_msg::compositor_msg::{FinishedLoading, Blank, Loading, PerformingLayout, ReadyState}; use servo_msg::compositor_msg::{FinishedLoading, Blank, Loading, PerformingLayout, ReadyState};
use glfw; use glfw;
use glfw::Context;
/// A structure responsible for setting up and tearing down the entire windowing system. /// A structure responsible for setting up and tearing down the entire windowing system.
pub struct Application; pub struct Application {
pub glfw: glfw::Glfw,
}
impl ApplicationMethods for Application { impl ApplicationMethods for Application {
fn new() -> Application { fn new() -> Application {
// Per GLFW docs it's safe to set the error callback before calling let app = glfw::init(glfw::LOG_ERRORS);
// glfwInit(), and this way we notice errors from init too. match app {
glfw::set_error_callback(~glfw::LogErrorHandler); Err(_) => {
// handles things like inability to connect to X
if glfw::init().is_err() { // cannot simply fail, since the runtime isn't up yet (causes a nasty abort)
// handles things like inability to connect to X println!("GLFW initialization failed");
// cannot simply fail, since the runtime isn't up yet (causes a nasty abort) unsafe { exit(1); }
println!("GLFW initialization failed"); }
unsafe { exit(1); } Ok(app) => {
Application { glfw: app }
}
} }
Application
} }
} }
@ -79,32 +83,38 @@ macro_rules! glfw_callback(
/// The type of a window. /// The type of a window.
pub struct Window { pub struct Window {
glfw_window: glfw::Window, pub glfw: glfw::Glfw,
event_queue: RefCell<~[WindowEvent]>, pub glfw_window: glfw::Window,
pub events: Receiver<(f64, glfw::WindowEvent)>,
drag_origin: Point2D<c_int>, pub event_queue: RefCell<~[WindowEvent]>,
mouse_down_button: Cell<Option<glfw::MouseButton>>, pub drag_origin: Point2D<c_int>,
mouse_down_point: Cell<Point2D<c_int>>,
ready_state: Cell<ReadyState>, pub mouse_down_button: Cell<Option<glfw::MouseButton>>,
render_state: Cell<RenderState>, pub mouse_down_point: Cell<Point2D<c_int>>,
last_title_set_time: Cell<Timespec>, pub ready_state: Cell<ReadyState>,
pub render_state: Cell<RenderState>,
pub last_title_set_time: Cell<Timespec>,
} }
impl WindowMethods<Application> for Window { impl WindowMethods<Application> for Window {
/// Creates a new window. /// Creates a new window.
fn new(_: &Application) -> Rc<Window> { fn new(app: &Application) -> Rc<Window> {
// Create the GLFW window. // Create the GLFW window.
let glfw_window = glfw::Window::create(800, 600, "Servo", glfw::Windowed) let (glfw_window, events) = app.glfw.create_window(800, 600, "Servo", glfw::Windowed)
.expect("Failed to create GLFW window"); .expect("Failed to create GLFW window");
glfw_window.make_context_current(); glfw_window.make_current();
// Create our window object. // Create our window object.
let window = Window { let window = Window {
glfw: app.glfw,
glfw_window: glfw_window, glfw_window: glfw_window,
events: events,
event_queue: RefCell::new(~[]), event_queue: RefCell::new(~[]),
@ -151,8 +161,8 @@ impl WindowMethods<Application> for Window {
} }
} }
glfw::poll_events(); self.glfw.poll_events();
for (_, event) in self.glfw_window.flush_events() { for (_, event) in glfw::flush_messages(&self.events) {
self.handle_window_event(&self.glfw_window, event); self.handle_window_event(&self.glfw_window, event);
} }

View file

@ -11,8 +11,8 @@ use windowing::{MouseWindowClickEvent, MouseWindowMouseDownEvent, MouseWindowMou
use windowing::{Forward, Back}; use windowing::{Forward, Back};
use alert::{Alert, AlertMethods}; use alert::{Alert, AlertMethods};
use libc::{c_int, c_uchar};
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
use std::libc::{c_int, c_uchar};
use std::local_data; use std::local_data;
use std::rc::Rc; use std::rc::Rc;
use geom::point::Point2D; use geom::point::Point2D;
@ -45,18 +45,18 @@ impl Drop for Application {
/// The type of a window. /// The type of a window.
pub struct Window { pub struct Window {
glut_window: glut::Window, pub glut_window: glut::Window,
event_queue: RefCell<~[WindowEvent]>, pub event_queue: RefCell<~[WindowEvent]>,
drag_origin: Point2D<c_int>, pub drag_origin: Point2D<c_int>,
mouse_down_button: Cell<c_int>, pub mouse_down_button: Cell<c_int>,
mouse_down_point: Cell<Point2D<c_int>>, pub mouse_down_point: Cell<Point2D<c_int>>,
ready_state: Cell<ReadyState>, pub ready_state: Cell<ReadyState>,
render_state: Cell<RenderState>, pub render_state: Cell<RenderState>,
throbber_frame: Cell<u8>, pub throbber_frame: Cell<u8>,
} }
impl WindowMethods<Application> for Window { impl WindowMethods<Application> for Window {

View file

@ -2,13 +2,13 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#[crate_id = "github.com/mozilla/servo"]; #![crate_id = "github.com/mozilla/servo"]
#[comment = "The Servo Parallel Browser Project"]; #![comment = "The Servo Parallel Browser Project"]
#[license = "MPL"]; #![license = "MPL"]
#[feature(globs, macro_rules, phase, thread_local)]; #![feature(globs, macro_rules, phase, thread_local)]
#[feature(phase)]; #![feature(phase)]
#[phase(syntax, link)] #[phase(syntax, link)]
extern crate log; extern crate log;
@ -17,7 +17,7 @@ extern crate azure;
extern crate geom; extern crate geom;
extern crate gfx; extern crate gfx;
#[cfg(not(target_os="android"))] #[cfg(not(target_os="android"))]
extern crate glfw = "glfw-rs"; extern crate glfw;
#[cfg(target_os="android")] #[cfg(target_os="android")]
extern crate glut; extern crate glut;
extern crate js; extern crate js;
@ -37,6 +37,7 @@ extern crate stb_image;
extern crate collections; extern crate collections;
extern crate green; extern crate green;
extern crate libc;
extern crate native; extern crate native;
extern crate serialize; extern crate serialize;
extern crate sync; extern crate sync;
@ -158,7 +159,9 @@ pub extern "C" fn android_start(argc: int, argv: **u8) -> int {
#[cfg(not(test))] #[cfg(not(test))]
fn run(opts: opts::Opts) { fn run(opts: opts::Opts) {
let mut pool = green::SchedPool::new(green::PoolConfig::new()); let mut pool_config = green::PoolConfig::new();
pool_config.event_loop_factory = rustuv::event_loop;
let mut pool = green::SchedPool::new(pool_config);
let (compositor_port, compositor_chan) = CompositorChan::new(); let (compositor_port, compositor_chan) = CompositorChan::new();
let profiler_chan = Profiler::create(opts.profiler_period); let profiler_chan = Profiler::create(opts.profiler_period);

View file

@ -17,25 +17,25 @@ use constellation_msg::PipelineId;
pub struct LayerBuffer { pub struct LayerBuffer {
/// The native surface which can be shared between threads or processes. On Mac this is an /// The native surface which can be shared between threads or processes. On Mac this is an
/// `IOSurface`; on Linux this is an X Pixmap; on Android this is an `EGLImageKHR`. /// `IOSurface`; on Linux this is an X Pixmap; on Android this is an `EGLImageKHR`.
native_surface: NativeSurface, pub native_surface: NativeSurface,
/// The rect in the containing RenderLayer that this represents. /// The rect in the containing RenderLayer that this represents.
rect: Rect<f32>, pub rect: Rect<f32>,
/// The rect in pixels that will be drawn to the screen. /// The rect in pixels that will be drawn to the screen.
screen_pos: Rect<uint>, pub screen_pos: Rect<uint>,
/// The scale at which this tile is rendered /// The scale at which this tile is rendered
resolution: f32, pub resolution: f32,
/// NB: stride is in pixels, like OpenGL GL_UNPACK_ROW_LENGTH. /// NB: stride is in pixels, like OpenGL GL_UNPACK_ROW_LENGTH.
stride: uint, pub stride: uint,
} }
/// A set of layer buffers. This is an atomic unit used to switch between the front and back /// A set of layer buffers. This is an atomic unit used to switch between the front and back
/// buffers. /// buffers.
pub struct LayerBufferSet { pub struct LayerBufferSet {
buffers: ~[~LayerBuffer] pub buffers: ~[~LayerBuffer]
} }
impl LayerBufferSet { impl LayerBufferSet {
@ -68,7 +68,7 @@ pub enum ReadyState {
/// A newtype struct for denoting the age of messages; prevents race conditions. /// A newtype struct for denoting the age of messages; prevents race conditions.
#[deriving(Eq)] #[deriving(Eq)]
pub struct Epoch(uint); pub struct Epoch(pub uint);
impl Epoch { impl Epoch {
pub fn next(&mut self) { pub fn next(&mut self) {
@ -78,7 +78,7 @@ impl Epoch {
} }
#[deriving(Clone, Eq)] #[deriving(Clone, Eq)]
pub struct LayerId(uint, uint); pub struct LayerId(pub uint, pub uint);
impl Show for LayerId { impl Show for LayerId {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
@ -108,13 +108,13 @@ pub enum ScrollPolicy {
/// buffer contents of the layer itself. /// buffer contents of the layer itself.
pub struct LayerMetadata { pub struct LayerMetadata {
/// An opaque ID. This is usually the address of the flow and index of the box within it. /// An opaque ID. This is usually the address of the flow and index of the box within it.
id: LayerId, pub id: LayerId,
/// The position and size of the layer in pixels. /// The position and size of the layer in pixels.
position: Rect<uint>, pub position: Rect<uint>,
/// The background color of the layer. /// The background color of the layer.
background_color: Color, pub background_color: Color,
/// The scrolling policy of this layer. /// The scrolling policy of this layer.
scroll_policy: ScrollPolicy, pub scroll_policy: ScrollPolicy,
} }
/// The interface used by the renderer to acquire draw targets for each render frame and /// The interface used by the renderer to acquire draw targets for each render frame and
@ -158,8 +158,9 @@ pub trait ScriptListener : Clone {
fn dup(&self) -> ~ScriptListener; fn dup(&self) -> ~ScriptListener;
} }
impl<S: Encoder> Encodable<S> for ~ScriptListener { impl<E, S: Encoder<E>> Encodable<S, E> for ~ScriptListener {
fn encode(&self, _s: &mut S) { fn encode(&self, _s: &mut S) -> Result<(), E> {
Ok(())
} }
} }

View file

@ -11,7 +11,7 @@ use std::comm::{channel, Sender, Receiver};
use url::Url; use url::Url;
#[deriving(Clone)] #[deriving(Clone)]
pub struct ConstellationChan(Sender<Msg>); pub struct ConstellationChan(pub Sender<Msg>);
impl ConstellationChan { impl ConstellationChan {
pub fn new() -> (Receiver<Msg>, ConstellationChan) { pub fn new() -> (Receiver<Msg>, ConstellationChan) {
@ -29,8 +29,8 @@ pub enum IFrameSandboxState {
// We pass this info to various tasks, so it lives in a separate, cloneable struct. // We pass this info to various tasks, so it lives in a separate, cloneable struct.
#[deriving(Clone)] #[deriving(Clone)]
pub struct Failure { pub struct Failure {
pipeline_id: PipelineId, pub pipeline_id: PipelineId,
subpage_id: Option<SubpageId>, pub subpage_id: Option<SubpageId>,
} }
/// Messages from the compositor and script to the constellation. /// Messages from the compositor and script to the constellation.
@ -61,7 +61,7 @@ pub enum NavigationDirection {
} }
#[deriving(Clone, Eq, TotalEq, Hash, Encodable)] #[deriving(Clone, Eq, TotalEq, Hash, Encodable)]
pub struct PipelineId(uint); pub struct PipelineId(pub uint);
#[deriving(Clone, Eq, TotalEq, Hash, Encodable)] #[deriving(Clone, Eq, TotalEq, Hash, Encodable)]
pub struct SubpageId(uint); pub struct SubpageId(pub uint);

View file

@ -2,10 +2,10 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#[crate_id = "github.com/mozilla/servo#msg:0.1"]; #![crate_id = "github.com/mozilla/servo#msg:0.1"]
#[crate_type = "lib"]; #![crate_type = "lib"]
#[crate_type = "dylib"]; #![crate_type = "dylib"]
#[crate_type = "rlib"]; #![crate_type = "rlib"]
extern crate azure; extern crate azure;
extern crate geom; extern crate geom;

View file

@ -25,7 +25,7 @@ fn load(url: Url, start_chan: Sender<LoadResponse>) {
let mut metadata = Metadata::default(url.clone()); let mut metadata = Metadata::default(url.clone());
// Split out content type and data. // Split out content type and data.
let parts: ~[&str] = url.path.splitn(',', 1).to_owned_vec(); let parts: ~[&str] = url.path.splitn(',', 1).collect();
if parts.len() != 2 { if parts.len() != 2 {
start_sending(start_chan, metadata).send(Done(Err(()))); start_sending(start_chan, metadata).send(Done(Err(())));
return; return;

View file

@ -14,9 +14,9 @@ static READ_SIZE: uint = 1;
fn read_all(reader: &mut io::Stream, progress_chan: &Sender<ProgressMsg>) fn read_all(reader: &mut io::Stream, progress_chan: &Sender<ProgressMsg>)
-> Result<(), ()> { -> Result<(), ()> {
loop { loop {
let mut buf = ~[]; let mut buf = Vec::new();
match reader.push_exact(&mut buf, READ_SIZE) { match reader.push_exact(&mut buf, READ_SIZE) {
Ok(_) => progress_chan.send(Payload(buf)), Ok(_) => progress_chan.send(Payload(buf.iter().map(|&x| x).collect())),
Err(e) => match e.kind { Err(e) => match e.kind {
io::EndOfFile => return Ok(()), io::EndOfFile => return Ok(()),
_ => return Err(()), _ => return Err(()),

View file

@ -5,11 +5,10 @@
use resource_task::{Metadata, Payload, Done, LoadResponse, LoaderTask, start_sending}; use resource_task::{Metadata, Payload, Done, LoadResponse, LoaderTask, start_sending};
use collections::hashmap::HashSet; use collections::hashmap::HashSet;
use http::client::RequestWriter; use http::client::{RequestWriter, NetworkStream};
use http::method::Get; use http::method::Get;
use http::headers::HeaderEnum; use http::headers::HeaderEnum;
use std::io::Reader; use std::io::Reader;
use std::io::net::tcp::TcpStream;
use std::slice; use std::slice;
use servo_util::task::spawn_named; use servo_util::task::spawn_named;
use url::Url; use url::Url;
@ -60,7 +59,7 @@ fn load(mut url: Url, start_chan: Sender<LoadResponse>) {
info!("requesting {:s}", url.to_str()); info!("requesting {:s}", url.to_str());
let request = RequestWriter::<TcpStream>::new(Get, url.clone()); let request = RequestWriter::<NetworkStream>::new(Get, url.clone());
let writer = match request { let writer = match request {
Ok(w) => ~w, Ok(w) => ~w,
Err(_) => { Err(_) => {

View file

@ -6,9 +6,9 @@ use image::base::Image;
use image_cache_task::{ImageReady, ImageNotReady, ImageFailed}; use image_cache_task::{ImageReady, ImageNotReady, ImageFailed};
use local_image_cache::LocalImageCache; use local_image_cache::LocalImageCache;
use sync::{Arc, MutexArc}; use sync::{Arc, Mutex};
use geom::size::Size2D; use geom::size::Size2D;
use std::mem; use std::{cast, mem};
use url::Url; use url::Url;
// FIXME: Nasty coupling here This will be a problem if we want to factor out image handling from // FIXME: Nasty coupling here This will be a problem if we want to factor out image handling from
@ -22,11 +22,12 @@ pub struct ImageHolder {
url: Url, url: Url,
image: Option<Arc<~Image>>, image: Option<Arc<~Image>>,
cached_size: Size2D<int>, cached_size: Size2D<int>,
local_image_cache: MutexArc<LocalImageCache>, // FIXME(rust#13125): Remove the *() for the real type.
local_image_cache: Arc<Mutex<*()>>,
} }
impl ImageHolder { impl ImageHolder {
pub fn new(url: Url, local_image_cache: MutexArc<LocalImageCache>) -> ImageHolder { pub fn new(url: Url, local_image_cache: Arc<Mutex<*()>>) -> ImageHolder {
debug!("ImageHolder::new() {}", url.to_str()); debug!("ImageHolder::new() {}", url.to_str());
let holder = ImageHolder { let holder = ImageHolder {
url: url, url: url,
@ -40,10 +41,14 @@ impl ImageHolder {
// but they are intended to be spread out in time. Ideally prefetch // but they are intended to be spread out in time. Ideally prefetch
// should be done as early as possible and decode only once we // should be done as early as possible and decode only once we
// are sure that the image will be used. // are sure that the image will be used.
holder.local_image_cache.access(|local_image_cache| { {
let val = holder.local_image_cache.lock();
let mut local_image_cache = unsafe {
cast::transmute::<*(), &mut LocalImageCache>(*val)
};
local_image_cache.prefetch(&holder.url); local_image_cache.prefetch(&holder.url);
local_image_cache.decode(&holder.url); local_image_cache.decode(&holder.url);
}); }
holder holder
} }
@ -61,9 +66,8 @@ impl ImageHolder {
pub fn get_size(&mut self) -> Option<Size2D<int>> { pub fn get_size(&mut self) -> Option<Size2D<int>> {
debug!("get_size() {}", self.url.to_str()); debug!("get_size() {}", self.url.to_str());
self.get_image().map(|img| { self.get_image().map(|img| {
let img_ref = img.get(); self.cached_size = Size2D(img.width as int,
self.cached_size = Size2D(img_ref.width as int, img.height as int);
img_ref.height as int);
self.cached_size.clone() self.cached_size.clone()
}) })
} }
@ -74,10 +78,13 @@ impl ImageHolder {
// If this is the first time we've called this function, load // If this is the first time we've called this function, load
// the image and store it for the future // the image and store it for the future
if self.image.is_none() { if self.image.is_none() {
let port = let port = {
self.local_image_cache.access(|local_image_cache| { let val = self.local_image_cache.lock();
local_image_cache.get_image(&self.url) let mut local_image_cache = unsafe {
}); cast::transmute::<*(), &mut LocalImageCache>(*val)
};
local_image_cache.get_image(&self.url)
};
match port.recv() { match port.recv() {
ImageReady(image) => { ImageReady(image) => {
self.image = Some(image); self.image = Some(image);

View file

@ -7,12 +7,13 @@ use resource_task;
use resource_task::ResourceTask; use resource_task::ResourceTask;
use servo_util::url::{UrlMap, url_map}; use servo_util::url::{UrlMap, url_map};
use std::cast;
use std::comm::{channel, Receiver, Sender}; use std::comm::{channel, Receiver, Sender};
use std::mem::replace; use std::mem::replace;
use std::task::spawn; use std::task::spawn;
use std::to_str::ToStr; use std::to_str::ToStr;
use std::result; use std::result;
use sync::{Arc,MutexArc}; use sync::{Arc, Mutex};
use serialize::{Encoder, Encodable}; use serialize::{Encoder, Encodable};
use url::Url; use url::Url;
@ -81,8 +82,9 @@ pub struct ImageCacheTask {
chan: Sender<Msg>, chan: Sender<Msg>,
} }
impl<S: Encoder> Encodable<S> for ImageCacheTask { impl<E, S: Encoder<E>> Encodable<S, E> for ImageCacheTask {
fn encode(&self, _: &mut S) { fn encode(&self, _: &mut S) -> Result<(), E> {
Ok(())
} }
} }
@ -147,7 +149,8 @@ struct ImageCache {
/// The state of processsing an image for a URL /// The state of processsing an image for a URL
state_map: UrlMap<ImageState>, state_map: UrlMap<ImageState>,
/// List of clients waiting on a WaitForImage response /// List of clients waiting on a WaitForImage response
wait_map: UrlMap<MutexArc<~[Sender<ImageResponseMsg>]>>, // FIXME(rust#13125): Remove the *() for the real type.
wait_map: UrlMap<Arc<Mutex<*()>>>,
need_exit: Option<Sender<()>>, need_exit: Option<Sender<()>>,
} }
@ -375,11 +378,17 @@ impl ImageCache {
fn purge_waiters(&mut self, url: Url, f: || -> ImageResponseMsg) { fn purge_waiters(&mut self, url: Url, f: || -> ImageResponseMsg) {
match self.wait_map.pop(&url) { match self.wait_map.pop(&url) {
Some(waiters) => { Some(waiters) => {
waiters.access(|waiters| { let val = waiters.lock();
for response in waiters.iter() { let items = unsafe {
response.send(f()); cast::transmute::<*(), ~[Sender<ImageResponseMsg>]>(*val)
} };
}); for response in items.iter() {
response.send(f());
}
let _ = unsafe {
// Cast back to avoid the drop at the end.
cast::transmute::<~[Sender<ImageResponseMsg>], *()>(items)
};
} }
None => () None => ()
} }
@ -407,9 +416,23 @@ impl ImageCache {
if self.wait_map.contains_key(&url) { if self.wait_map.contains_key(&url) {
let waiters = self.wait_map.find_mut(&url).unwrap(); let waiters = self.wait_map.find_mut(&url).unwrap();
let mut response = Some(response); let mut response = Some(response);
waiters.access(|waiters| waiters.push(response.take().unwrap())); let val = waiters.lock();
let mut items = unsafe {
cast::transmute::<*(), ~[Sender<ImageResponseMsg>]>(*val)
};
items.push(response.take().unwrap());
let _ = unsafe {
// Cast back to avoid the drop at the end.
cast::transmute::<~[Sender<ImageResponseMsg>], *()>(items)
};
} else { } else {
self.wait_map.insert(url, MutexArc::new(~[response])); let response = ~[response];
let wrapped = unsafe {
Arc::new(Mutex::new(
cast::transmute::<~[Sender<ImageResponseMsg>], *()>(response)))
};
self.wait_map.insert(url, wrapped);
} }
} }
@ -481,7 +504,7 @@ fn load_image_data(url: Url, resource_task: ResourceTask) -> Result<~[u8], ()> {
} }
pub fn spawn_listener<A: Send>(f: proc(Receiver<A>)) -> Sender<A> { pub fn spawn_listener<A: Send>(f: proc(Receiver<A>):Send) -> Sender<A> {
let (setup_chan, setup_port) = channel(); let (setup_chan, setup_port) = channel();
spawn(proc() { spawn(proc() {
@ -504,13 +527,79 @@ mod tests {
use std::comm; use std::comm;
use std::comm::{Empty, Data, Disconnected}; use std::comm::{Empty, Data, Disconnected};
fn mock_resource_task(on_load: proc(resource: Sender<resource_task::ProgressMsg>)) -> ResourceTask { trait Closure {
fn invoke(&self, response: Sender<resource_task::ProgressMsg>) { }
}
struct DoesNothing;
impl Closure for DoesNothing { }
struct JustSendOK {
url_requested_chan: Sender<()>,
}
impl Closure for JustSendOK {
fn invoke(&self, response: Sender<resource_task::ProgressMsg>) {
self.url_requested_chan.send(());
response.send(resource_task::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(())));
}
}
struct SendBogusImage;
impl Closure for SendBogusImage {
fn invoke(&self, response: Sender<resource_task::ProgressMsg>) {
response.send(resource_task::Payload(~[]));
response.send(resource_task::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(())));
}
}
struct WaitSendTestImage {
wait_port: Receiver<()>,
}
impl Closure for WaitSendTestImage {
fn invoke(&self, response: Sender<resource_task::ProgressMsg>) {
// 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(())));
}
}
struct WaitSendTestImageErr {
wait_port: Receiver<()>,
}
impl Closure for WaitSendTestImageErr {
fn invoke(&self, response: Sender<resource_task::ProgressMsg>) {
// 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(())));
}
}
fn mock_resource_task<T: Closure+Send>(on_load: ~T) -> ResourceTask {
spawn_listener(proc(port: Receiver<resource_task::ControlMsg>) { spawn_listener(proc(port: Receiver<resource_task::ControlMsg>) {
loop { loop {
match port.recv() { match port.recv() {
resource_task::Load(_, response) => { resource_task::Load(_, response) => {
let chan = start_sending(response, Metadata::default(parse_url("file:///fake", None))); let chan = start_sending(response, Metadata::default(parse_url("file:///fake", None)));
on_load(chan); on_load.invoke(chan);
} }
resource_task::Exit => break resource_task::Exit => break
} }
@ -520,7 +609,7 @@ mod tests {
#[test] #[test]
fn should_exit_on_request() { fn should_exit_on_request() {
let mock_resource_task = mock_resource_task(proc(_response) {}); let mock_resource_task = mock_resource_task(~DoesNothing);
let image_cache_task = ImageCacheTask(mock_resource_task.clone()); let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let _url = parse_url("file", None); let _url = parse_url("file", None);
@ -532,7 +621,7 @@ mod tests {
#[test] #[test]
#[should_fail] #[should_fail]
fn should_fail_if_unprefetched_image_is_requested() { fn should_fail_if_unprefetched_image_is_requested() {
let mock_resource_task = mock_resource_task(proc(_response) {}); let mock_resource_task = mock_resource_task(~DoesNothing);
let image_cache_task = ImageCacheTask(mock_resource_task.clone()); let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None); let url = parse_url("file", None);
@ -546,10 +635,7 @@ mod tests {
fn should_request_url_from_resource_task_on_prefetch() { fn should_request_url_from_resource_task_on_prefetch() {
let (url_requested_chan, url_requested) = channel(); let (url_requested_chan, url_requested) = channel();
let mock_resource_task = mock_resource_task(proc(response) { let mock_resource_task = mock_resource_task(~JustSendOK { url_requested_chan: url_requested_chan});
url_requested_chan.send(());
response.send(resource_task::Done(Ok(())));
});
let image_cache_task = ImageCacheTask(mock_resource_task.clone()); let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None); let url = parse_url("file", None);
@ -564,10 +650,7 @@ mod tests {
fn should_not_request_url_from_resource_task_on_multiple_prefetches() { fn should_not_request_url_from_resource_task_on_multiple_prefetches() {
let (url_requested_chan, url_requested) = comm::channel(); let (url_requested_chan, url_requested) = comm::channel();
let mock_resource_task = mock_resource_task(proc(response) { let mock_resource_task = mock_resource_task(~JustSendOK { url_requested_chan: url_requested_chan});
url_requested_chan.send(());
response.send(resource_task::Done(Ok(())));
});
let image_cache_task = ImageCacheTask(mock_resource_task.clone()); let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None); let url = parse_url("file", None);
@ -587,13 +670,7 @@ mod tests {
fn should_return_image_not_ready_if_data_has_not_arrived() { fn should_return_image_not_ready_if_data_has_not_arrived() {
let (wait_chan, wait_port) = comm::channel(); let (wait_chan, wait_port) = comm::channel();
let mock_resource_task = mock_resource_task(proc(response) { let mock_resource_task = mock_resource_task(~WaitSendTestImage{wait_port: wait_port});
// Don't send the data until after the client requests
// the image
wait_port.recv();
response.send(resource_task::Payload(test_image_bin()));
response.send(resource_task::Done(Ok(())));
});
let image_cache_task = ImageCacheTask(mock_resource_task.clone()); let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None); let url = parse_url("file", None);
@ -610,10 +687,7 @@ mod tests {
#[test] #[test]
fn should_return_decoded_image_data_if_data_has_arrived() { fn should_return_decoded_image_data_if_data_has_arrived() {
let mock_resource_task = mock_resource_task(proc(response) { let mock_resource_task = mock_resource_task(~SendTestImage);
response.send(resource_task::Payload(test_image_bin()));
response.send(resource_task::Done(Ok(())));
});
let image_cache_task = ImageCacheTask(mock_resource_task.clone()); let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None); let url = parse_url("file", None);
@ -639,10 +713,7 @@ mod tests {
#[test] #[test]
fn should_return_decoded_image_data_for_multiple_requests() { fn should_return_decoded_image_data_for_multiple_requests() {
let mock_resource_task = mock_resource_task(proc(response) { let mock_resource_task = mock_resource_task(~SendTestImage);
response.send(resource_task::Payload(test_image_bin()));
response.send(resource_task::Done(Ok(())));
});
let image_cache_task = ImageCacheTask(mock_resource_task.clone()); let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None); let url = parse_url("file", None);
@ -764,11 +835,7 @@ mod tests {
#[test] #[test]
fn should_return_failed_if_image_bin_cannot_be_fetched() { fn should_return_failed_if_image_bin_cannot_be_fetched() {
let mock_resource_task = mock_resource_task(proc(response) { let mock_resource_task = mock_resource_task(~SendTestImageErr);
response.send(resource_task::Payload(test_image_bin()));
// ERROR fetching image
response.send(resource_task::Done(Err(())));
});
let image_cache_task = ImageCacheTask(mock_resource_task.clone()); let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None); let url = parse_url("file", None);
@ -794,11 +861,7 @@ mod tests {
#[test] #[test]
fn should_return_failed_for_multiple_get_image_requests_if_image_bin_cannot_be_fetched() { fn should_return_failed_for_multiple_get_image_requests_if_image_bin_cannot_be_fetched() {
let mock_resource_task = mock_resource_task(proc(response) { let mock_resource_task = mock_resource_task(~SendTestImageErr);
response.send(resource_task::Payload(test_image_bin()));
// ERROR fetching image
response.send(resource_task::Done(Err(())));
});
let image_cache_task = ImageCacheTask(mock_resource_task.clone()); let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None); let url = parse_url("file", None);
@ -832,11 +895,7 @@ mod tests {
#[test] #[test]
fn should_return_failed_if_image_decode_fails() { fn should_return_failed_if_image_decode_fails() {
let mock_resource_task = mock_resource_task(proc(response) { let mock_resource_task = mock_resource_task(~SendBogusImage);
// Bogus data
response.send(resource_task::Payload(~[]));
response.send(resource_task::Done(Ok(())));
});
let image_cache_task = ImageCacheTask(mock_resource_task.clone()); let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None); let url = parse_url("file", None);
@ -864,10 +923,7 @@ mod tests {
#[test] #[test]
fn should_return_image_on_wait_if_image_is_already_loaded() { fn should_return_image_on_wait_if_image_is_already_loaded() {
let mock_resource_task = mock_resource_task(proc(response) { let mock_resource_task = mock_resource_task(~SendTestImage);
response.send(resource_task::Payload(test_image_bin()));
response.send(resource_task::Done(Ok(())));
});
let image_cache_task = ImageCacheTask(mock_resource_task.clone()); let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None); let url = parse_url("file", None);
@ -895,11 +951,7 @@ mod tests {
fn should_return_image_on_wait_if_image_is_not_yet_loaded() { fn should_return_image_on_wait_if_image_is_not_yet_loaded() {
let (wait_chan, wait_port) = comm::channel(); let (wait_chan, wait_port) = comm::channel();
let mock_resource_task = mock_resource_task(proc(response) { let mock_resource_task = mock_resource_task(~WaitSendTestImage {wait_port: wait_port});
wait_port.recv();
response.send(resource_task::Payload(test_image_bin()));
response.send(resource_task::Done(Ok(())));
});
let image_cache_task = ImageCacheTask(mock_resource_task.clone()); let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None); let url = parse_url("file", None);
@ -925,11 +977,7 @@ mod tests {
fn should_return_image_failed_on_wait_if_image_fails_to_load() { fn should_return_image_failed_on_wait_if_image_fails_to_load() {
let (wait_chan, wait_port) = comm::channel(); let (wait_chan, wait_port) = comm::channel();
let mock_resource_task = mock_resource_task(proc(response) { let mock_resource_task = mock_resource_task(~WaitSendTestImageErr{wait_port: wait_port});
wait_port.recv();
response.send(resource_task::Payload(test_image_bin()));
response.send(resource_task::Done(Err(())));
});
let image_cache_task = ImageCacheTask(mock_resource_task.clone()); let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None); let url = parse_url("file", None);
@ -953,10 +1001,7 @@ mod tests {
#[test] #[test]
fn sync_cache_should_wait_for_images() { fn sync_cache_should_wait_for_images() {
let mock_resource_task = mock_resource_task(proc(response) { let mock_resource_task = mock_resource_task(~SendTestImage);
response.send(resource_task::Payload(test_image_bin()));
response.send(resource_task::Done(Ok(())));
});
let image_cache_task = SyncImageCacheTask(mock_resource_task.clone()); let image_cache_task = SyncImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None); let url = parse_url("file", None);

View file

@ -17,7 +17,7 @@ use servo_util::task::spawn_named;
use url::Url; use url::Url;
pub trait ImageResponder { pub trait ImageResponder {
fn respond(&self) -> proc(ImageResponseMsg); fn respond(&self) -> proc(ImageResponseMsg):Send;
} }
pub fn LocalImageCache(image_cache_task: ImageCacheTask) -> LocalImageCache { pub fn LocalImageCache(image_cache_task: ImageCacheTask) -> LocalImageCache {
@ -30,10 +30,10 @@ pub fn LocalImageCache(image_cache_task: ImageCacheTask) -> LocalImageCache {
} }
pub struct LocalImageCache { pub struct LocalImageCache {
priv image_cache_task: ImageCacheTask, image_cache_task: ImageCacheTask,
priv round_number: uint, round_number: uint,
priv on_image_available: Option<~ImageResponder:Send>, on_image_available: Option<~ImageResponder:Send>,
priv state_map: UrlMap<ImageState> state_map: UrlMap<ImageState>
} }
#[deriving(Clone)] #[deriving(Clone)]
@ -124,7 +124,7 @@ impl LocalImageCache {
// on the image to load and triggering layout // on the image to load and triggering layout
let image_cache_task = self.image_cache_task.clone(); let image_cache_task = self.image_cache_task.clone();
assert!(self.on_image_available.is_some()); assert!(self.on_image_available.is_some());
let on_image_available = self.on_image_available.as_ref().unwrap().respond(); let on_image_available: proc(ImageResponseMsg):Send = self.on_image_available.as_ref().unwrap().respond();
let url = (*url).clone(); let url = (*url).clone();
spawn_named("LocalImageCache", proc() { spawn_named("LocalImageCache", proc() {
let (response_chan, response_port) = channel(); let (response_chan, response_port) = channel();
@ -161,4 +161,3 @@ impl LocalImageCache {
state state
} }
} }

View file

@ -2,24 +2,22 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#[crate_id = "github.com/mozilla/servo#net:0.1"]; #![crate_id = "github.com/mozilla/servo#net:0.1"]
#[crate_type = "lib"]; #![crate_type = "lib"]
#[crate_type = "dylib"]; #![crate_type = "dylib"]
#[crate_type = "rlib"]; #![crate_type = "rlib"]
#[feature(globs)]; #![feature(default_type_params, globs, managed_boxes, phase)]
#[feature(phase)];
#[phase(syntax, link)]
extern crate log;
extern crate collections; extern crate collections;
extern crate geom; extern crate geom;
extern crate http; extern crate http;
extern crate png;
#[phase(syntax, link)]
extern crate log;
extern crate serialize;
extern crate servo_util = "util"; extern crate servo_util = "util";
extern crate stb_image; extern crate stb_image;
extern crate png;
extern crate serialize;
extern crate sync; extern crate sync;
extern crate url; extern crate url;

View file

@ -25,13 +25,13 @@ pub enum ControlMsg {
/// Metadata about a loaded resource, such as is obtained from HTTP headers. /// Metadata about a loaded resource, such as is obtained from HTTP headers.
pub struct Metadata { pub struct Metadata {
/// Final URL after redirects. /// Final URL after redirects.
final_url: Url, pub final_url: Url,
/// MIME type / subtype. /// MIME type / subtype.
content_type: Option<(~str, ~str)>, pub content_type: Option<(~str, ~str)>,
/// Character set. /// Character set.
charset: Option<~str>, pub charset: Option<~str>,
} }
impl Metadata { impl Metadata {
@ -69,9 +69,9 @@ impl Metadata {
/// progress_port will provide the error. /// progress_port will provide the error.
pub struct LoadResponse { pub struct LoadResponse {
/// Metadata, such as from HTTP headers. /// Metadata, such as from HTTP headers.
metadata: Metadata, pub metadata: Metadata,
/// Port for reading data. /// Port for reading data.
progress_port: Receiver<ProgressMsg>, pub progress_port: Receiver<ProgressMsg>,
} }
/// Messages sent in response to a `Load` message /// Messages sent in response to a `Load` message

View file

@ -21,15 +21,15 @@ pub enum AttrSettingType {
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct Attr { pub struct Attr {
reflector_: Reflector, pub reflector_: Reflector,
local_name: DOMString, pub local_name: DOMString,
value: DOMString, pub value: DOMString,
name: DOMString, pub name: DOMString,
namespace: Namespace, pub namespace: Namespace,
prefix: Option<DOMString>, pub prefix: Option<DOMString>,
/// the element that owns this attribute. /// the element that owns this attribute.
owner: JS<Element>, pub owner: JS<Element>,
} }
impl Reflectable for Attr { impl Reflectable for Attr {

View file

@ -11,9 +11,9 @@ use dom::window::Window;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct AttrList { pub struct AttrList {
reflector_: Reflector, pub reflector_: Reflector,
window: JS<Window>, pub window: JS<Window>,
owner: JS<Element>, pub owner: JS<Element>,
} }
impl AttrList { impl AttrList {

View file

@ -8,8 +8,8 @@ use js::jsapi::{JS_GetProperty, JSTracer, JS_CallTracer};
use js::jsval::{JSVal, UndefinedValue}; use js::jsval::{JSVal, UndefinedValue};
use js::JSTRACE_OBJECT; use js::JSTRACE_OBJECT;
use libc;
use std::cast; use std::cast;
use std::libc;
use std::ptr; use std::ptr;
use serialize::{Encodable, Encoder}; use serialize::{Encodable, Encoder};
@ -27,11 +27,11 @@ pub enum ExceptionHandling {
#[deriving(Clone,Eq)] #[deriving(Clone,Eq)]
pub struct CallbackInterface { pub struct CallbackInterface {
callback: *JSObject pub callback: *JSObject
} }
impl<S: Encoder> Encodable<S> for CallbackInterface { impl<S: Encoder<E>, E> Encodable<S, E> for CallbackInterface {
fn encode(&self, s: &mut S) { fn encode(&self, s: &mut S) -> Result<(), E> {
unsafe { unsafe {
let tracer: *mut JSTracer = cast::transmute(s); let tracer: *mut JSTracer = cast::transmute(s);
"callback".to_c_str().with_ref(|name| { "callback".to_c_str().with_ref(|name| {
@ -40,7 +40,8 @@ impl<S: Encoder> Encodable<S> for CallbackInterface {
(*tracer).debugPrintArg = name as *libc::c_void; (*tracer).debugPrintArg = name as *libc::c_void;
JS_CallTracer(tracer as *JSTracer, self.callback, JSTRACE_OBJECT as u32); JS_CallTracer(tracer as *JSTracer, self.callback, JSTRACE_OBJECT as u32);
}); });
} };
Ok(())
} }
} }
@ -98,8 +99,8 @@ pub fn WrapCallThisObject<T: 'static + CallbackContainer + Reflectable>(cx: *JSC
} }
pub struct CallSetup { pub struct CallSetup {
cx: *JSContext, pub cx: *JSContext,
handling: ExceptionHandling pub handling: ExceptionHandling
} }
impl CallSetup { impl CallSetup {

View file

@ -1394,7 +1394,7 @@ class CGImports(CGWrapper):
'dead_code', 'dead_code',
] ]
statements = ['#[allow(%s)];' % ','.join(ignored_warnings)] statements = ['#![allow(%s)]' % ','.join(ignored_warnings)]
statements.extend('use %s;' % i for i in sorted(imports)) statements.extend('use %s;' % i for i in sorted(imports))
CGWrapper.__init__(self, child, CGWrapper.__init__(self, child,
@ -4076,11 +4076,11 @@ class CGDictionary(CGThing):
def struct(self): def struct(self):
d = self.dictionary d = self.dictionary
if d.parent: if d.parent:
inheritance = " parent: %s::%s,\n" % (self.makeModuleName(d.parent), inheritance = " pub parent: %s::%s,\n" % (self.makeModuleName(d.parent),
self.makeClassName(d.parent)) self.makeClassName(d.parent))
else: else:
inheritance = "" inheritance = ""
memberDecls = [" %s: %s," % memberDecls = [" pub %s: %s," %
(self.makeMemberName(m[0].identifier.name), self.getMemberType(m)) (self.makeMemberName(m[0].identifier.name), self.getMemberType(m))
for m in self.memberInfo] for m in self.memberInfo]
@ -4344,11 +4344,11 @@ class CGBindingRoot(CGThing):
'dom::bindings::proxyhandler::{_obj_toString, defineProperty}', 'dom::bindings::proxyhandler::{_obj_toString, defineProperty}',
'dom::bindings::proxyhandler::{FillPropertyDescriptor, GetExpandoObject}', 'dom::bindings::proxyhandler::{FillPropertyDescriptor, GetExpandoObject}',
'dom::bindings::proxyhandler::{getPropertyDescriptor}', 'dom::bindings::proxyhandler::{getPropertyDescriptor}',
'libc',
'servo_util::str::DOMString', 'servo_util::str::DOMString',
'servo_util::vec::zip_copies', 'servo_util::vec::zip_copies',
'std::cast', 'std::cast',
'std::cmp', 'std::cmp',
'std::libc',
'std::ptr', 'std::ptr',
'std::slice', 'std::slice',
'std::str', 'std::str',
@ -5282,7 +5282,7 @@ class GlobalGenRoots():
def InheritTypes(config): def InheritTypes(config):
descriptors = config.getDescriptors(register=True, hasInterfaceObject=True) descriptors = config.getDescriptors(register=True, hasInterfaceObject=True)
allprotos = [CGGeneric("#[allow(unused_imports)];\n"), allprotos = [CGGeneric("#![allow(unused_imports)]\n"),
CGGeneric("use dom::types::*;\n"), CGGeneric("use dom::types::*;\n"),
CGGeneric("use dom::bindings::js::JS;\n"), CGGeneric("use dom::bindings::js::JS;\n"),
CGGeneric("use dom::bindings::trace::JSTraceable;\n"), CGGeneric("use dom::bindings::trace::JSTraceable;\n"),

View file

@ -18,8 +18,8 @@ use js::jsval::JSVal;
use js::jsval::{UndefinedValue, NullValue, BooleanValue, Int32Value, UInt32Value}; use js::jsval::{UndefinedValue, NullValue, BooleanValue, Int32Value, UInt32Value};
use js::jsval::{StringValue, ObjectValue}; use js::jsval::{StringValue, ObjectValue};
use js::glue::RUST_JS_NumberValue; use js::glue::RUST_JS_NumberValue;
use libc;
use std::default::Default; use std::default::Default;
use std::libc;
use dom::bindings::codegen::PrototypeList; use dom::bindings::codegen::PrototypeList;

View file

@ -11,7 +11,7 @@ use std::cast;
use std::cell::RefCell; use std::cell::RefCell;
pub struct JS<T> { pub struct JS<T> {
priv ptr: RefCell<*mut T> ptr: RefCell<*mut T>
} }
impl<T> Eq for JS<T> { impl<T> Eq for JS<T> {

View file

@ -13,8 +13,8 @@ use js::glue::{GetObjectProto, GetObjectParent, SetProxyExtra, GetProxyHandler};
use js::glue::InvokeGetOwnPropertyDescriptor; use js::glue::InvokeGetOwnPropertyDescriptor;
use js::{JSPROP_GETTER, JSPROP_ENUMERATE, JSPROP_READONLY, JSRESOLVE_QUALIFIED}; use js::{JSPROP_GETTER, JSPROP_ENUMERATE, JSPROP_READONLY, JSRESOLVE_QUALIFIED};
use libc;
use std::cast; use std::cast;
use std::libc;
use std::ptr; use std::ptr;
use std::str; use std::str;
use std::mem::size_of; use std::mem::size_of;

View file

@ -7,9 +7,9 @@ use dom::bindings::utils::{Reflectable, Reflector};
use js::jsapi::{JSObject, JSTracer, JS_CallTracer, JSTRACE_OBJECT}; use js::jsapi::{JSObject, JSTracer, JS_CallTracer, JSTRACE_OBJECT};
use libc;
use std::cast; use std::cast;
use std::cell::RefCell; use std::cell::RefCell;
use std::libc;
use std::ptr; use std::ptr;
use std::ptr::null; use std::ptr::null;
use serialize::{Encodable, Encoder}; use serialize::{Encodable, Encoder};
@ -19,20 +19,22 @@ use serialize::{Encodable, Encoder};
// we are unfortunately required to use generic types everywhere and // we are unfortunately required to use generic types everywhere and
// unsafely cast to the concrete JSTracer we actually require. // unsafely cast to the concrete JSTracer we actually require.
fn get_jstracer<'a, S: Encoder>(s: &'a mut S) -> &'a mut JSTracer { fn get_jstracer<'a, S: Encoder<E>, E>(s: &'a mut S) -> &'a mut JSTracer {
unsafe { unsafe {
cast::transmute(s) cast::transmute(s)
} }
} }
impl<T: Reflectable+Encodable<S>, S: Encoder> Encodable<S> for JS<T> { impl<T: Reflectable+Encodable<S, E>, S: Encoder<E>, E> Encodable<S, E> for JS<T> {
fn encode(&self, s: &mut S) { fn encode(&self, s: &mut S) -> Result<(), E> {
trace_reflector(get_jstracer(s), "", self.reflector()); trace_reflector(get_jstracer(s), "", self.reflector());
Ok(())
} }
} }
impl<S: Encoder> Encodable<S> for Reflector { impl<S: Encoder<E>, E> Encodable<S, E> for Reflector {
fn encode(&self, _s: &mut S) { fn encode(&self, _s: &mut S) -> Result<(), E> {
Ok(())
} }
} }
@ -61,7 +63,7 @@ pub fn trace_object(tracer: *mut JSTracer, description: &str, obj: *JSObject) {
/// Use only with types that are not associated with a JS reflector and do not contain /// Use only with types that are not associated with a JS reflector and do not contain
/// fields of types associated with JS reflectors. /// fields of types associated with JS reflectors.
pub struct Untraceable<T> { pub struct Untraceable<T> {
priv inner: T, inner: T,
} }
impl<T> Untraceable<T> { impl<T> Untraceable<T> {
@ -72,8 +74,9 @@ impl<T> Untraceable<T> {
} }
} }
impl<S: Encoder, T> Encodable<S> for Untraceable<T> { impl<S: Encoder<E>, E, T> Encodable<S, E> for Untraceable<T> {
fn encode(&self, _s: &mut S) { fn encode(&self, _s: &mut S) -> Result<(), E> {
Ok(())
} }
} }
@ -93,7 +96,7 @@ impl<T> DerefMut<T> for Untraceable<T> {
/// (such as RefCell). Wrap a field in Traceable and implement the Encodable trait /// (such as RefCell). Wrap a field in Traceable and implement the Encodable trait
/// for that new concrete type to achieve magic compiler-derived trace hooks. /// for that new concrete type to achieve magic compiler-derived trace hooks.
pub struct Traceable<T> { pub struct Traceable<T> {
priv inner: T inner: T
} }
impl<T> Traceable<T> { impl<T> Traceable<T> {
@ -116,14 +119,16 @@ impl<T> DerefMut<T> for Traceable<T> {
} }
} }
impl<S: Encoder, T: Encodable<S>> Encodable<S> for Traceable<RefCell<T>> { impl<S: Encoder<E>, E, T: Encodable<S, E>> Encodable<S, E> for Traceable<RefCell<T>> {
fn encode(&self, s: &mut S) { fn encode(&self, s: &mut S) -> Result<(), E> {
self.borrow().encode(s) self.borrow().encode(s);
Ok(())
} }
} }
impl<S: Encoder> Encodable<S> for Traceable<*JSObject> { impl<S: Encoder<E>, E> Encodable<S, E> for Traceable<*JSObject> {
fn encode(&self, s: &mut S) { fn encode(&self, s: &mut S) -> Result<(), E> {
trace_object(get_jstracer(s), "object", **self) trace_object(get_jstracer(s), "object", **self);
Ok(())
} }
} }

View file

@ -12,10 +12,10 @@ use dom::window;
use servo_util::str::DOMString; use servo_util::str::DOMString;
use collections::hashmap::HashMap; use collections::hashmap::HashMap;
use std::libc::c_uint; use libc;
use libc::c_uint;
use std::cast; use std::cast;
use std::cmp::Eq; use std::cmp::Eq;
use std::libc;
use std::ptr; use std::ptr;
use std::ptr::null; use std::ptr::null;
use std::slice; use std::slice;
@ -49,8 +49,8 @@ use js;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct GlobalStaticData { pub struct GlobalStaticData {
proxy_handlers: Untraceable<HashMap<uint, *libc::c_void>>, pub proxy_handlers: Untraceable<HashMap<uint, *libc::c_void>>,
windowproxy_handler: Untraceable<*libc::c_void>, pub windowproxy_handler: Untraceable<*libc::c_void>,
} }
pub fn GlobalStaticData() -> GlobalStaticData { pub fn GlobalStaticData() -> GlobalStaticData {
@ -190,19 +190,19 @@ pub enum ConstantVal {
#[deriving(Clone)] #[deriving(Clone)]
pub struct ConstantSpec { pub struct ConstantSpec {
name: *libc::c_char, pub name: *libc::c_char,
value: ConstantVal pub value: ConstantVal
} }
pub struct DOMClass { pub struct DOMClass {
// A list of interfaces that this object implements, in order of decreasing // A list of interfaces that this object implements, in order of decreasing
// derivedness. // derivedness.
interface_chain: [PrototypeList::id::ID, ..MAX_PROTO_CHAIN_LENGTH] pub interface_chain: [PrototypeList::id::ID, ..MAX_PROTO_CHAIN_LENGTH]
} }
pub struct DOMJSClass { pub struct DOMJSClass {
base: js::Class, pub base: js::Class,
dom_class: DOMClass pub dom_class: DOMClass
} }
pub fn GetProtoOrIfaceArray(global: *JSObject) -> **JSObject { pub fn GetProtoOrIfaceArray(global: *JSObject) -> **JSObject {
@ -398,7 +398,7 @@ pub fn reflect_dom_object<T: Reflectable>
#[deriving(Eq)] #[deriving(Eq)]
pub struct Reflector { pub struct Reflector {
object: *JSObject, pub object: *JSObject,
} }
impl Reflector { impl Reflector {
@ -509,8 +509,8 @@ pub fn FindEnumStringIndex(cx: *JSContext,
Ok(values.iter().position(|value| { Ok(values.iter().position(|value| {
value.len() == length as uint && value.len() == length as uint &&
range(0, length as int).all(|j| { range(0, length as uint).all(|j| {
value[j] as u16 == *chars.offset(j) value[j] as u16 == *chars.offset(j as int)
}) })
})) }))
} }

View file

@ -11,8 +11,8 @@ use servo_util::str::DOMString;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct Blob { pub struct Blob {
reflector_: Reflector, pub reflector_: Reflector,
window: JS<Window> pub window: JS<Window>
} }
impl Blob { impl Blob {

View file

@ -11,14 +11,14 @@ use dom::window::Window;
use js::jsapi::JSObject; use js::jsapi::JSObject;
use js::glue::{WrapperNew, CreateWrapperProxyHandler, ProxyTraps}; use js::glue::{WrapperNew, CreateWrapperProxyHandler, ProxyTraps};
use std::libc::c_void; use libc::c_void;
use std::ptr; use std::ptr;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct BrowserContext { pub struct BrowserContext {
priv history: Vec<SessionHistoryEntry>, history: Vec<SessionHistoryEntry>,
priv active_index: uint, active_index: uint,
priv window_proxy: Traceable<*JSObject>, window_proxy: Traceable<*JSObject>,
} }
impl BrowserContext { impl BrowserContext {
@ -66,8 +66,8 @@ impl BrowserContext {
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct SessionHistoryEntry { pub struct SessionHistoryEntry {
priv document: JS<Document>, document: JS<Document>,
priv children: Vec<BrowserContext> children: Vec<BrowserContext>
} }
impl SessionHistoryEntry { impl SessionHistoryEntry {

View file

@ -15,8 +15,8 @@ use servo_util::str::DOMString;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct CharacterData { pub struct CharacterData {
node: Node, pub node: Node,
data: DOMString, pub data: DOMString,
} }
impl CharacterDataDerived for EventTarget { impl CharacterDataDerived for EventTarget {

View file

@ -10,12 +10,12 @@ use servo_util::geometry::Au;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct ClientRect { pub struct ClientRect {
reflector_: Reflector, pub reflector_: Reflector,
top: f32, pub top: f32,
bottom: f32, pub bottom: f32,
left: f32, pub left: f32,
right: f32, pub right: f32,
window: JS<Window>, pub window: JS<Window>,
} }
impl ClientRect { impl ClientRect {

View file

@ -10,9 +10,9 @@ use dom::window::Window;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct ClientRectList { pub struct ClientRectList {
reflector_: Reflector, pub reflector_: Reflector,
rects: ~[JS<ClientRect>], pub rects: ~[JS<ClientRect>],
window: JS<Window>, pub window: JS<Window>,
} }
impl ClientRectList { impl ClientRectList {
@ -37,7 +37,7 @@ impl ClientRectList {
pub fn Item(&self, index: u32) -> Option<JS<ClientRect>> { pub fn Item(&self, index: u32) -> Option<JS<ClientRect>> {
if index < self.rects.len() as u32 { if index < self.rects.len() as u32 {
Some(self.rects[index].clone()) Some(self.rects[index as uint].clone())
} else { } else {
None None
} }

View file

@ -16,7 +16,7 @@ use servo_util::str::DOMString;
/// An HTML comment. /// An HTML comment.
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct Comment { pub struct Comment {
characterdata: CharacterData, pub characterdata: CharacterData,
} }
impl CommentDerived for EventTarget { impl CommentDerived for EventTarget {

View file

@ -10,7 +10,7 @@ use servo_util::str::DOMString;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct Console { pub struct Console {
reflector_: Reflector pub reflector_: Reflector
} }
impl Console { impl Console {

View file

@ -55,16 +55,16 @@ pub enum IsHTMLDocument {
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct Document { pub struct Document {
node: Node, pub node: Node,
reflector_: Reflector, pub reflector_: Reflector,
window: JS<Window>, pub window: JS<Window>,
idmap: HashMap<DOMString, ~[JS<Element>]>, pub idmap: HashMap<DOMString, ~[JS<Element>]>,
implementation: Option<JS<DOMImplementation>>, pub implementation: Option<JS<DOMImplementation>>,
content_type: DOMString, pub content_type: DOMString,
encoding_name: DOMString, pub encoding_name: DOMString,
is_html_document: bool, pub is_html_document: bool,
url: Untraceable<Url>, pub url: Untraceable<Url>,
quirks_mode: Untraceable<QuirksMode>, pub quirks_mode: Untraceable<QuirksMode>,
} }
impl DocumentDerived for EventTarget { impl DocumentDerived for EventTarget {

View file

@ -14,7 +14,7 @@ use dom::window::Window;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct DocumentFragment { pub struct DocumentFragment {
node: Node, pub node: Node,
} }
impl DocumentFragmentDerived for EventTarget { impl DocumentFragmentDerived for EventTarget {

View file

@ -13,10 +13,10 @@ use servo_util::str::DOMString;
/// The `DOCTYPE` tag. /// The `DOCTYPE` tag.
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct DocumentType { pub struct DocumentType {
node: Node, pub node: Node,
name: DOMString, pub name: DOMString,
public_id: DOMString, pub public_id: DOMString,
system_id: DOMString, pub system_id: DOMString,
} }
impl DocumentTypeDerived for EventTarget { impl DocumentTypeDerived for EventTarget {

View file

@ -37,8 +37,8 @@ pub enum DOMErrorName {
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct DOMException { pub struct DOMException {
code: DOMErrorName, pub code: DOMErrorName,
reflector_: Reflector pub reflector_: Reflector
} }
impl DOMException { impl DOMException {

View file

@ -21,8 +21,8 @@ use servo_util::str::DOMString;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct DOMImplementation { pub struct DOMImplementation {
owner: JS<Window>, pub owner: JS<Window>,
reflector_: Reflector, pub reflector_: Reflector,
} }
impl DOMImplementation { impl DOMImplementation {

View file

@ -13,8 +13,8 @@ use servo_util::str::DOMString;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct DOMParser { pub struct DOMParser {
owner: JS<Window>, //XXXjdm Document instead? pub owner: JS<Window>, //XXXjdm Document instead?
reflector_: Reflector pub reflector_: Reflector
} }
impl DOMParser { impl DOMParser {

View file

@ -32,13 +32,13 @@ use std::cast;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct Element { pub struct Element {
node: Node, pub node: Node,
local_name: DOMString, // TODO: This should be an atom, not a DOMString. pub local_name: DOMString, // TODO: This should be an atom, not a DOMString.
namespace: Namespace, pub namespace: Namespace,
prefix: Option<DOMString>, pub prefix: Option<DOMString>,
attrs: ~[JS<Attr>], pub attrs: ~[JS<Attr>],
style_attribute: Option<style::PropertyDeclarationBlock>, pub style_attribute: Option<style::PropertyDeclarationBlock>,
attr_list: Option<JS<AttrList>> pub attr_list: Option<JS<AttrList>>
} }
impl ElementDerived for EventTarget { impl ElementDerived for EventTarget {
@ -605,14 +605,14 @@ impl Element {
let win = &doc.get().window; let win = &doc.get().window;
let node: JS<Node> = NodeCast::from(abstract_self); let node: JS<Node> = NodeCast::from(abstract_self);
let rects = node.get_content_boxes(); let rects = node.get_content_boxes();
let rects = rects.map(|r| { let rects = rects.iter().map(|r| {
ClientRect::new( ClientRect::new(
win, win,
r.origin.y, r.origin.y,
r.origin.y + r.size.height, r.origin.y + r.size.height,
r.origin.x, r.origin.x,
r.origin.x + r.size.width) r.origin.x + r.size.width)
}); }).collect();
ClientRectList::new(win, rects) ClientRectList::new(win, rects)
} }

View file

@ -40,20 +40,20 @@ pub enum EventTypeId {
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct Event { pub struct Event {
type_id: EventTypeId, pub type_id: EventTypeId,
reflector_: Reflector, pub reflector_: Reflector,
current_target: Option<JS<EventTarget>>, pub current_target: Option<JS<EventTarget>>,
target: Option<JS<EventTarget>>, pub target: Option<JS<EventTarget>>,
type_: DOMString, pub type_: DOMString,
phase: EventPhase, pub phase: EventPhase,
canceled: bool, pub canceled: bool,
stop_propagation: bool, pub stop_propagation: bool,
stop_immediate: bool, pub stop_immediate: bool,
cancelable: bool, pub cancelable: bool,
bubbles: bool, pub bubbles: bool,
trusted: bool, pub trusted: bool,
dispatching: bool, pub dispatching: bool,
initialized: bool, pub initialized: bool,
} }
impl Event { impl Event {

View file

@ -29,15 +29,15 @@ pub enum EventTargetTypeId {
#[deriving(Eq,Encodable)] #[deriving(Eq,Encodable)]
pub struct EventListenerEntry { pub struct EventListenerEntry {
phase: ListenerPhase, pub phase: ListenerPhase,
listener: EventListener pub listener: EventListener
} }
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct EventTarget { pub struct EventTarget {
type_id: EventTargetTypeId, pub type_id: EventTargetTypeId,
reflector_: Reflector, pub reflector_: Reflector,
handlers: HashMap<DOMString, ~[EventListenerEntry]>, pub handlers: HashMap<DOMString, ~[EventListenerEntry]>,
} }
impl EventTarget { impl EventTarget {

View file

@ -21,10 +21,10 @@ pub enum FormDatum {
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct FormData { pub struct FormData {
data: HashMap<DOMString, FormDatum>, pub data: HashMap<DOMString, FormDatum>,
reflector_: Reflector, pub reflector_: Reflector,
window: JS<Window>, pub window: JS<Window>,
form: Option<JS<HTMLFormElement>> pub form: Option<JS<HTMLFormElement>>
} }
impl FormData { impl FormData {

View file

@ -15,7 +15,7 @@ use servo_util::str::DOMString;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct HTMLAnchorElement { pub struct HTMLAnchorElement {
htmlelement: HTMLElement pub htmlelement: HTMLElement
} }
impl HTMLAnchorElementDerived for EventTarget { impl HTMLAnchorElementDerived for EventTarget {

View file

@ -15,7 +15,7 @@ use servo_util::str::DOMString;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct HTMLAppletElement { pub struct HTMLAppletElement {
htmlelement: HTMLElement pub htmlelement: HTMLElement
} }
impl HTMLAppletElementDerived for EventTarget { impl HTMLAppletElementDerived for EventTarget {

View file

@ -15,7 +15,7 @@ use servo_util::str::DOMString;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct HTMLAreaElement { pub struct HTMLAreaElement {
htmlelement: HTMLElement pub htmlelement: HTMLElement
} }
impl HTMLAreaElementDerived for EventTarget { impl HTMLAreaElementDerived for EventTarget {

View file

@ -14,7 +14,7 @@ use servo_util::str::DOMString;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct HTMLAudioElement { pub struct HTMLAudioElement {
htmlmediaelement: HTMLMediaElement pub htmlmediaelement: HTMLMediaElement
} }
impl HTMLAudioElementDerived for EventTarget { impl HTMLAudioElementDerived for EventTarget {

View file

@ -15,7 +15,7 @@ use servo_util::str::DOMString;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct HTMLBaseElement { pub struct HTMLBaseElement {
htmlelement: HTMLElement pub htmlelement: HTMLElement
} }
impl HTMLBaseElementDerived for EventTarget { impl HTMLBaseElementDerived for EventTarget {

View file

@ -15,7 +15,7 @@ use servo_util::str::DOMString;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct HTMLBodyElement { pub struct HTMLBodyElement {
htmlelement: HTMLElement pub htmlelement: HTMLElement
} }
impl HTMLBodyElementDerived for EventTarget { impl HTMLBodyElementDerived for EventTarget {

View file

@ -15,7 +15,7 @@ use servo_util::str::DOMString;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct HTMLBRElement { pub struct HTMLBRElement {
htmlelement: HTMLElement, pub htmlelement: HTMLElement,
} }
impl HTMLBRElementDerived for EventTarget { impl HTMLBRElementDerived for EventTarget {

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