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
servo: $(DEPS_servo)
@$(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
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.
# 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.
2014-03-23
2014-04-10b

View file

@ -15,7 +15,7 @@ use std::mem;
/// needs it.
pub struct BufferMap<T> {
/// 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.
mem: uint,
/// 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.
#[deriving(TotalEq)]
struct BufferKey([uint, ..2]);
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
impl BufferKey {
fn get(input: Size2D<uint>) -> BufferKey {

View file

@ -19,11 +19,11 @@ use render_context::RenderContext;
use text::TextRun;
use geom::{Point2D, Rect, SideOffsets2D, Size2D};
use libc::uintptr_t;
use servo_net::image::base::Image;
use servo_util::geometry::Au;
use servo_util::range::Range;
use servo_util::smallvec::{SmallVec, SmallVec0, SmallVecIterator};
use std::libc::uintptr_t;
use std::mem;
use std::slice::Items;
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
/// locality reasons. Using `OpaqueNode` enforces this invariant.
#[deriving(Clone, Eq)]
pub struct OpaqueNode(uintptr_t);
pub struct OpaqueNode(pub uintptr_t);
impl OpaqueNode {
/// Returns the address of this node, for debugging purposes.
@ -52,20 +52,20 @@ impl OpaqueNode {
/// TODO(pcwalton): Outlines.
pub struct StackingContext {
/// 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.
block_backgrounds_and_borders: DisplayList,
pub block_backgrounds_and_borders: DisplayList,
/// Floats: step 5. These are treated as pseudo-stacking contexts.
floats: DisplayList,
pub floats: DisplayList,
/// All other content.
content: DisplayList,
pub content: DisplayList,
/// 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
/// `auto`, not just an integer. In this case we should store an actual stacking context, not
/// a flattened display list.
positioned_descendants: SmallVec0<(int, DisplayList)>,
pub positioned_descendants: SmallVec0<(int, DisplayList)>,
}
impl StackingContext {
@ -143,7 +143,7 @@ pub enum BackgroundAndBorderLevel {
/// A list of rendering operations to be performed.
pub struct DisplayList {
list: SmallVec0<DisplayItem>,
pub list: SmallVec0<DisplayItem>,
}
pub enum DisplayListIterator<'a> {
@ -216,43 +216,43 @@ pub struct BaseDisplayItem {
/// The boundaries of the display item.
///
/// TODO: Which coordinate system should this use?
bounds: Rect<Au>,
pub bounds: Rect<Au>,
/// The originating DOM node.
node: OpaqueNode,
pub node: OpaqueNode,
}
/// Renders a solid color.
pub struct SolidColorDisplayItem {
base: BaseDisplayItem,
color: Color,
pub base: BaseDisplayItem,
pub color: Color,
}
/// Renders text.
pub struct TextDisplayItem {
/// Fields common to all display items.
base: BaseDisplayItem,
pub base: BaseDisplayItem,
/// The text run.
text_run: Arc<~TextRun>,
pub text_run: Arc<~TextRun>,
/// The range of text within the text run.
range: Range,
pub range: Range,
/// The color of the text.
text_color: Color,
pub text_color: Color,
/// A bitfield of flags for text display items.
flags: TextDisplayItemFlags,
pub flags: TextDisplayItemFlags,
/// The color of text-decorations
underline_color: Color,
overline_color: Color,
line_through_color: Color,
pub underline_color: Color,
pub overline_color: Color,
pub line_through_color: Color,
}
/// Flags for text display items.
pub struct TextDisplayItemFlags(u8);
pub struct TextDisplayItemFlags(pub u8);
impl TextDisplayItemFlags {
pub fn new() -> TextDisplayItemFlags {
@ -269,44 +269,44 @@ bitfield!(TextDisplayItemFlags, override_line_through, set_override_line_through
/// Renders an image.
pub struct ImageDisplayItem {
base: BaseDisplayItem,
image: Arc<~Image>,
pub base: BaseDisplayItem,
pub image: Arc<~Image>,
/// 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
/// direction to tile the entire bounds.
stretch_size: Size2D<Au>,
pub stretch_size: Size2D<Au>,
}
/// Renders a border.
pub struct BorderDisplayItem {
base: BaseDisplayItem,
pub base: BaseDisplayItem,
/// The border widths
border: SideOffsets2D<Au>,
pub border: SideOffsets2D<Au>,
/// The border colors.
color: SideOffsets2D<Color>,
pub color: SideOffsets2D<Color>,
/// The border styles.
style: SideOffsets2D<border_style::T>
pub style: SideOffsets2D<border_style::T>
}
/// Renders a line segment.
pub struct LineDisplayItem {
base: BaseDisplayItem,
pub base: BaseDisplayItem,
/// The line segment color.
color: Color,
pub color: Color,
/// The line segment style.
style: border_style::T
pub style: border_style::T
}
pub struct ClipDisplayItem {
base: BaseDisplayItem,
child_list: SmallVec0<DisplayItem>,
need_clip: bool
pub base: BaseDisplayItem,
pub child_list: SmallVec0<DisplayItem>,
pub need_clip: bool
}
pub enum DisplayItemIterator<'a> {
@ -348,7 +348,7 @@ impl DisplayItem {
debug!("Drawing text at {:?}.", text.base.bounds);
// 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_metrics = {
@ -358,7 +358,7 @@ impl DisplayItem {
let baseline_origin = Point2D(origin.x, origin.y + font_metrics.ascent);
{
font.borrow_mut().draw_text_into_context(render_context,
text.text_run.get(),
&*text.text_run,
&text.range,
baseline_origin,
text.text_color);

View file

@ -77,16 +77,16 @@ pub trait FontTableMethods {
#[deriving(Clone)]
pub struct FontMetrics {
underline_size: Au,
underline_offset: Au,
strikeout_size: Au,
strikeout_offset: Au,
leading: Au,
x_height: Au,
em_size: Au,
ascent: Au,
descent: Au,
max_advance: Au
pub underline_size: Au,
pub underline_offset: Au,
pub strikeout_size: Au,
pub strikeout_offset: Au,
pub leading: Au,
pub x_height: Au,
pub em_size: Au,
pub ascent: Au,
pub descent: Au,
pub max_advance: Au
}
// 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
#[deriving(Clone, Eq)]
pub struct FontStyle {
pt_size: f64,
weight: font_weight::T,
style: font_style::T,
families: ~[~str],
pub pt_size: f64,
pub weight: font_weight::T,
pub style: font_style::T,
pub families: ~[~str],
// TODO(Issue #198): font-stretch, text-decoration, font-variant, size-adjust
}
@ -115,8 +115,8 @@ pub type UsedFontStyle = FontStyle;
// and render tasks.
#[deriving(Clone, Eq)]
pub struct FontDescriptor {
style: UsedFontStyle,
selector: FontSelector,
pub style: UsedFontStyle,
pub selector: FontSelector,
}
impl FontDescriptor {
@ -142,11 +142,11 @@ pub enum FontSelector {
// The ordering of font instances is mainly decided by the CSS
// 'font-family' property. The last font is a system fallback font.
pub struct FontGroup {
families: ~[~str],
pub families: ~[~str],
// style of the first western font in group, which is
// used for purposes of calculating text run metrics.
style: UsedFontStyle,
fonts: ~[Rc<RefCell<Font>>]
pub style: UsedFontStyle,
pub fonts: ~[Rc<RefCell<Font>>]
}
impl FontGroup {
@ -172,12 +172,12 @@ impl FontGroup {
pub struct RunMetrics {
// may be negative due to negative width (i.e., kerning of '.' in 'P.T.')
advance_width: Au,
ascent: Au, // nonzero
descent: Au, // nonzero
pub advance_width: Au,
pub ascent: Au, // nonzero
pub descent: Au, // nonzero
// this bounding box is relative to the left origin baseline.
// so, bounding_box.position.y = -ascent
bounding_box: Rect<Au>
pub bounding_box: Rect<Au>
}
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.
*/
pub struct Font {
priv handle: FontHandle,
priv azure_font: Option<ScaledFont>,
priv shaper: Option<Shaper>,
style: UsedFontStyle,
metrics: FontMetrics,
backend: BackendType,
shape_cache: HashCache<~str, Arc<GlyphStore>>,
glyph_advance_cache: HashCache<u32, FractionalPixel>,
pub handle: FontHandle,
pub azure_font: Option<ScaledFont>,
pub shaper: Option<Shaper>,
pub style: UsedFontStyle,
pub metrics: FontMetrics,
pub backend: BackendType,
pub shape_cache: HashCache<~str, Arc<GlyphStore>>,
pub glyph_advance_cache: HashCache<u32, FractionalPixel>,
}
impl<'a> Font {
@ -341,7 +341,7 @@ impl Font {
range: &Range,
baseline_origin: Point2D<Au>,
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,
struct__AzGlyph,
struct__AzGlyphBuffer,

View file

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

View file

@ -83,8 +83,8 @@ impl FontList {
// Holds a specific font family, and the various
pub struct FontFamily {
family_name: ~str,
entries: ~[FontEntry],
pub family_name: ~str,
pub entries: ~[FontEntry],
}
impl FontFamily {
@ -131,10 +131,10 @@ impl FontFamily {
/// In the common case, each FontFamily will have a singleton FontEntry, or it will have the
/// standard four faces: Normal, Bold, Italic, BoldItalic.
pub struct FontEntry {
face_name: ~str,
priv weight: font_weight::T,
priv italic: bool,
handle: FontHandle,
pub face_name: ~str,
weight: font_weight::T,
italic: bool,
pub handle: FontHandle,
// 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
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#[crate_id = "github.com/mozilla/servo#gfx:0.1"];
#[crate_type = "lib"];
#[crate_type = "dylib"];
#[crate_type = "rlib"];
#![crate_id = "github.com/mozilla/servo#gfx:0.1"]
#![crate_type = "lib"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#[feature(globs, macro_rules, phase)];
#![feature(globs, macro_rules, phase)]
#[feature(phase)];
#![feature(phase)]
#[phase(syntax, link)]
extern crate log;
@ -17,6 +17,7 @@ extern crate azure;
extern crate collections;
extern crate geom;
extern crate layers;
extern crate libc;
extern crate stb_image;
extern crate png;
#[phase(syntax)]

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -13,22 +13,22 @@ use geom::point::Point2D;
use geom::rect::Rect;
use geom::size::Size2D;
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 servo_net::image::base::Image;
use servo_util::geometry::Au;
use servo_util::opts::Opts;
use std::libc::types::common::c99::uint16_t;
use std::libc::size_t;
use sync::Arc;
pub struct RenderContext<'a> {
draw_target: &'a DrawTarget,
font_ctx: &'a mut ~FontContext,
opts: &'a Opts,
pub draw_target: &'a DrawTarget,
pub font_ctx: &'a mut ~FontContext,
pub opts: &'a Opts,
/// 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).
screen_rect: Rect<uint>,
pub screen_rect: Rect<uint>,
}
enum Direction {
@ -94,7 +94,6 @@ impl<'a> RenderContext<'a> {
}
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 pixel_width = match image.color_type {
RGBA8 => 4,

View file

@ -36,15 +36,15 @@ use sync::Arc;
/// Information about a layer that layout sends to the painting task.
pub struct RenderLayer {
/// 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.
display_list: Arc<DisplayList>,
pub display_list: Arc<DisplayList>,
/// 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.
background_color: Color,
pub background_color: Color,
/// The scrolling policy of this layer.
scroll_policy: ScrollPolicy,
pub scroll_policy: ScrollPolicy,
}
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.
pub struct RenderChan {
chan: Sender<Msg>,
pub chan: Sender<Msg>,
}
impl Clone for RenderChan {
@ -138,7 +138,7 @@ pub struct RenderTask<C> {
epoch: Epoch,
/// 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
@ -352,7 +352,7 @@ impl<C: RenderListener + Send> RenderTask<C> {
// Draw the display list.
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();
});
}

View file

@ -500,9 +500,9 @@ impl<'a> GlyphInfo<'a> {
pub struct GlyphStore {
// TODO(pcwalton): Allocation of this buffer is expensive. Consider a small-vector
// optimization.
priv entry_buffer: ~[GlyphEntry],
entry_buffer: ~[GlyphEntry],
priv detail_store: DetailedGlyphStore,
detail_store: DetailedGlyphStore,
is_whitespace: bool,
}
@ -673,10 +673,10 @@ impl<'a> GlyphStore {
}
pub struct GlyphIterator<'a> {
priv store: &'a GlyphStore,
priv char_index: uint,
priv char_range: iter::Range<uint>,
priv glyph_range: Option<iter::Range<uint>>,
store: &'a GlyphStore,
char_index: uint,
char_range: iter::Range<uint>,
glyph_range: Option<iter::Range<uint>>,
}
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_position_t, hb_tag_t};
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::range::Range;
use std::cast::transmute;
use std::char;
use std::cmp;
use std::libc::{c_uint, c_int, c_void, c_char};
use std::ptr::null;
use std::slice;
@ -133,9 +133,9 @@ impl ShapedGlyphData {
}
pub struct Shaper {
priv hb_face: *hb_face_t,
priv hb_font: *hb_font_t,
priv hb_funcs: *hb_font_funcs_t,
hb_face: *hb_face_t,
hb_font: *hb_font_t,
hb_funcs: *hb_font_funcs_t,
}
#[unsafe_destructor]

View file

@ -13,18 +13,18 @@ use text::glyph::GlyphStore;
/// A text run.
#[deriving(Clone)]
pub struct TextRun {
text: Arc<~str>,
font_descriptor: FontDescriptor,
font_metrics: FontMetrics,
font_style: FontStyle,
decoration: text_decoration::T,
glyphs: Arc<~[Arc<GlyphStore>]>,
pub text: Arc<~str>,
pub font_descriptor: FontDescriptor,
pub font_metrics: FontMetrics,
pub font_style: FontStyle,
pub decoration: text_decoration::T,
pub glyphs: Arc<~[Arc<GlyphStore>]>,
}
pub struct SliceIterator<'a> {
priv glyph_iter: Items<'a, Arc<GlyphStore>>,
priv range: Range,
priv offset: uint,
glyph_iter: Items<'a, Arc<GlyphStore>>,
range: Range,
offset: uint,
}
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() {
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 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;
self.offset += slice_glyphs.char_len();
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> {
priv range: Range,
priv clump: Option<Range>,
priv slices: SliceIterator<'a>,
range: Range,
clump: Option<Range>,
slices: SliceIterator<'a>,
}
impl<'a> Iterator<Range> for LineIterator<'a> {
@ -169,13 +169,13 @@ impl<'a> TextRun {
}
pub fn char_len(&self) -> uint {
self.glyphs.get().iter().fold(0u, |len, slice_glyphs| {
len + slice_glyphs.get().char_len()
self.glyphs.iter().fold(0u, |len, slice_glyphs| {
len + slice_glyphs.char_len()
})
}
pub fn glyphs(&'a self) -> &'a ~[Arc<GlyphStore>] {
self.glyphs.get()
&*self.glyphs
}
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> {
SliceIterator {
glyph_iter: self.glyphs.get().iter(),
glyph_iter: self.glyphs.iter(),
range: *range,
offset: 0,
}

View file

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

View file

@ -43,72 +43,72 @@ use time::precise_time_s;
pub struct IOCompositor {
/// The application window.
window: Rc<Window>,
pub window: Rc<Window>,
/// The port on which we receive messages.
port: Receiver<Msg>,
pub port: Receiver<Msg>,
/// The render context.
context: RenderContext,
pub context: RenderContext,
/// The root ContainerLayer.
root_layer: Rc<ContainerLayer>,
pub root_layer: Rc<ContainerLayer>,
/// The root pipeline.
root_pipeline: Option<CompositionPipeline>,
pub root_pipeline: Option<CompositionPipeline>,
/// The canvas to paint a page.
scene: Scene,
pub scene: Scene,
/// The application window size.
window_size: Size2D<uint>,
pub window_size: Size2D<uint>,
/// The platform-specific graphics context.
graphics_context: NativeCompositingGraphicsContext,
pub graphics_context: NativeCompositingGraphicsContext,
/// 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.
shutting_down: bool,
pub shutting_down: bool,
/// Tracks whether we should close compositor.
done: bool,
pub done: bool,
/// Tracks whether we need to re-composite a page.
recomposite: bool,
pub recomposite: bool,
/// Keeps track of the current zoom factor.
world_zoom: f32,
pub world_zoom: f32,
/// Tracks whether the zoom action has happend recently.
zoom_action: bool,
pub zoom_action: bool,
/// The time of the last zoom action has started.
zoom_time: f64,
pub zoom_time: f64,
/// Current display/reflow status of the page
ready_state: ReadyState,
pub ready_state: ReadyState,
/// Whether the page being rendered has loaded completely.
/// Differs from ReadyState because we can finish loading (ready)
/// many times for a single page.
load_complete: bool,
pub load_complete: bool,
/// The command line option flags.
opts: Opts,
pub opts: Opts,
/// The root CompositorLayer
compositor_layer: Option<CompositorLayer>,
pub compositor_layer: Option<CompositorLayer>,
/// 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.
profiler_chan: ProfilerChan,
pub profiler_chan: ProfilerChan,
/// Pending scroll to fragment event, if any
fragment_point: Option<Point2D<f32>>
pub fragment_point: Option<Point2D<f32>>
}
impl IOCompositor {
@ -376,7 +376,7 @@ impl IOCompositor {
self.opts.tile_size,
self.opts.cpu_painting);
match self.root_layer.first_child.get() {
match *self.root_layer.first_child.borrow() {
None => {}
Some(ref old_layer) => {
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.
pub struct CompositorLayer {
/// 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.
id: LayerId,
pub id: LayerId,
/// 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
/// 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.
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
/// 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
/// differs in scroll behavior from its parent. Each is associated with a
/// ContainerLayer which determines its position relative to its parent and
/// 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.
quadtree: MaybeQuadtree,
pub quadtree: MaybeQuadtree,
/// 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.
root_layer: Rc<ContainerLayer>,
pub root_layer: Rc<ContainerLayer>,
/// When set to true, this layer is ignored by its parents. This is useful for
/// 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.
/// 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.
wants_scroll_events: WantsScrollEventsFlag,
pub wants_scroll_events: WantsScrollEventsFlag,
/// 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.
cpu_painting: bool,
pub cpu_painting: bool,
/// The color to use for the unrendered-content void
unrendered_color: Color,
pub unrendered_color: Color,
}
/// Helper struct for keeping CompositorLayer children organized.
pub struct CompositorLayerChild {
/// The child itself.
child: ~CompositorLayer,
pub child: ~CompositorLayer,
/// A ContainerLayer managed by the parent node. This deals with clipping and
/// 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
@ -128,7 +128,7 @@ pub enum WantsScrollEventsFlag {
fn create_container_layer_from_rect(rect: Rect<f32>) -> Rc<ContainerLayer> {
let container = Rc::new(ContainerLayer());
container.scissor.set(Some(rect));
*container.scissor.borrow_mut() = Some(rect);
container.common.borrow_mut().transform =
identity().translate(rect.origin.x, rect.origin.y, 0f32);
container
@ -303,7 +303,7 @@ impl CompositorLayer {
// Allow children to scroll.
let cursor = cursor - self.scroll_offset;
for child in self.children.mut_iter() {
match child.container.scissor.get() {
match *child.container.scissor.borrow() {
None => {
error!("CompositorLayer: unable to perform cursor hit test for layer");
}
@ -343,7 +343,7 @@ impl CompositorLayer {
#[allow(dead_code)]
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() {
match kid {
ContainerLayerKind(ref container_layer) => {
@ -385,7 +385,7 @@ impl CompositorLayer {
pub fn send_mouse_event(&self, event: MouseWindowEvent, cursor: Point2D<f32>) {
let cursor = cursor - self.scroll_offset;
for child in self.children.iter().filter(|&x| !x.child.hidden) {
match child.container.scissor.get() {
match *child.container.scissor.borrow() {
None => {
error!("CompositorLayer: unable to perform cursor hit test for layer");
}
@ -450,7 +450,7 @@ impl CompositorLayer {
}
let transform = |x: &mut CompositorLayerChild| -> bool {
match x.container.scissor.get() {
match *x.container.scissor.borrow() {
Some(scissor) => {
let mut new_rect = window_rect;
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];
child_node.container.common.borrow_mut().set_transform(
identity().translate(new_rect.origin.x, new_rect.origin.y, 0.0));
let old_rect = child_node.container.scissor.get().clone();
child_node.container.scissor.set(Some(new_rect));
let old_rect = child_node.container.scissor.borrow().clone();
*child_node.container.scissor.borrow_mut() = Some(new_rect);
match self.quadtree {
NoTree(..) => {} // Nothing to do
Tree(ref mut quadtree) => {
@ -665,7 +665,7 @@ impl CompositorLayer {
max_mem))
}
}
match child_node.container.scissor.get() {
match *child_node.container.scissor.borrow() {
Some(scissor) => {
// 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.
@ -698,7 +698,7 @@ impl CompositorLayer {
// are not rebuilt directly from this method.
pub fn build_layer_tree(&mut self, graphics_context: &NativeCompositingGraphicsContext) {
// 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.
while current_layer_child.is_some() {
@ -869,7 +869,7 @@ impl CompositorLayer {
match self.quadtree {
NoTree(..) => {} // Nothing to do
Tree(ref mut quadtree) => {
match child.get_ref().container.scissor.get() {
match *child.get_ref().container.scissor.borrow() {
Some(rect) => {
quadtree.set_status_page(rect, Normal, false); // Unhide this rect
}
@ -899,7 +899,7 @@ impl CompositorLayer {
Tree(ref mut quadtree) => quadtree,
};
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
Some(rect) => {
quadtree.set_status_page(rect, Hidden, false);

View file

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

View file

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

View file

@ -23,33 +23,33 @@ use layers::platform::surface::NativePaintingGraphicsContext;
/// at this level are in pixel coordinates.
pub struct Quadtree<T> {
// 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.
// Note that the underlying quadtree has a potentailly larger size, since it is rounded
// 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
// 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
// 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.
struct QuadtreeNode<T> {
/// 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.
origin: Point2D<f32>,
pub origin: Point2D<f32>,
/// The width and height of the node in page coordinates.
size: f32,
pub size: f32,
/// 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
tile_mem: uint,
pub tile_mem: uint,
/// 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
@ -201,12 +201,12 @@ impl<T: Tile> Quadtree<T> {
tile_mem: self.root.tile_mem,
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
let difference = difference.abs() as uint;
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 {
Some(child) => self.root = child,
None => {
@ -318,7 +318,7 @@ impl<T: Tile> QuadtreeNode<T> {
(self.tile_mem as int - old_size as int, unused_tiles)
} else { // Send tile to children
let quad = self.get_quadrant(x, y);
match self.quadrants[quad as int] {
match self.quadrants[quad as uint] {
Some(ref mut child) => {
let (delta, unused) = child.add_tile(x, y, tile, tile_size);
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 (delta, unused) = c.add_tile(x, y, tile, tile_size);
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)
}
}
@ -365,7 +365,7 @@ impl<T: Tile> QuadtreeNode<T> {
}
let quad = self.get_quadrant(x,y);
match self.quadrants[quad as int] {
match self.quadrants[quad as uint] {
None => {
let new_size = self.size / 2.0;
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 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
}
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);
for quad in queue.iter() {
match self.quadrants[*quad as int] {
match self.quadrants[*quad as uint] {
Some(ref mut child) => {
let (tile, flag, delta) = child.remove_tile(x, y);
match tile {
@ -443,7 +443,7 @@ impl<T: Tile> QuadtreeNode<T> {
match del_quad {
Some(quad) => {
self.quadrants[quad as int] = None;
self.quadrants[quad as uint] = None;
let (tile, _, delta) = ret;
match (&self.tile, &self.quadrants) {
(&None, &[None, None, None, None]) => (tile, true, delta),
@ -575,7 +575,7 @@ impl<T: Tile> QuadtreeNode<T> {
let override = override || self.status == Invalid;
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),
None => {
// 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 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
}
};

View file

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

View file

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

View file

@ -42,19 +42,19 @@ use sync::Arc;
/// Information specific to floated blocks.
pub struct FloatedBlockInfo {
containing_width: Au,
pub containing_width: Au,
/// 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: Option<uint>,
pub index: Option<uint>,
/// Number of floated children
floated_children: uint,
pub floated_children: uint,
/// Left or right?
float_kind: FloatKind,
pub float_kind: FloatKind,
}
impl FloatedBlockInfo {
@ -481,20 +481,20 @@ fn propagate_layer_flag_from_child(layers_needed_for_descendants: &mut bool, kid
// A block formatting context.
pub struct BlockFlow {
/// Data common to all flows.
base: BaseFlow,
pub base: BaseFlow,
/// The associated box.
box_: Box,
pub box_: Box,
/// TODO: is_root should be a bit field to conserve memory.
/// 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: Au,
pub static_y_offset: Au,
/// Additional floating flow members.
float: Option<~FloatedBlockInfo>
pub float: Option<~FloatedBlockInfo>
}
impl BlockFlow {
@ -780,9 +780,9 @@ impl BlockFlow {
self.base.position.size.height = self.base.position.size.height + top_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;
self.box_.border_box.set(position);
*self.box_.border_box.borrow_mut() = position;
}
/// Assign height for current flow.
@ -819,14 +819,14 @@ impl BlockFlow {
self.base.floats.translate(Point2D(-self.box_.left_offset(), Au(0)));
// 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);
let can_collapse_top_margin_with_kids =
margins_may_collapse == MarginsMayCollapse &&
!self.is_absolutely_positioned() &&
self.box_.border.get().top == Au(0) &&
self.box_.padding.get().top == Au(0);
self.box_.border.borrow().top == Au(0) &&
self.box_.padding.borrow().top == Au(0);
margin_collapse_info.initialize_top_margin(&self.box_,
can_collapse_top_margin_with_kids);
@ -940,8 +940,8 @@ impl BlockFlow {
let can_collapse_bottom_margin_with_kids =
margins_may_collapse == MarginsMayCollapse &&
!self.is_absolutely_positioned() &&
self.box_.border.get().bottom == Au(0) &&
self.box_.padding.get().bottom == Au(0);
self.box_.border.borrow().bottom == Au(0) &&
self.box_.padding.borrow().bottom == Au(0);
let (collapsible_margins, delta) =
margin_collapse_info.finish_and_compute_collapsible_margins(
&self.box_,
@ -970,9 +970,9 @@ impl BlockFlow {
// Store the content height for use in calculating the absolute flow's dimensions
// later.
let mut temp_position = self.box_.border_box.get();
let mut temp_position = *self.box_.border_box.borrow();
temp_position.size.height = height;
self.box_.border_box.set(temp_position);
*self.box_.border_box.borrow_mut() = temp_position;
return
}
@ -991,15 +991,15 @@ impl BlockFlow {
translate_including_floats(&mut cur_y, delta, inorder, &mut floats);
// 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);
// Now that `cur_y` is at the bottom of the border box, compute the final border box
// 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.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.floats = floats.clone();
@ -1031,18 +1031,18 @@ impl BlockFlow {
/// Therefore, assign_height_float was already called on this kid flow by
/// the traversal function. So, the values used are well-defined.
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() {
None => Au(0),
Some(clear) => self.base.floats.clearance(clear),
};
let noncontent_width = self.box_.padding.get().left + self.box_.padding.get().right +
self.box_.border.get().left + self.box_.border.get().right;
let noncontent_width = self.box_.padding.borrow().left + self.box_.padding.borrow().right +
self.box_.border.borrow().left + self.box_.border.borrow().right;
let full_noncontent_width = noncontent_width + self.box_.margin.get().left +
self.box_.margin.get().right;
let margin_height = self.box_.margin.get().top + self.box_.margin.get().bottom;
let full_noncontent_width = noncontent_width + self.box_.margin.borrow().left +
self.box_.margin.borrow().right;
let margin_height = self.box_.margin.borrow().top + self.box_.margin.borrow().bottom;
let info = PlacementInfo {
size: Size2D(self.base.position.size.width + full_noncontent_width,
@ -1083,7 +1083,7 @@ impl BlockFlow {
}
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 is now at the top content edge
@ -1098,13 +1098,13 @@ impl BlockFlow {
let content_height = cur_y - top_offset;
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.
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 +
self.box_.border.get().top + self.box_.border.get().bottom;
noncontent_height = self.box_.padding.borrow().top + self.box_.padding.borrow().bottom +
self.box_.border.borrow().top + self.box_.border.borrow().bottom;
// 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);
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,
@ -1232,13 +1232,13 @@ impl BlockFlow {
let static_y_offset = self.static_y_offset;
// 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();
// Non-auto margin-top and margin-bottom values have already been
// 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)) {
Auto => Auto,
_ => Specified(margin.top)
@ -1262,7 +1262,7 @@ impl BlockFlow {
// TODO: Right now, this content height value includes the
// margin because of erroneous height calculation in Box_.
// 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(
height_used_val,
margin_top,
@ -1294,17 +1294,14 @@ impl BlockFlow {
let solution = solution.unwrap();
let mut margin = self.box_.margin.get();
margin.top = solution.margin_top;
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);
// Border box height
let border_and_padding = self.box_.noncontent_height();
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.size.height = solution.height + border_and_padding;
@ -1403,7 +1400,7 @@ impl BlockFlow {
// Pass yourself as a new Containing Block
// The static x offset for any immediate kid flows will be the
// left padding
kid_abs_cb_x_offset = self.box_.padding.get().left;
kid_abs_cb_x_offset = self.box_.padding.borrow().left;
} else {
// For kids, the left margin edge will be at our left content edge.
// 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;
// Move in from the left border edge
let left_content_edge = self.box_.border_box.get().origin.x
+ self.box_.padding.get().left + self.box_.border.get().left;
let padding_and_borders = self.box_.padding.get().left + self.box_.padding.get().right +
self.box_.border.get().left + self.box_.border.get().right;
let content_width = self.box_.border_box.get().size.width - padding_and_borders;
let left_content_edge = self.box_.border_box.borrow().origin.x
+ self.box_.padding.borrow().left + self.box_.border.borrow().left;
let padding_and_borders = self.box_.padding.borrow().left + self.box_.padding.borrow().right +
self.box_.border.borrow().left + self.box_.border.borrow().right;
let content_width = self.box_.border_box.borrow().size.width - padding_and_borders;
if self.is_float() {
self.base.position.size.width = content_width;
@ -1637,7 +1634,7 @@ impl Flow for BlockFlow {
/// The 'position' property of this flow.
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.
@ -1657,7 +1654,7 @@ impl Flow for BlockFlow {
/// Return position of the CB generated by this flow from the start of this flow.
fn generated_cb_position(&self) -> Point2D<Au> {
// 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 {
@ -1685,13 +1682,13 @@ impl Flow for BlockFlow {
/// The inputs for the widths-and-margins constraint equation.
pub struct WidthConstraintInput {
computed_width: MaybeAuto,
left_margin: MaybeAuto,
right_margin: MaybeAuto,
left: MaybeAuto,
right: MaybeAuto,
available_width: Au,
static_x_offset: Au,
pub computed_width: MaybeAuto,
pub left_margin: MaybeAuto,
pub right_margin: MaybeAuto,
pub left: MaybeAuto,
pub right: MaybeAuto,
pub available_width: Au,
pub static_x_offset: Au,
}
impl WidthConstraintInput {
@ -1717,11 +1714,11 @@ impl WidthConstraintInput {
/// The solutions for the widths-and-margins constraint equation.
pub struct WidthConstraintSolution {
left: Au,
right: Au,
width: Au,
margin_left: Au,
margin_right: Au
pub left: Au,
pub right: Au,
pub width: Au,
pub margin_left: Au,
pub margin_right: Au
}
impl WidthConstraintSolution {
@ -1807,15 +1804,14 @@ pub trait WidthAndMarginsComputer {
block: &mut BlockFlow,
solution: WidthConstraintSolution) {
let box_ = block.box_();
let mut margin = box_.margin.get();
let mut margin = box_.margin.borrow_mut();
margin.left = solution.margin_left;
margin.right = solution.margin_right;
box_.margin.set(margin);
// The associated box is the border box of this flow.
let mut position_ref = box_.border_box.borrow_mut();
// Left border edge.
position_ref.origin.x = box_.margin.borrow().left;
position_ref.origin.x = margin.left;
// Border box 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::wrapper::{TLayoutNode, ThreadSafeLayoutNode};
use sync::{MutexArc, Arc};
use sync::{Arc, Mutex};
use geom::{Point2D, Rect, Size2D, SideOffsets2D};
use geom::approxeq::ApproxEq;
use gfx::color::rgb;
@ -30,7 +30,6 @@ use gfx::font::FontStyle;
use gfx::text::text_run::TextRun;
use servo_msg::constellation_msg::{ConstellationChan, FrameRectMsg, PipelineId, SubpageId};
use servo_net::image::holder::ImageHolder;
use servo_net::local_image_cache::LocalImageCache;
use servo_util::geometry::Au;
use servo_util::geometry;
use servo_util::range::*;
@ -71,37 +70,37 @@ use url::Url;
#[deriving(Clone)]
pub struct Box {
/// An opaque reference to the DOM node that this `Box` originates from.
node: OpaqueNode,
pub node: OpaqueNode,
/// The CSS style of this box.
style: Arc<ComputedValues>,
pub style: Arc<ComputedValues>,
/// The position of this box relative to its owning flow.
/// 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.
///
/// 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.
padding: RefCell<SideOffsets2D<Au>>,
pub padding: RefCell<SideOffsets2D<Au>>,
/// 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.
specific: SpecificBoxInfo,
pub specific: SpecificBoxInfo,
/// positioned box offsets
position_offsets: RefCell<SideOffsets2D<Au>>,
pub position_offsets: RefCell<SideOffsets2D<Au>>,
/// Inline data
inline_info: RefCell<Option<InlineInfo>>,
pub inline_info: RefCell<Option<InlineInfo>>,
/// 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.
@ -123,11 +122,11 @@ pub enum SpecificBoxInfo {
#[deriving(Clone)]
pub struct ImageBoxInfo {
/// The image held within this box.
image: RefCell<ImageHolder>,
computed_width: RefCell<Option<Au>>,
computed_height: RefCell<Option<Au>>,
dom_width: Option<Au>,
dom_height: Option<Au>,
pub image: RefCell<ImageHolder>,
pub computed_width: RefCell<Option<Au>>,
pub computed_height: RefCell<Option<Au>>,
pub dom_width: Option<Au>,
pub dom_height: Option<Au>,
}
impl ImageBoxInfo {
@ -137,7 +136,7 @@ impl ImageBoxInfo {
/// me.
pub fn new(node: &ThreadSafeLayoutNode,
image_url: Url,
local_image_cache: MutexArc<LocalImageCache>)
local_image_cache: Arc<Mutex<*()>>)
-> ImageBoxInfo {
fn convert_length(node: &ThreadSafeLayoutNode, name: &str) -> Option<Au> {
let element = node.as_element();
@ -216,9 +215,9 @@ impl ImageBoxInfo {
#[deriving(Clone)]
pub struct IframeBoxInfo {
/// The pipeline ID of this iframe.
pipeline_id: PipelineId,
pub pipeline_id: PipelineId,
/// The subpage ID of this iframe.
subpage_id: SubpageId,
pub subpage_id: SubpageId,
}
impl IframeBoxInfo {
@ -239,10 +238,10 @@ impl IframeBoxInfo {
#[deriving(Clone)]
pub struct ScannedTextBoxInfo {
/// The text run that this represents.
run: Arc<~TextRun>,
pub run: Arc<~TextRun>,
/// The range within the above text run that this represents.
range: Range,
pub range: Range,
}
impl ScannedTextBoxInfo {
@ -260,7 +259,7 @@ impl ScannedTextBoxInfo {
#[deriving(Clone)]
pub struct UnscannedTextBoxInfo {
/// The text inside the box.
text: ~str,
pub text: ~str,
}
impl UnscannedTextBoxInfo {
@ -297,8 +296,8 @@ pub enum SplitBoxResult {
/// Use atomic reference counting instead.
#[deriving(Clone)]
pub struct InlineInfo {
parent_info: SmallVec0<InlineParentInfo>,
baseline: Au,
pub parent_info: SmallVec0<InlineParentInfo>,
pub baseline: Au,
}
impl InlineInfo {
@ -312,20 +311,20 @@ impl InlineInfo {
#[deriving(Clone)]
pub struct InlineParentInfo {
padding: SideOffsets2D<Au>,
border: SideOffsets2D<Au>,
margin: SideOffsets2D<Au>,
style: Arc<ComputedValues>,
font_ascent: Au,
font_descent: Au,
node: OpaqueNode,
pub padding: SideOffsets2D<Au>,
pub border: SideOffsets2D<Au>,
pub margin: SideOffsets2D<Au>,
pub style: Arc<ComputedValues>,
pub font_ascent: Au,
pub font_descent: Au,
pub node: OpaqueNode,
}
/// A box that represents a table column.
#[deriving(Clone)]
pub struct TableColumnBoxInfo {
/// the number of columns a <col> element should span
span: Option<int>,
pub span: Option<int>,
}
impl TableColumnBoxInfo {
@ -348,7 +347,7 @@ impl TableColumnBoxInfo {
macro_rules! def_noncontent( ($side:ident, $get:ident, $inline_get:ident) => (
impl Box {
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 {
@ -469,7 +468,7 @@ impl Box {
//
// 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);
Box {
node: OpaqueNodeMethods::from_thread_safe_layout_node(node),
@ -518,10 +517,10 @@ impl Box {
Box {
node: self.node,
style: self.style.clone(),
border_box: RefCell::new(Rect(self.border_box.get().origin, size)),
border: RefCell::new(self.border.get()),
padding: RefCell::new(self.padding.get()),
margin: RefCell::new(self.margin.get()),
border_box: RefCell::new(Rect(self.border_box.borrow().origin, size)),
border: RefCell::new(*self.border.borrow()),
padding: RefCell::new(*self.padding.borrow()),
margin: RefCell::new(*self.margin.borrow()),
specific: specific,
position_offsets: RefCell::new(Zero::zero()),
inline_info: self.inline_info.clone(),
@ -561,7 +560,7 @@ impl Box {
};
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 {
minimum_width: width,
@ -608,11 +607,11 @@ impl Box {
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) {
self.position_offsets.set(SideOffsets2D::new(
*self.position_offsets.borrow_mut() = SideOffsets2D::new(
MaybeAuto::from_style(style.PositionOffsets.get().top, containing_height)
.specified_or_zero(),
MaybeAuto::from_style(style.PositionOffsets.get().right, containing_width)
@ -620,7 +619,7 @@ impl Box {
MaybeAuto::from_style(style.PositionOffsets.get().bottom, containing_height)
.specified_or_zero(),
MaybeAuto::from_style(style.PositionOffsets.get().left, containing_width)
.specified_or_zero()));
.specified_or_zero());
}
/// 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) {
match self.specific {
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();
@ -640,10 +639,10 @@ impl Box {
containing_block_width).specified_or_zero();
let margin_bottom = MaybeAuto::from_style(style.Margin.get().margin_bottom,
containing_block_width).specified_or_zero();
let mut margin = self.margin.get();
let mut margin = *self.margin.borrow();
margin.top = margin_top;
margin.bottom = margin_bottom;
self.margin.set(margin);
*self.margin.borrow_mut() = margin;
}
}
}
@ -674,7 +673,7 @@ impl Box {
containing_block_width))
}
};
self.padding.set(padding)
*self.padding.borrow_mut() = padding;
}
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> {
let border_box_size = self.border_box.get().size;
Size2D(border_box_size.width - self.border.get().left - self.border.get().right,
border_box_size.height - self.border.get().top - self.border.get().bottom)
let border_box_size = self.border_box.borrow().size;
Size2D(border_box_size.width - self.border.borrow().left - self.border.borrow().right,
border_box_size.height - self.border.borrow().top - self.border.borrow().bottom)
}
pub fn noncontent_width(&self) -> Au {
@ -739,10 +738,10 @@ impl Box {
match &*info {
&Some(ref info) => {
for info in info.parent_info.iter() {
if info.style.get().Box.get().position == position::relative {
rel_pos.x = rel_pos.x + left_right(info.style.get(),
if info.style.Box.get().position == position::relative {
rel_pos.x = rel_pos.x + left_right(&*info.style,
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);
}
}
@ -776,11 +775,11 @@ impl Box {
debug!("(font style) start");
// 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 {
font_family::FamilyName(ref name) => (*name).clone(),
}
});
}).collect();
debug!("(font style) font families: `{:?}`", font_families);
let font_size = my_style.Font.get().font_size.to_f64().unwrap() / 60.0;
@ -796,7 +795,7 @@ impl Box {
#[inline(always)]
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`
@ -827,33 +826,33 @@ impl Box {
/// Returns the left offset from margin edge to content edge.
pub fn left_offset(&self) -> Au {
match self.specific {
TableWrapperBox => self.margin.get().left,
TableBox | TableCellBox => self.border.get().left + self.padding.get().left,
TableRowBox => self.border.get().left,
TableWrapperBox => self.margin.borrow().left,
TableBox | TableCellBox => self.border.borrow().left + self.padding.borrow().left,
TableRowBox => self.border.borrow().left,
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.
pub fn top_offset(&self) -> Au {
match self.specific {
TableWrapperBox => self.margin.get().top,
TableBox | TableCellBox => self.border.get().top + self.padding.get().top,
TableRowBox => self.border.get().top,
TableWrapperBox => self.margin.borrow().top,
TableBox | TableCellBox => self.border.borrow().top + self.padding.borrow().top,
TableRowBox => self.border.borrow().top,
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.
pub fn bottom_offset(&self) -> Au {
match self.specific {
TableWrapperBox => self.margin.get().bottom,
TableBox | TableCellBox => self.border.get().bottom + self.padding.get().bottom,
TableRowBox => self.border.get().bottom,
TableWrapperBox => self.margin.borrow().bottom,
TableBox | TableCellBox => self.border.borrow().bottom + self.padding.borrow().bottom,
TableRowBox => self.border.borrow().bottom,
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
bg_rect.origin.y = box_info.baseline + offset.y - info.font_ascent;
bg_rect.size.height = info.font_ascent + info.font_descent;
let background_color = info.style.get().resolve_color(
info.style.get().Background.get().background_color);
let background_color = info.style.resolve_color(
info.style.Background.get().background_color);
if !background_color.alpha.approx_eq(&0.0) {
let solid_color_display_item = ~SolidColorDisplayItem {
@ -920,7 +919,7 @@ impl Box {
bg_rect.origin.y = bg_rect.origin.y - border.top;
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 right_color = style.resolve_color(style.Border.get().border_right_color);
let bottom_color = style.resolve_color(style.Border.get().border_bottom_color);
@ -1025,14 +1024,14 @@ impl Box {
// Adjust sizes for `background-repeat`.
match style.Background.get().background_repeat {
background_repeat::no_repeat => {
bounds.size.width = Au::from_px(image.get().width as int);
bounds.size.height = Au::from_px(image.get().height as int)
bounds.size.width = Au::from_px(image.width as int);
bounds.size.height = Au::from_px(image.height as int)
}
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 => {
bounds.size.width = Au::from_px(image.get().width as int)
bounds.size.width = Au::from_px(image.width as int)
}
background_repeat::repeat => {}
};
@ -1045,8 +1044,8 @@ impl Box {
node: self.node,
},
image: image.clone(),
stretch_size: Size2D(Au::from_px(image.get().width as int),
Au::from_px(image.get().height as int)),
stretch_size: Size2D(Au::from_px(image.width as int),
Au::from_px(image.height as int)),
});
match clip_display_item {
@ -1073,7 +1072,7 @@ impl Box {
/// necessary.
pub fn paint_borders_if_applicable(&self, list: &mut DisplayList, abs_bounds: &Rect<Au>) {
// Fast path.
let border = self.border.get();
let border = self.border.borrow();
if border.is_zero() {
return
}
@ -1099,7 +1098,7 @@ impl Box {
bounds: abs_bounds,
node: self.node,
},
border: border,
border: *border,
color: SideOffsets2D::new(top_color.to_gfx_color(),
right_color.to_gfx_color(),
bottom_color.to_gfx_color(),
@ -1117,7 +1116,7 @@ impl Box {
stacking_context: &mut StackingContext,
flow_origin: Point2D<Au>,
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);
// 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));
// 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),
Size2D(absolute_box_bounds.size.width, Au(0)));
@ -1155,7 +1154,7 @@ impl Box {
fn build_debug_borders_around_box(&self,
stacking_context: &mut StackingContext,
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);
// This prints a debug border around the border of this box.
@ -1192,7 +1191,7 @@ impl Box {
flow: &Flow,
background_and_border_level: BackgroundAndBorderLevel) {
// 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);
debug!("Box::build_display_list at rel={}, abs={}: {:s}",
box_bounds,
@ -1244,7 +1243,7 @@ impl Box {
match &*inline_info {
&Some(ref info) => {
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);
}
},
@ -1374,11 +1373,11 @@ impl Box {
}
ScannedTextBox(ref text_box_info) => {
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);
for line_range in text_box_info.run.get().iter_natural_lines_for_range(range) {
let line_metrics = text_box_info.run.get().metrics_for_range(&line_range);
for line_range in text_box_info.run.iter_natural_lines_for_range(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);
}
@ -1389,8 +1388,7 @@ impl Box {
}
// Take borders and padding for parent inline boxes into account.
let inline_info = self.inline_info.get();
match inline_info {
match *self.inline_info.borrow() {
None => {}
Some(ref inline_info) => {
for inline_parent_info in inline_info.parent_info.iter() {
@ -1418,7 +1416,7 @@ impl Box {
}
ScannedTextBox(ref text_box_info) => {
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
}
TableColumnBox(_) => fail!("Table column boxes do not have width"),
@ -1437,7 +1435,7 @@ impl Box {
ScannedTextBox(ref text_box_info) => {
// Compute the height based on the line-height and font size.
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;
self.calculate_line_height(em_size)
}
@ -1448,7 +1446,7 @@ impl Box {
/// Return the size of the content box.
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(),
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.
let left_box = {
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));
new_box.new_line_pos = ~[];
Some(new_box)
@ -1479,7 +1477,7 @@ impl Box {
// Right box is for right text of first founded new-line character.
let right_box = if right_range.length() > 0 {
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));
new_box.new_line_pos = new_line_pos;
Some(new_box)
@ -1507,11 +1505,11 @@ impl Box {
debug!("split_to_width: splitting text box (strlen={:u}, range={}, \
avail_width={})",
text_box_info.run.get().text.get().len(),
text_box_info.run.text.len(),
text_box_info.range,
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) {
debug!("split_to_width: considering slice (offset={}, range={}, \
remain_width={})",
@ -1519,7 +1517,7 @@ impl Box {
slice_range,
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 should_continue;
@ -1571,8 +1569,8 @@ impl Box {
let left_box = if left_range.length() > 0 {
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);
new_metrics.bounding_box.size.height = self.border_box.get().size.height;
let mut new_metrics = new_text_box_info.run.metrics_for_range(&left_range);
new_metrics.bounding_box.size.height = self.border_box.borrow().size.height;
Some(self.transform(new_metrics.bounding_box.size,
ScannedTextBox(new_text_box_info)))
} else {
@ -1581,8 +1579,8 @@ impl Box {
let right_box = right_range.map_or(None, |range: 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);
new_metrics.bounding_box.size.height = self.border_box.get().size.height;
let mut new_metrics = new_text_box_info.run.metrics_for_range(&range);
new_metrics.bounding_box.size.height = self.border_box.borrow().size.height;
Some(self.transform(new_metrics.bounding_box.size,
ScannedTextBox(new_text_box_info)))
});
@ -1647,7 +1645,7 @@ impl Box {
let mut position = self.border_box.borrow_mut();
position.size.width = width + self.noncontent_width() +
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(_) => {
// Scanned text boxes will have already had their
@ -1694,7 +1692,7 @@ impl Box {
};
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()
}
ScannedTextBox(_) => {
@ -1724,7 +1722,7 @@ impl Box {
/// Cleans up all the memory associated with this box.
pub fn teardown(&self) {
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!("({}{}{}{})",
class_name,
self.side_offsets_debug_string("b", self.border.get()),
self.side_offsets_debug_string("p", self.padding.get()),
self.side_offsets_debug_string("m", self.margin.get()))
self.side_offsets_debug_string("b", *self.border.borrow()),
self.side_offsets_debug_string("p", *self.padding.borrow()),
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
@ -1778,12 +1776,12 @@ impl Box {
iframe_box: &IframeBoxInfo,
offset: Point2D<Au>,
layout_context: &LayoutContext) {
let left = offset.x + self.margin.get().left + self.border.get().left +
self.padding.get().left;
let top = offset.y + self.margin.get().top + self.border.get().top +
self.padding.get().top;
let width = self.border_box.get().size.width - self.noncontent_width();
let height = self.border_box.get().size.height - self.noncontent_height();
let left = offset.x + self.margin.borrow().left + self.border.borrow().left +
self.padding.borrow().left;
let top = offset.y + self.margin.borrow().top + self.border.borrow().top +
self.padding.borrow().top;
let width = self.border_box.borrow().size.width - self.noncontent_width();
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 size = Size2D(geometry::to_frac_px(width) as f32, geometry::to_frac_px(height) as f32);
let rect = Rect(origin, size);

View file

@ -128,13 +128,13 @@ pub struct InlineBoxesConstructionResult {
/// Any {ib} splits that we're bubbling up.
///
/// TODO(pcwalton): Small vector optimization.
splits: Option<~[InlineBlockSplit]>,
pub splits: Option<~[InlineBlockSplit]>,
/// Any boxes that succeed the {ib} splits.
boxes: ~[Box],
pub boxes: ~[Box],
/// 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
@ -163,10 +163,10 @@ pub struct InlineBlockSplit {
/// The inline boxes that precede the flow.
///
/// TODO(pcwalton): Small vector optimization.
predecessor_boxes: ~[Box],
pub predecessor_boxes: ~[Box],
/// The flow that caused this {ib} split.
flow: ~Flow,
pub flow: ~Flow,
}
impl InlineBlockSplit {
@ -241,14 +241,14 @@ impl<T> OptVector<T> for Option<~[T]> {
/// An object that knows how to create flows.
pub struct FlowConstructor<'a> {
/// 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
/// layout context.
///
/// FIXME(pcwalton): This is pretty bogus and is basically just a workaround for libgreen
/// having slow TLS.
font_context: Option<~FontContext>,
pub font_context: Option<~FontContext>,
}
impl<'a> FlowConstructor<'a> {
@ -705,8 +705,8 @@ impl<'a> FlowConstructor<'a> {
*info = Some(InlineInfo::new());
}
let mut border = parent_box.border.get();
let mut padding = parent_box.padding.get();
let mut border = *parent_box.border.borrow();
let mut padding = *parent_box.padding.borrow();
if i != 0 {
border.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() {
None => {
// Pseudo-element.
let style = node.style().get();
let style = node.style();
(display::inline, style.Box.get().float, style.Box.get().position)
}
Some(ElementNodeTypeId(_)) => {
let style = node.style().get();
let style = node.style();
(style.Box.get().display, style.Box.get().float, style.Box.get().position)
}
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
// want to update this check.
match self.style().get().InheritedText.get().white_space {
match self.style().InheritedText.get().white_space {
white_space::normal => true,
_ => false,
}

View file

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

View file

@ -15,23 +15,23 @@ use style;
/// Manages the information needed to construct the display list.
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.
layers: SmallVec0<RenderLayer>,
pub layers: SmallVec0<RenderLayer>,
/// The dirty rect.
dirty: Rect<Au>,
pub dirty: Rect<Au>,
}
/// Information needed at each step of the display list building traversal.
pub struct DisplayListBuildingInfo {
/// 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.
absolute_containing_block_position: Point2D<Au>,
pub absolute_containing_block_position: Point2D<Au>,
/// 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.
pub struct PlacementInfo {
/// The dimensions of the float.
size: Size2D<Au>,
pub size: Size2D<Au>,
/// 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.
max_width: Au,
pub max_width: Au,
/// 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) {
@ -123,9 +123,9 @@ fn range_intersect(top_1: Au, bottom_1: Au, top_2: Au, bottom_2: Au) -> (Au, Au)
#[deriving(Clone)]
pub struct Floats {
/// The list of floats.
priv list: FloatListRef,
list: FloatListRef,
/// The offset of the flow relative to the first float.
priv offset: Point2D<Au>,
offset: Point2D<Au>,
}
impl Floats {

View file

@ -441,22 +441,22 @@ pub trait PostorderFlowTraversal {
#[deriving(Clone)]
pub struct FlowFlagsInfo {
flags: FlowFlags,
pub flags: FlowFlags,
/// text-decoration colors
rare_flow_flags: Option<~RareFlowFlags>,
pub rare_flow_flags: Option<~RareFlowFlags>,
}
#[deriving(Clone)]
pub struct RareFlowFlags {
underline_color: Color,
overline_color: Color,
line_through_color: Color,
pub underline_color: Color,
pub overline_color: Color,
pub line_through_color: Color,
}
/// Flags used in flows, tightly packed to save space.
#[deriving(Clone)]
pub struct FlowFlags(u8);
pub struct FlowFlags(pub u8);
/// 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).
pub struct Descendants {
/// 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: SmallVec0<Au>,
pub static_y_offsets: SmallVec0<Au>,
}
impl Descendants {
@ -724,17 +724,17 @@ pub type DescendantOffsetIter<'a> = Zip<MutItems<'a, Rawlink>, MutItems<'a, Au>>
/// Data common to all flows.
pub struct BaseFlow {
restyle_damage: RestyleDamage,
pub restyle_damage: RestyleDamage,
/// The children of this flow.
children: FlowList,
next_sibling: Link,
prev_sibling: Rawlink,
pub children: FlowList,
pub next_sibling: Link,
pub prev_sibling: Rawlink,
/* layout computations */
// TODO: min/pref and position are used during disjoint phases of
// 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
/// 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
/// for the block direction (usually vertical), this represents the *border box*. For the
/// 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
/// pixels of all the display list items for correct invalidation.
overflow: Rect<Au>,
pub overflow: Rect<Au>,
/// Data used during parallel traversals.
///
/// TODO(pcwalton): Group with other transient data to save space.
parallel: FlowParallelInfo,
pub parallel: FlowParallelInfo,
/// The floats next to this flow.
floats: Floats,
pub floats: Floats,
/// 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
/// not contained within any other floated descendant of this flow. For
/// floats, it is 1.
/// It is used to allocate float data if necessary and to
/// 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.
collapsible_margins: CollapsibleMargins,
pub collapsible_margins: CollapsibleMargins,
/// 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
/// 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
/// for any absolutely positioned elements.
absolute_static_x_offset: Au,
pub absolute_static_x_offset: Au,
/// 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.
absolute_cb: Rawlink,
pub absolute_cb: Rawlink,
/// Whether this flow has been destroyed.
///
/// TODO(pcwalton): Pack this into the flags? Need to be careful because manipulation of this
/// flag can have memory safety implications.
priv destroyed: bool,
destroyed: bool,
/// Various flags for flows and some info
flags_info: FlowFlagsInfo,
pub flags_info: FlowFlagsInfo,
}
#[unsafe_destructor]
impl Drop for BaseFlow {
fn drop(&mut self) {
if !self.destroyed {
@ -834,7 +835,7 @@ impl BaseFlow {
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)]
pub struct Rawlink {
priv vtable: *(),
priv obj: *mut (),
vtable: *(),
obj: *mut (),
}
/// Doubly-linked list of Flows.
@ -24,24 +24,24 @@ pub struct Rawlink {
/// The forward links are strong references.
/// The backward links are weak references.
pub struct FlowList {
priv length: uint,
priv list_head: Link,
priv list_tail: Rawlink,
length: uint,
list_head: Link,
list_tail: Rawlink,
}
/// Double-ended FlowList iterator
pub struct FlowListIterator<'a> {
priv head: &'a Link,
priv tail: Rawlink,
priv nelem: uint,
head: &'a Link,
tail: Rawlink,
nelem: uint,
}
/// Double-ended mutable FlowList iterator
pub struct MutFlowListIterator<'a> {
priv list: &'a mut FlowList,
priv head: Rawlink,
priv tail: Rawlink,
priv nelem: uint,
list: &'a mut FlowList,
head: Rawlink,
tail: Rawlink,
nelem: uint,
}
impl Rawlink {

View file

@ -28,7 +28,7 @@ pub enum RestyleEffect {
// FIXME: Switch to librustc/util/enum_set.rs if that gets moved into
// libextra (Rust #8054)
pub struct RestyleDamage {
priv bits: int
bits: int
}
// 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
/// the green zone can be taller and wider than the line itself.
pub struct LineBox {
range: Range,
bounds: Rect<Au>,
green_zone: Size2D<Au>
pub range: Range,
pub bounds: Rect<Au>,
pub green_zone: Size2D<Au>
}
struct LineboxScanner {
floats: Floats,
new_boxes: ~[Box],
work_list: RingBuf<Box>,
pending_line: LineBox,
lines: ~[LineBox],
cur_y: Au,
pub floats: Floats,
pub new_boxes: ~[Box],
pub work_list: RingBuf<Box>,
pub pending_line: LineBox,
pub lines: ~[LineBox],
pub cur_y: Au,
}
impl LineboxScanner {
@ -179,7 +179,7 @@ impl LineboxScanner {
-> (Rect<Au>, Au) {
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();
debug!("LineboxScanner: box size: {}, splittable: {}", first_box_size, splittable);
let line_is_empty: bool = self.pending_line.range.length() == 0;
@ -233,9 +233,9 @@ impl LineboxScanner {
debug!("LineboxScanner: case=box split and fit");
let actual_box_width = match (left, right) {
(Some(l_box), Some(_)) => l_box.border_box.get().size.width,
(Some(l_box), None) => l_box.border_box.get().size.width,
(None, Some(r_box)) => r_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.borrow().size.width,
(None, Some(r_box)) => r_box.border_box.borrow().size.width,
(None, None) => fail!("This case makes no sense.")
};
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");
let actual_box_width = match (left, right) {
(Some(l_box), Some(_)) => l_box.border_box.get().size.width,
(Some(l_box), None) => l_box.border_box.get().size.width,
(None, Some(r_box)) => r_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.borrow().size.width,
(None, Some(r_box)) => r_box.border_box.borrow().size.width,
(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: \
{}): {:s}",
self.lines.len(),
in_box.border_box.get().size,
in_box.border_box.borrow().size,
self.pending_line.green_zone,
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
// 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 {
debug!("LineboxScanner: case=box fits without splitting");
self.push_box_to_line(in_box);
@ -439,29 +439,29 @@ impl LineboxScanner {
}
self.pending_line.range.extend_by(1);
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,
box_.border_box.get().size.height);
box_.border_box.borrow().size.height);
self.new_boxes.push(box_);
}
}
pub struct InlineFlow {
/// 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.
boxes: ~[Box],
pub boxes: ~[Box],
// vec of ranges into boxes that represents line positions.
// these ranges are disjoint, and are the result of inline layout.
// also some metadata used for positioning lines
lines: ~[LineBox],
pub lines: ~[LineBox],
// vec of ranges into boxes that represent elements. These ranges
// must be well-nested, and are only related to the content of
// boxes (not lines). Ranges are only kept for non-leaf elements.
elems: ElementMapping,
pub elems: ElementMapping,
}
impl InlineFlow {
@ -600,8 +600,9 @@ impl InlineFlow {
for i in line.range.eachi() {
let box_ = &boxes[i];
let size = box_.border_box.get().size;
box_.border_box.set(Rect(Point2D(offset_x, box_.border_box.get().origin.y), size));
let mut border_box = box_.border_box.borrow_mut();
let size = border_box.size;
*border_box = Rect(Point2D(offset_x, border_box.origin.y), size);
offset_x = offset_x + size.width;
}
}
@ -749,23 +750,23 @@ impl Flow for InlineFlow {
let run = &text_box.run;
// 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 line_height = cur_box.calculate_line_height(em_size);
// Find the top and bottom of the content area.
// 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
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)
},
GenericBox | IframeBox(_) | TableBox | TableCellBox | TableRowBox |
TableWrapperBox => {
let height = cur_box.border_box.get().size.height;
let height = cur_box.border_box.borrow().size.height;
(height, Au::new(0), height)
},
TableColumnBox(_) => fail!("Table column boxes do not have height"),
@ -850,8 +851,8 @@ impl Flow for InlineFlow {
_ => baseline_offset,
};
cur_box.border_box.borrow_mut().origin.y = cur_box.border_box.get().origin.y +
adjust_offset;
let mut border_box = cur_box.border_box.borrow_mut();
border_box.origin.y = border_box.origin.y + adjust_offset;
let mut info = cur_box.inline_info.borrow_mut();
if info.is_none() {
@ -884,6 +885,8 @@ impl Flow for InlineFlow {
}
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 style::{AuthorOrigin, ComputedValues, Stylesheet, Stylist};
use style;
use sync::{Arc, MutexArc};
use sync::{Arc, Mutex};
use url::Url;
/// Information needed by the layout task.
pub struct LayoutTask {
/// The ID of the pipeline that we belong to.
id: PipelineId,
pub id: PipelineId,
/// The port on which we receive messages.
port: Receiver<Msg>,
pub port: Receiver<Msg>,
//// The channel to send messages to ourself.
chan: LayoutChan,
pub chan: LayoutChan,
/// 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.
script_chan: ScriptChan,
pub script_chan: ScriptChan,
/// 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.
image_cache_task: ImageCacheTask,
pub image_cache_task: ImageCacheTask,
/// 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.
screen_size: Size2D<Au>,
pub screen_size: Size2D<Au>,
/// 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.
initial_css_values: Arc<ComputedValues>,
pub initial_css_values: Arc<ComputedValues>,
/// 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.
profiler_chan: ProfilerChan,
pub profiler_chan: ProfilerChan,
opts: Opts
pub opts: Opts
}
/// 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
/// and intrinsic widths and bubbles them up the tree.
pub struct BubbleWidthsTraversal<'a> {
layout_context: &'a mut LayoutContext,
pub layout_context: &'a mut LayoutContext,
}
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`.
pub struct AssignWidthsTraversal<'a> {
layout_context: &'a mut LayoutContext,
pub layout_context: &'a mut LayoutContext,
}
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
/// computes overflow regions. In Gecko this corresponds to `FinishAndStoreOverflow`.
pub struct AssignHeightsAndStoreOverflowTraversal<'a> {
layout_context: &'a mut LayoutContext,
pub layout_context: &'a mut LayoutContext,
}
impl<'a> PostorderFlowTraversal for AssignHeightsAndStoreOverflowTraversal<'a> {
@ -234,10 +235,10 @@ struct LayoutImageResponder {
}
impl ImageResponder for LayoutImageResponder {
fn respond(&self) -> proc(ImageResponseMsg) {
fn respond(&self) -> proc(ImageResponseMsg):Send {
let id = self.id.clone();
let script_chan = self.script_chan.clone();
let f: proc(ImageResponseMsg) = proc(_) {
let f: proc(ImageResponseMsg):Send = proc(_) {
let ScriptChan(chan) = script_chan;
drop(chan.try_send(SendEventMsg(id.clone(), ReflowEvent)))
};
@ -289,7 +290,10 @@ impl LayoutTask {
opts: &Opts,
profiler_chan: ProfilerChan)
-> 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 parallel_traversal = if opts.layout_threads != 1 {
Some(WorkQueue::new("LayoutWorker", opts.layout_threads, ptr::mut_null()))
@ -539,10 +543,14 @@ impl LayoutTask {
debug!("layout: parsed Node tree");
debug!("{:?}", node.dump());
// Reset the image cache.
self.local_image_cache.access(|local_image_cache| {
local_image_cache.next_round(self.make_on_image_available_cb())
});
{
// Reset the image cache.
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
// changed or the window was resized.
@ -654,9 +662,7 @@ impl LayoutTask {
let element_bg_color = {
let thread_safe_child = ThreadSafeLayoutNode::new(&child);
thread_safe_child.style()
.get()
.resolve_color(thread_safe_child.style()
.get()
.Background
.get()
.background_color)
@ -740,7 +746,7 @@ impl LayoutTask {
match self.display_list {
None => fail!("no 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())))
@ -763,7 +769,7 @@ impl LayoutTask {
match self.display_list {
None => fail!("no 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))
@ -811,7 +817,7 @@ impl LayoutTask {
Au::from_frac_px(point.y as f64));
let resp = match self.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() {
reply_chan.send(Ok(resp.unwrap()));
@ -858,7 +864,7 @@ impl LayoutTask {
Some(ref display_list) => {
mouse_over_test(x,
y,
display_list.get().list.as_slice(),
display_list.list.as_slice(),
&mut mouse_over_list);
}
};

View file

@ -14,11 +14,11 @@ use servo_util::geometry;
/// A collapsible margin. See CSS 2.1 § 8.3.1.
pub struct AdjoiningMargins {
/// 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
/// value. Since this is not the absolute value, this is always zero or negative.
most_negative: Au,
pub most_negative: Au,
}
impl AdjoiningMargins {
@ -79,9 +79,9 @@ enum FinalMarginState {
}
pub struct MarginCollapseInfo {
state: MarginCollapseState,
top_margin: AdjoiningMargins,
margin_in: AdjoiningMargins,
pub state: MarginCollapseState,
pub top_margin: AdjoiningMargins,
pub margin_in: AdjoiningMargins,
}
impl MarginCollapseInfo {
@ -101,7 +101,7 @@ impl MarginCollapseInfo {
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,
@ -135,7 +135,7 @@ impl MarginCollapseInfo {
// Different logic is needed here depending on whether this flow can collapse its bottom
// 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 {
match state {
MarginsCollapseThroughFinalMarginState => {
@ -239,12 +239,12 @@ pub enum MarginCollapseState {
/// Intrinsic widths, which consist of minimum and preferred.
pub struct IntrinsicWidths {
/// The *minimum width* of the content.
minimum_width: Au,
pub minimum_width: Au,
/// 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
/// when computing intrinsic widths.
surround_width: Au,
pub surround_width: Au,
}
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.
pub struct DomParallelInfo {
/// The number of children that still need work done.
children_count: AtomicInt,
pub children_count: AtomicInt,
}
impl DomParallelInfo {
@ -104,9 +104,9 @@ impl DomParallelInfo {
/// Information that we need stored in each flow.
pub struct FlowParallelInfo {
/// The number of children that still need work done.
children_count: AtomicInt,
pub children_count: AtomicInt,
/// The address of the parent flow.
parent: UnsafeFlow,
pub parent: UnsafeFlow,
}
impl FlowParallelInfo {
@ -270,7 +270,7 @@ fn recalc_style_for_node(unsafe_layout_node: UnsafeLayoutNode,
// Perform the CSS cascade.
node.cascade_node(parent_opt,
layout_context.initial_css_values.get(),
&*layout_context.initial_css_values,
&applicable_declarations,
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,
/// not table box per CSS 2.1 § 10.5.
pub struct TableFlow {
block_flow: BlockFlow,
pub block_flow: BlockFlow,
/// Column widths
col_widths: ~[Au],
pub col_widths: ~[Au],
/// Column min widths.
col_min_widths: ~[Au],
pub col_min_widths: ~[Au],
/// Column pref widths.
col_pref_widths: ~[Au],
pub col_pref_widths: ~[Au],
/// Table-layout property
table_layout: TableLayout,
pub table_layout: TableLayout,
}
impl TableFlow {
@ -268,10 +268,10 @@ impl Flow for TableFlow {
let width_computer = InternalTable;
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 padding_and_borders = self.block_flow.box_.padding.get().left + self.block_flow.box_.padding.get().right +
self.block_flow.box_.border.get().left + self.block_flow.box_.border.get().right;
let content_width = self.block_flow.box_.border_box.get().size.width - padding_and_borders;
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.borrow().left + self.block_flow.box_.padding.borrow().right +
self.block_flow.box_.border.borrow().left + self.block_flow.box_.border.borrow().right;
let content_width = self.block_flow.box_.border_box.borrow().size.width - padding_and_borders;
match self.table_layout {
FixedLayout => {

View file

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

View file

@ -19,7 +19,7 @@ use servo_util::geometry::Au;
/// A table formatting context.
pub struct TableCellFlow {
/// Data common to all flows.
block_flow: BlockFlow,
pub block_flow: BlockFlow,
}
impl TableCellFlow {
@ -100,10 +100,10 @@ impl Flow for TableCellFlow {
let width_computer = InternalTable;
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 padding_and_borders = self.block_flow.box_.padding.get().left + self.block_flow.box_.padding.get().right +
self.block_flow.box_.border.get().left + self.block_flow.box_.border.get().right;
let content_width = self.block_flow.box_.border_box.get().size.width - padding_and_borders;
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.borrow().left + self.block_flow.box_.padding.borrow().right +
self.block_flow.box_.border.borrow().left + self.block_flow.box_.border.borrow().right;
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);
}

View file

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

View file

@ -22,16 +22,16 @@ use servo_util::geometry;
/// A table formatting context.
pub struct TableRowFlow {
block_flow: BlockFlow,
pub block_flow: BlockFlow,
/// Column widths.
col_widths: ~[Au],
pub col_widths: ~[Au],
/// Column min widths.
col_min_widths: ~[Au],
pub col_min_widths: ~[Au],
/// Column pref widths.
col_pref_widths: ~[Au],
pub col_pref_widths: ~[Au],
}
impl TableRowFlow {
@ -116,18 +116,18 @@ impl TableRowFlow {
// Assign the height of own box
//
// 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;
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;
// Assign the height of kid boxes, which is the same value as own height.
for kid in self.block_flow.base.child_iter() {
{
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;
kid_box_.border_box.set(position);
*kid_box_.border_box.borrow_mut() = position;
}
let child_node = flow::mut_base(kid);
child_node.position.size.height = height;

View file

@ -21,16 +21,16 @@ use servo_util::geometry;
/// A table formatting context.
pub struct TableRowGroupFlow {
block_flow: BlockFlow,
pub block_flow: BlockFlow,
/// Column widths
col_widths: ~[Au],
pub col_widths: ~[Au],
/// Column min widths.
col_min_widths: ~[Au],
pub col_min_widths: ~[Au],
/// Column pref widths.
col_pref_widths: ~[Au],
pub col_pref_widths: ~[Au],
}
impl TableRowGroupFlow {
@ -93,9 +93,9 @@ impl TableRowGroupFlow {
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;
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;
}

View file

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

View file

@ -17,7 +17,7 @@ use sync::Arc;
/// A stack-allocated object for scanning an inline flow into `TextRun`-containing `TextBox`es.
pub struct TextRunScanner {
clump: Range,
pub clump: Range,
}
impl TextRunScanner {
@ -244,7 +244,7 @@ impl TextRunScanner {
}
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,
ScannedTextBox(new_text_box_info));
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 gfx::display_list::OpaqueNode;
use libc::uintptr_t;
use script::dom::bindings::js::JS;
use script::dom::bindings::utils::Reflectable;
use script::dom::node::Node;
@ -16,15 +17,14 @@ use servo_util::range::Range;
use std::cast;
use std::cell::{Ref, RefMut};
use std::iter::Enumerate;
use std::libc::uintptr_t;
use std::slice::Items;
use style::ComputedValues;
use sync::Arc;
/// A range of nodes.
pub struct NodeRange {
node: OpaqueNode,
range: Range,
pub node: OpaqueNode,
pub range: Range,
}
impl NodeRange {
@ -37,7 +37,7 @@ impl NodeRange {
}
pub struct ElementMapping {
priv entries: ~[NodeRange],
entries: ~[NodeRange],
}
impl ElementMapping {
@ -132,27 +132,27 @@ impl ElementMapping {
/// Data that layout associates with a node.
pub struct PrivateLayoutData {
/// 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.
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.
after_style: Option<Arc<ComputedValues>>,
pub after_style: Option<Arc<ComputedValues>>,
/// 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
/// `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.
parallel: DomParallelInfo,
pub parallel: DomParallelInfo,
}
impl PrivateLayoutData {
@ -172,8 +172,8 @@ impl PrivateLayoutData {
}
pub struct LayoutDataWrapper {
chan: Option<LayoutChan>,
data: ~PrivateLayoutData,
pub chan: Option<LayoutChan>,
pub data: ~PrivateLayoutData,
}
/// 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`.
pub struct LayoutNode<'a> {
/// The wrapped node.
priv node: JS<Node>,
node: JS<Node>,
/// Being chained to a value prevents `LayoutNode`s from escaping.
chain: &'a (),
pub chain: &'a (),
}
impl<'ln> Clone for LayoutNode<'ln> {
@ -278,7 +278,7 @@ impl<'ln> TNode<LayoutElement<'ln>> for LayoutNode<'ln> {
}
pub struct LayoutNodeChildrenIterator<'a> {
priv current_node: Option<LayoutNode<'a>>,
current_node: Option<LayoutNode<'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.
pub struct LayoutTreeIterator<'a> {
priv nodes: ~[LayoutNode<'a>],
priv index: uint,
nodes: ~[LayoutNode<'a>],
index: uint,
}
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.
pub struct LayoutElement<'le> {
priv element: &'le Element,
element: &'le Element,
}
impl<'le> LayoutElement<'le> {
@ -409,9 +409,9 @@ pub enum PseudoElementType {
#[deriving(Clone)]
pub struct ThreadSafeLayoutNode<'ln> {
/// The wrapped node.
priv node: LayoutNode<'ln>,
node: LayoutNode<'ln>,
priv pseudo: PseudoElementType,
pseudo: PseudoElementType,
}
impl<'ln> TLayoutNode for ThreadSafeLayoutNode<'ln> {
@ -470,10 +470,10 @@ impl<'ln> TLayoutNode for ThreadSafeLayoutNode<'ln> {
if self.pseudo == Before {
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 {
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 {
Before | BeforeBlock => {
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 => {
let after_style = node_layout_data_wrapper.data.after_style.get_ref();
after_style.get().Box.get().display
after_style.Box.get().display
}
Normal => {
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> {
priv current_node: Option<ThreadSafeLayoutNode<'a>>,
priv parent_node: Option<ThreadSafeLayoutNode<'a>>,
current_node: Option<ThreadSafeLayoutNode<'a>>,
parent_node: Option<ThreadSafeLayoutNode<'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
/// race on elements.
pub struct ThreadSafeLayoutElement<'le> {
priv element: &'le Element,
element: &'le Element,
}
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.
pub struct Pipeline {
id: PipelineId,
subpage_id: Option<SubpageId>,
script_chan: ScriptChan,
layout_chan: LayoutChan,
render_chan: RenderChan,
layout_shutdown_port: Receiver<()>,
render_shutdown_port: Receiver<()>,
pub id: PipelineId,
pub subpage_id: Option<SubpageId>,
pub script_chan: ScriptChan,
pub layout_chan: LayoutChan,
pub render_chan: RenderChan,
pub layout_shutdown_port: Receiver<()>,
pub render_shutdown_port: Receiver<()>,
/// 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.
#[deriving(Clone)]
pub struct CompositionPipeline {
id: PipelineId,
script_chan: ScriptChan,
render_chan: RenderChan,
pub id: PipelineId,
pub script_chan: ScriptChan,
pub render_chan: RenderChan,
}
impl Pipeline {
@ -187,7 +187,7 @@ impl Pipeline {
}
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;
chan.send(LoadMsg(self.id, url));
}

View file

@ -12,10 +12,11 @@ use windowing::RefreshWindowEvent;
use windowing::{Forward, Back};
use alert::{Alert, AlertMethods};
use libc::{exit, c_int};
use time;
use time::Timespec;
use std::cell::{Cell, RefCell};
use std::libc::{exit, c_int};
use std::comm::Receiver;
use std::rc::Rc;
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 glfw;
use glfw::Context;
/// 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 {
fn new() -> Application {
// Per GLFW docs it's safe to set the error callback before calling
// glfwInit(), and this way we notice errors from init too.
glfw::set_error_callback(~glfw::LogErrorHandler);
if glfw::init().is_err() {
// handles things like inability to connect to X
// cannot simply fail, since the runtime isn't up yet (causes a nasty abort)
println!("GLFW initialization failed");
unsafe { exit(1); }
let app = glfw::init(glfw::LOG_ERRORS);
match app {
Err(_) => {
// handles things like inability to connect to X
// cannot simply fail, since the runtime isn't up yet (causes a nasty abort)
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.
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>>,
mouse_down_point: Cell<Point2D<c_int>>,
pub drag_origin: Point2D<c_int>,
ready_state: Cell<ReadyState>,
render_state: Cell<RenderState>,
pub mouse_down_button: Cell<Option<glfw::MouseButton>>,
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 {
/// Creates a new window.
fn new(_: &Application) -> Rc<Window> {
fn new(app: &Application) -> Rc<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");
glfw_window.make_context_current();
glfw_window.make_current();
// Create our window object.
let window = Window {
glfw: app.glfw,
glfw_window: glfw_window,
events: events,
event_queue: RefCell::new(~[]),
@ -151,8 +161,8 @@ impl WindowMethods<Application> for Window {
}
}
glfw::poll_events();
for (_, event) in self.glfw_window.flush_events() {
self.glfw.poll_events();
for (_, event) in glfw::flush_messages(&self.events) {
self.handle_window_event(&self.glfw_window, event);
}

View file

@ -11,8 +11,8 @@ use windowing::{MouseWindowClickEvent, MouseWindowMouseDownEvent, MouseWindowMou
use windowing::{Forward, Back};
use alert::{Alert, AlertMethods};
use libc::{c_int, c_uchar};
use std::cell::{Cell, RefCell};
use std::libc::{c_int, c_uchar};
use std::local_data;
use std::rc::Rc;
use geom::point::Point2D;
@ -45,18 +45,18 @@ impl Drop for Application {
/// The type of a 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>,
mouse_down_point: Cell<Point2D<c_int>>,
pub mouse_down_button: Cell<c_int>,
pub mouse_down_point: Cell<Point2D<c_int>>,
ready_state: Cell<ReadyState>,
render_state: Cell<RenderState>,
throbber_frame: Cell<u8>,
pub ready_state: Cell<ReadyState>,
pub render_state: Cell<RenderState>,
pub throbber_frame: Cell<u8>,
}
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
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#[crate_id = "github.com/mozilla/servo"];
#[comment = "The Servo Parallel Browser Project"];
#[license = "MPL"];
#![crate_id = "github.com/mozilla/servo"]
#![comment = "The Servo Parallel Browser Project"]
#![license = "MPL"]
#[feature(globs, macro_rules, phase, thread_local)];
#![feature(globs, macro_rules, phase, thread_local)]
#[feature(phase)];
#![feature(phase)]
#[phase(syntax, link)]
extern crate log;
@ -17,7 +17,7 @@ extern crate azure;
extern crate geom;
extern crate gfx;
#[cfg(not(target_os="android"))]
extern crate glfw = "glfw-rs";
extern crate glfw;
#[cfg(target_os="android")]
extern crate glut;
extern crate js;
@ -37,6 +37,7 @@ extern crate stb_image;
extern crate collections;
extern crate green;
extern crate libc;
extern crate native;
extern crate serialize;
extern crate sync;
@ -158,7 +159,9 @@ pub extern "C" fn android_start(argc: int, argv: **u8) -> int {
#[cfg(not(test))]
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 profiler_chan = Profiler::create(opts.profiler_period);

View file

@ -17,25 +17,25 @@ use constellation_msg::PipelineId;
pub struct LayerBuffer {
/// 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`.
native_surface: NativeSurface,
pub native_surface: NativeSurface,
/// 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.
screen_pos: Rect<uint>,
pub screen_pos: Rect<uint>,
/// The scale at which this tile is rendered
resolution: f32,
pub resolution: f32,
/// 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
/// buffers.
pub struct LayerBufferSet {
buffers: ~[~LayerBuffer]
pub buffers: ~[~LayerBuffer]
}
impl LayerBufferSet {
@ -68,7 +68,7 @@ pub enum ReadyState {
/// A newtype struct for denoting the age of messages; prevents race conditions.
#[deriving(Eq)]
pub struct Epoch(uint);
pub struct Epoch(pub uint);
impl Epoch {
pub fn next(&mut self) {
@ -78,7 +78,7 @@ impl Epoch {
}
#[deriving(Clone, Eq)]
pub struct LayerId(uint, uint);
pub struct LayerId(pub uint, pub uint);
impl Show for LayerId {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
@ -108,13 +108,13 @@ pub enum ScrollPolicy {
/// buffer contents of the layer itself.
pub struct LayerMetadata {
/// 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.
position: Rect<uint>,
pub position: Rect<uint>,
/// The background color of the layer.
background_color: Color,
pub background_color: Color,
/// 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
@ -158,8 +158,9 @@ pub trait ScriptListener : Clone {
fn dup(&self) -> ~ScriptListener;
}
impl<S: Encoder> Encodable<S> for ~ScriptListener {
fn encode(&self, _s: &mut S) {
impl<E, S: Encoder<E>> Encodable<S, E> for ~ScriptListener {
fn encode(&self, _s: &mut S) -> Result<(), E> {
Ok(())
}
}

View file

@ -11,7 +11,7 @@ use std::comm::{channel, Sender, Receiver};
use url::Url;
#[deriving(Clone)]
pub struct ConstellationChan(Sender<Msg>);
pub struct ConstellationChan(pub Sender<Msg>);
impl 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.
#[deriving(Clone)]
pub struct Failure {
pipeline_id: PipelineId,
subpage_id: Option<SubpageId>,
pub pipeline_id: PipelineId,
pub subpage_id: Option<SubpageId>,
}
/// Messages from the compositor and script to the constellation.
@ -61,7 +61,7 @@ pub enum NavigationDirection {
}
#[deriving(Clone, Eq, TotalEq, Hash, Encodable)]
pub struct PipelineId(uint);
pub struct PipelineId(pub uint);
#[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
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#[crate_id = "github.com/mozilla/servo#msg:0.1"];
#[crate_type = "lib"];
#[crate_type = "dylib"];
#[crate_type = "rlib"];
#![crate_id = "github.com/mozilla/servo#msg:0.1"]
#![crate_type = "lib"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
extern crate azure;
extern crate geom;

View file

@ -25,7 +25,7 @@ fn load(url: Url, start_chan: Sender<LoadResponse>) {
let mut metadata = Metadata::default(url.clone());
// 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 {
start_sending(start_chan, metadata).send(Done(Err(())));
return;

View file

@ -14,9 +14,9 @@ static READ_SIZE: uint = 1;
fn read_all(reader: &mut io::Stream, progress_chan: &Sender<ProgressMsg>)
-> Result<(), ()> {
loop {
let mut buf = ~[];
let mut buf = Vec::new();
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 {
io::EndOfFile => return Ok(()),
_ => return Err(()),

View file

@ -5,11 +5,10 @@
use resource_task::{Metadata, Payload, Done, LoadResponse, LoaderTask, start_sending};
use collections::hashmap::HashSet;
use http::client::RequestWriter;
use http::client::{RequestWriter, NetworkStream};
use http::method::Get;
use http::headers::HeaderEnum;
use std::io::Reader;
use std::io::net::tcp::TcpStream;
use std::slice;
use servo_util::task::spawn_named;
use url::Url;
@ -60,7 +59,7 @@ fn load(mut url: Url, start_chan: Sender<LoadResponse>) {
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 {
Ok(w) => ~w,
Err(_) => {

View file

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

View file

@ -7,12 +7,13 @@ use resource_task;
use resource_task::ResourceTask;
use servo_util::url::{UrlMap, url_map};
use std::cast;
use std::comm::{channel, Receiver, Sender};
use std::mem::replace;
use std::task::spawn;
use std::to_str::ToStr;
use std::result;
use sync::{Arc,MutexArc};
use sync::{Arc, Mutex};
use serialize::{Encoder, Encodable};
use url::Url;
@ -81,8 +82,9 @@ pub struct ImageCacheTask {
chan: Sender<Msg>,
}
impl<S: Encoder> Encodable<S> for ImageCacheTask {
fn encode(&self, _: &mut S) {
impl<E, S: Encoder<E>> Encodable<S, E> for ImageCacheTask {
fn encode(&self, _: &mut S) -> Result<(), E> {
Ok(())
}
}
@ -147,7 +149,8 @@ struct ImageCache {
/// The state of processsing an image for a URL
state_map: UrlMap<ImageState>,
/// 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<()>>,
}
@ -375,11 +378,17 @@ impl ImageCache {
fn purge_waiters(&mut self, url: Url, f: || -> ImageResponseMsg) {
match self.wait_map.pop(&url) {
Some(waiters) => {
waiters.access(|waiters| {
for response in waiters.iter() {
response.send(f());
}
});
let val = waiters.lock();
let items = unsafe {
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 => ()
}
@ -407,9 +416,23 @@ impl ImageCache {
if self.wait_map.contains_key(&url) {
let waiters = self.wait_map.find_mut(&url).unwrap();
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 {
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();
spawn(proc() {
@ -504,13 +527,79 @@ mod tests {
use std::comm;
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>) {
loop {
match port.recv() {
resource_task::Load(_, response) => {
let chan = start_sending(response, Metadata::default(parse_url("file:///fake", None)));
on_load(chan);
on_load.invoke(chan);
}
resource_task::Exit => break
}
@ -520,7 +609,7 @@ mod tests {
#[test]
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 _url = parse_url("file", None);
@ -532,7 +621,7 @@ mod tests {
#[test]
#[should_fail]
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 url = parse_url("file", None);
@ -546,10 +635,7 @@ mod tests {
fn should_request_url_from_resource_task_on_prefetch() {
let (url_requested_chan, url_requested) = channel();
let mock_resource_task = mock_resource_task(proc(response) {
url_requested_chan.send(());
response.send(resource_task::Done(Ok(())));
});
let mock_resource_task = mock_resource_task(~JustSendOK { url_requested_chan: url_requested_chan});
let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None);
@ -564,10 +650,7 @@ mod tests {
fn should_not_request_url_from_resource_task_on_multiple_prefetches() {
let (url_requested_chan, url_requested) = comm::channel();
let mock_resource_task = mock_resource_task(proc(response) {
url_requested_chan.send(());
response.send(resource_task::Done(Ok(())));
});
let mock_resource_task = mock_resource_task(~JustSendOK { url_requested_chan: url_requested_chan});
let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None);
@ -587,13 +670,7 @@ mod tests {
fn should_return_image_not_ready_if_data_has_not_arrived() {
let (wait_chan, wait_port) = comm::channel();
let mock_resource_task = mock_resource_task(proc(response) {
// 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 mock_resource_task = mock_resource_task(~WaitSendTestImage{wait_port: wait_port});
let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None);
@ -610,10 +687,7 @@ mod tests {
#[test]
fn should_return_decoded_image_data_if_data_has_arrived() {
let mock_resource_task = mock_resource_task(proc(response) {
response.send(resource_task::Payload(test_image_bin()));
response.send(resource_task::Done(Ok(())));
});
let mock_resource_task = mock_resource_task(~SendTestImage);
let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None);
@ -639,10 +713,7 @@ mod tests {
#[test]
fn should_return_decoded_image_data_for_multiple_requests() {
let mock_resource_task = mock_resource_task(proc(response) {
response.send(resource_task::Payload(test_image_bin()));
response.send(resource_task::Done(Ok(())));
});
let mock_resource_task = mock_resource_task(~SendTestImage);
let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None);
@ -764,11 +835,7 @@ mod tests {
#[test]
fn should_return_failed_if_image_bin_cannot_be_fetched() {
let mock_resource_task = mock_resource_task(proc(response) {
response.send(resource_task::Payload(test_image_bin()));
// ERROR fetching image
response.send(resource_task::Done(Err(())));
});
let mock_resource_task = mock_resource_task(~SendTestImageErr);
let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None);
@ -794,11 +861,7 @@ mod tests {
#[test]
fn should_return_failed_for_multiple_get_image_requests_if_image_bin_cannot_be_fetched() {
let mock_resource_task = mock_resource_task(proc(response) {
response.send(resource_task::Payload(test_image_bin()));
// ERROR fetching image
response.send(resource_task::Done(Err(())));
});
let mock_resource_task = mock_resource_task(~SendTestImageErr);
let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None);
@ -832,11 +895,7 @@ mod tests {
#[test]
fn should_return_failed_if_image_decode_fails() {
let mock_resource_task = mock_resource_task(proc(response) {
// Bogus data
response.send(resource_task::Payload(~[]));
response.send(resource_task::Done(Ok(())));
});
let mock_resource_task = mock_resource_task(~SendBogusImage);
let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None);
@ -864,10 +923,7 @@ mod tests {
#[test]
fn should_return_image_on_wait_if_image_is_already_loaded() {
let mock_resource_task = mock_resource_task(proc(response) {
response.send(resource_task::Payload(test_image_bin()));
response.send(resource_task::Done(Ok(())));
});
let mock_resource_task = mock_resource_task(~SendTestImage);
let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None);
@ -895,11 +951,7 @@ mod tests {
fn should_return_image_on_wait_if_image_is_not_yet_loaded() {
let (wait_chan, wait_port) = comm::channel();
let mock_resource_task = mock_resource_task(proc(response) {
wait_port.recv();
response.send(resource_task::Payload(test_image_bin()));
response.send(resource_task::Done(Ok(())));
});
let mock_resource_task = mock_resource_task(~WaitSendTestImage {wait_port: wait_port});
let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None);
@ -925,11 +977,7 @@ mod tests {
fn should_return_image_failed_on_wait_if_image_fails_to_load() {
let (wait_chan, wait_port) = comm::channel();
let mock_resource_task = mock_resource_task(proc(response) {
wait_port.recv();
response.send(resource_task::Payload(test_image_bin()));
response.send(resource_task::Done(Err(())));
});
let mock_resource_task = mock_resource_task(~WaitSendTestImageErr{wait_port: wait_port});
let image_cache_task = ImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None);
@ -953,10 +1001,7 @@ mod tests {
#[test]
fn sync_cache_should_wait_for_images() {
let mock_resource_task = mock_resource_task(proc(response) {
response.send(resource_task::Payload(test_image_bin()));
response.send(resource_task::Done(Ok(())));
});
let mock_resource_task = mock_resource_task(~SendTestImage);
let image_cache_task = SyncImageCacheTask(mock_resource_task.clone());
let url = parse_url("file", None);

View file

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

View file

@ -2,24 +2,22 @@
* 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/. */
#[crate_id = "github.com/mozilla/servo#net:0.1"];
#[crate_type = "lib"];
#[crate_type = "dylib"];
#[crate_type = "rlib"];
#![crate_id = "github.com/mozilla/servo#net:0.1"]
#![crate_type = "lib"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#[feature(globs)];
#[feature(phase)];
#[phase(syntax, link)]
extern crate log;
#![feature(default_type_params, globs, managed_boxes, phase)]
extern crate collections;
extern crate geom;
extern crate http;
extern crate png;
#[phase(syntax, link)]
extern crate log;
extern crate serialize;
extern crate servo_util = "util";
extern crate stb_image;
extern crate png;
extern crate serialize;
extern crate sync;
extern crate url;

View file

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

View file

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

View file

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

View file

@ -8,8 +8,8 @@ use js::jsapi::{JS_GetProperty, JSTracer, JS_CallTracer};
use js::jsval::{JSVal, UndefinedValue};
use js::JSTRACE_OBJECT;
use libc;
use std::cast;
use std::libc;
use std::ptr;
use serialize::{Encodable, Encoder};
@ -27,11 +27,11 @@ pub enum ExceptionHandling {
#[deriving(Clone,Eq)]
pub struct CallbackInterface {
callback: *JSObject
pub callback: *JSObject
}
impl<S: Encoder> Encodable<S> for CallbackInterface {
fn encode(&self, s: &mut S) {
impl<S: Encoder<E>, E> Encodable<S, E> for CallbackInterface {
fn encode(&self, s: &mut S) -> Result<(), E> {
unsafe {
let tracer: *mut JSTracer = cast::transmute(s);
"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;
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 {
cx: *JSContext,
handling: ExceptionHandling
pub cx: *JSContext,
pub handling: ExceptionHandling
}
impl CallSetup {

View file

@ -1394,7 +1394,7 @@ class CGImports(CGWrapper):
'dead_code',
]
statements = ['#[allow(%s)];' % ','.join(ignored_warnings)]
statements = ['#![allow(%s)]' % ','.join(ignored_warnings)]
statements.extend('use %s;' % i for i in sorted(imports))
CGWrapper.__init__(self, child,
@ -4076,11 +4076,11 @@ class CGDictionary(CGThing):
def struct(self):
d = self.dictionary
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))
else:
inheritance = ""
memberDecls = [" %s: %s," %
memberDecls = [" pub %s: %s," %
(self.makeMemberName(m[0].identifier.name), self.getMemberType(m))
for m in self.memberInfo]
@ -4344,11 +4344,11 @@ class CGBindingRoot(CGThing):
'dom::bindings::proxyhandler::{_obj_toString, defineProperty}',
'dom::bindings::proxyhandler::{FillPropertyDescriptor, GetExpandoObject}',
'dom::bindings::proxyhandler::{getPropertyDescriptor}',
'libc',
'servo_util::str::DOMString',
'servo_util::vec::zip_copies',
'std::cast',
'std::cmp',
'std::libc',
'std::ptr',
'std::slice',
'std::str',
@ -5282,7 +5282,7 @@ class GlobalGenRoots():
def InheritTypes(config):
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::bindings::js::JS;\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::{StringValue, ObjectValue};
use js::glue::RUST_JS_NumberValue;
use libc;
use std::default::Default;
use std::libc;
use dom::bindings::codegen::PrototypeList;

View file

@ -11,7 +11,7 @@ use std::cast;
use std::cell::RefCell;
pub struct JS<T> {
priv ptr: RefCell<*mut T>
ptr: RefCell<*mut 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::{JSPROP_GETTER, JSPROP_ENUMERATE, JSPROP_READONLY, JSRESOLVE_QUALIFIED};
use libc;
use std::cast;
use std::libc;
use std::ptr;
use std::str;
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 libc;
use std::cast;
use std::cell::RefCell;
use std::libc;
use std::ptr;
use std::ptr::null;
use serialize::{Encodable, Encoder};
@ -19,20 +19,22 @@ use serialize::{Encodable, Encoder};
// we are unfortunately required to use generic types everywhere and
// 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 {
cast::transmute(s)
}
}
impl<T: Reflectable+Encodable<S>, S: Encoder> Encodable<S> for JS<T> {
fn encode(&self, s: &mut S) {
impl<T: Reflectable+Encodable<S, E>, S: Encoder<E>, E> Encodable<S, E> for JS<T> {
fn encode(&self, s: &mut S) -> Result<(), E> {
trace_reflector(get_jstracer(s), "", self.reflector());
Ok(())
}
}
impl<S: Encoder> Encodable<S> for Reflector {
fn encode(&self, _s: &mut S) {
impl<S: Encoder<E>, E> Encodable<S, E> for Reflector {
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
/// fields of types associated with JS reflectors.
pub struct Untraceable<T> {
priv inner: T,
inner: T,
}
impl<T> Untraceable<T> {
@ -72,8 +74,9 @@ impl<T> Untraceable<T> {
}
}
impl<S: Encoder, T> Encodable<S> for Untraceable<T> {
fn encode(&self, _s: &mut S) {
impl<S: Encoder<E>, E, T> Encodable<S, E> for Untraceable<T> {
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
/// for that new concrete type to achieve magic compiler-derived trace hooks.
pub struct Traceable<T> {
priv inner: T
inner: 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>> {
fn encode(&self, s: &mut S) {
self.borrow().encode(s)
impl<S: Encoder<E>, E, T: Encodable<S, E>> Encodable<S, E> for Traceable<RefCell<T>> {
fn encode(&self, s: &mut S) -> Result<(), E> {
self.borrow().encode(s);
Ok(())
}
}
impl<S: Encoder> Encodable<S> for Traceable<*JSObject> {
fn encode(&self, s: &mut S) {
trace_object(get_jstracer(s), "object", **self)
impl<S: Encoder<E>, E> Encodable<S, E> for Traceable<*JSObject> {
fn encode(&self, s: &mut S) -> Result<(), E> {
trace_object(get_jstracer(s), "object", **self);
Ok(())
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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