Upgrade to rustc 551a74dddd84cf01440ee84148ebd18bc68bd7c8.

This commit is contained in:
Simon Sapin 2015-04-23 00:14:02 +02:00 committed by Josh Matthews
parent 7b87085c18
commit ef8edd4e87
168 changed files with 2247 additions and 2408 deletions

View file

@ -1 +1 @@
2015-03-11 2015-04-14

View file

@ -10,9 +10,6 @@ path = "lib.rs"
[dependencies.azure] [dependencies.azure]
git = "https://github.com/servo/rust-azure" git = "https://github.com/servo/rust-azure"
[dependencies.cssparser]
git = "https://github.com/servo/rust-cssparser"
[dependencies.geom] [dependencies.geom]
git = "https://github.com/servo/rust-geom" git = "https://github.com/servo/rust-geom"
@ -31,4 +28,8 @@ branch = "servo"
features = ["headless"] features = ["headless"]
[dependencies.offscreen_gl_context] [dependencies.offscreen_gl_context]
git = "https://github.com/ecoal95/rust-offscreen-rendering-context" git = "https://github.com/servo/rust-offscreen-rendering-context"
[dependencies]
cssparser = "0.3.1"
num = "0.1.24"

View file

@ -13,13 +13,13 @@ use geom::point::Point2D;
use geom::rect::Rect; use geom::rect::Rect;
use geom::size::Size2D; use geom::size::Size2D;
use gfx::color; use gfx::color;
use num::ToPrimitive;
use util::task::spawn_named; use util::task::spawn_named;
use util::vec::byte_swap; use util::vec::byte_swap;
use cssparser::RGBA; use cssparser::RGBA;
use std::borrow::ToOwned; use std::borrow::ToOwned;
use std::mem; use std::mem;
use std::num::{Float, ToPrimitive};
use std::sync::mpsc::{channel, Sender}; use std::sync::mpsc::{channel, Sender};
impl<'a> CanvasPaintTask<'a> { impl<'a> CanvasPaintTask<'a> {

View file

@ -2,9 +2,8 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(collections)]
#![feature(core)] #![feature(core)]
#![feature(std_misc)] #![feature(collections)]
#![feature(rustc_private)] #![feature(rustc_private)]
extern crate azure; extern crate azure;
@ -13,6 +12,7 @@ extern crate geom;
extern crate gfx; extern crate gfx;
extern crate util; extern crate util;
extern crate gleam; extern crate gleam;
extern crate num;
extern crate offscreen_gl_context; extern crate offscreen_gl_context;
extern crate glutin; extern crate glutin;

View file

@ -163,7 +163,7 @@ impl WebGLPaintTask {
} }
fn get_attrib_location(&self, program_id: u32, name: String, chan: Sender<i32> ) { fn get_attrib_location(&self, program_id: u32, name: String, chan: Sender<i32> ) {
let attrib_location = gl::get_attrib_location(program_id, name.as_slice()); let attrib_location = gl::get_attrib_location(program_id, &name);
chan.send(attrib_location).unwrap(); chan.send(attrib_location).unwrap();
} }
@ -178,7 +178,7 @@ impl WebGLPaintTask {
} }
fn get_uniform_location(&self, program_id: u32, name: String, chan: Sender<u32>) { fn get_uniform_location(&self, program_id: u32, name: String, chan: Sender<u32>) {
let uniform_location = gl::get_uniform_location(program_id, name.as_slice()); let uniform_location = gl::get_uniform_location(program_id, &name);
chan.send(uniform_location as u32).unwrap(); chan.send(uniform_location as u32).unwrap();
} }
@ -202,8 +202,7 @@ impl WebGLPaintTask {
let dst_start = y * stride; let dst_start = y * stride;
let src_start = (height - y - 1) * stride; let src_start = (height - y - 1) * stride;
let src_slice = &orig_pixels[src_start .. src_start + stride]; let src_slice = &orig_pixels[src_start .. src_start + stride];
copy_memory(&mut pixels[dst_start .. dst_start + stride], copy_memory(&src_slice[..stride], &mut pixels[dst_start .. dst_start + stride]);
&src_slice[..stride]);
} }
// rgba -> bgra // rgba -> bgra
@ -213,7 +212,7 @@ impl WebGLPaintTask {
fn shader_source(&self, shader_id: u32, source_lines: Vec<String>) { fn shader_source(&self, shader_id: u32, source_lines: Vec<String>) {
let mut lines: Vec<&[u8]> = source_lines.iter().map(|line| line.as_bytes()).collect(); let mut lines: Vec<&[u8]> = source_lines.iter().map(|line| line.as_bytes()).collect();
gl::shader_source(shader_id, lines.as_mut_slice()); gl::shader_source(shader_id, &mut lines);
} }
fn uniform_4fv(&self, uniform_id: u32, data: Vec<f32>) { fn uniform_4fv(&self, uniform_id: u32, data: Vec<f32>) {

View file

@ -59,7 +59,7 @@ git = "https://github.com/servo/rust-core-text"
git = "https://github.com/servo/gleam" git = "https://github.com/servo/gleam"
[dependencies.clipboard] [dependencies.clipboard]
git = "https://github.com/aweinstock314/rust-x11-clipboard" git = "https://github.com/servo/rust-x11-clipboard"
[dependencies] [dependencies]
url = "0.2.16" url = "0.2.16"

View file

@ -39,7 +39,6 @@ use std::cmp;
use std::collections::HashMap; use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::mem as std_mem; use std::mem as std_mem;
use std::num::Float;
use std::rc::Rc; use std::rc::Rc;
use std::slice::bytes::copy_memory; use std::slice::bytes::copy_memory;
use std::sync::mpsc::Sender; use std::sync::mpsc::Sender;
@ -1189,8 +1188,8 @@ impl<Window: WindowMethods> IOCompositor<Window> {
let dst_start = y * stride; let dst_start = y * stride;
let src_start = (height - y - 1) * stride; let src_start = (height - y - 1) * stride;
let src_slice = &orig_pixels[src_start .. src_start + stride]; let src_slice = &orig_pixels[src_start .. src_start + stride];
copy_memory(&mut pixels[dst_start .. dst_start + stride], copy_memory(&src_slice[..stride],
&src_slice[..stride]); &mut pixels[dst_start .. dst_start + stride]);
} }
let mut img = png::Image { let mut img = png::Image {
width: width as u32, width: width as u32,

View file

@ -20,7 +20,6 @@ use script_traits::CompositorEvent::{ClickEvent, MouseDownEvent, MouseMoveEvent,
use script_traits::{ScriptControlChan, ConstellationControlMsg}; use script_traits::{ScriptControlChan, ConstellationControlMsg};
use msg::compositor_msg::{Epoch, LayerId, ScrollPolicy}; use msg::compositor_msg::{Epoch, LayerId, ScrollPolicy};
use msg::constellation_msg::PipelineId; use msg::constellation_msg::PipelineId;
use std::num::Float;
use std::rc::Rc; use std::rc::Rc;
pub struct CompositorData { pub struct CompositorData {
@ -63,6 +62,7 @@ impl CompositorData {
Rc::new(Layer::new(Rect::from_untyped(&layer_properties.rect), Rc::new(Layer::new(Rect::from_untyped(&layer_properties.rect),
tile_size, tile_size,
to_layers_color(&layer_properties.background_color), to_layers_color(&layer_properties.background_color),
1.0,
new_compositor_data)) new_compositor_data))
} }
} }

View file

@ -4,10 +4,7 @@
#![feature(box_syntax)] #![feature(box_syntax)]
#![feature(core)] #![feature(core)]
#![feature(io)]
#![feature(old_io)]
#![feature(rustc_private)] #![feature(rustc_private)]
#![feature(std_misc)]
#[macro_use] #[macro_use]
extern crate log; extern crate log;

View file

@ -6,10 +6,8 @@
use compositor_task::{CompositorProxy, Msg}; use compositor_task::{CompositorProxy, Msg};
use std::old_io::timer;
use std::sync::mpsc::{Receiver, Sender, channel}; use std::sync::mpsc::{Receiver, Sender, channel};
use std::thread::Builder; use std::thread::{Builder, sleep_ms};
use std::time::duration::Duration;
use time; use time;
/// The amount of time in nanoseconds that we give to the painting thread to paint new tiles upon /// The amount of time in nanoseconds that we give to the painting thread to paint new tiles upon
@ -61,8 +59,8 @@ impl ScrollingTimer {
match self.receiver.recv() { match self.receiver.recv() {
Ok(ToScrollingTimerMsg::ScrollEventProcessedMsg(timestamp)) => { Ok(ToScrollingTimerMsg::ScrollEventProcessedMsg(timestamp)) => {
let target = timestamp as i64 + TIMEOUT; let target = timestamp as i64 + TIMEOUT;
let delta = target - (time::precise_time_ns() as i64); let delta_ns = target - (time::precise_time_ns() as i64);
timer::sleep(Duration::nanoseconds(delta)); sleep_ms((delta_ns / 1000) as u32);
self.compositor_proxy.send(Msg::ScrollTimeout(timestamp)); self.compositor_proxy.send(Msg::ScrollTimeout(timestamp));
} }
Ok(ToScrollingTimerMsg::ExitMsg) | Err(_) => break, Ok(ToScrollingTimerMsg::ExitMsg) | Err(_) => break,

View file

@ -8,6 +8,7 @@ use rustc_serialize::json;
use std::any::{Any, TypeId}; use std::any::{Any, TypeId};
use std::collections::HashMap; use std::collections::HashMap;
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
use std::marker::Reflect;
use std::mem::{replace, transmute}; use std::mem::{replace, transmute};
use std::net::TcpStream; use std::net::TcpStream;
use std::raw::TraitObject; use std::raw::TraitObject;
@ -26,10 +27,10 @@ pub trait Actor: Any {
fn name(&self) -> String; fn name(&self) -> String;
} }
impl Actor { impl Actor + Send {
/// Returns true if the boxed type is the same as `T` /// Returns true if the boxed type is the same as `T`
#[inline] #[inline]
pub fn is<T: 'static>(&self) -> bool { pub fn is<T: Reflect + 'static>(&self) -> bool {
// Get TypeId of the type this function is instantiated with // Get TypeId of the type this function is instantiated with
let t = TypeId::of::<T>(); let t = TypeId::of::<T>();
@ -43,7 +44,7 @@ impl Actor {
/// Returns some reference to the boxed value if it is of type `T`, or /// Returns some reference to the boxed value if it is of type `T`, or
/// `None` if it isn't. /// `None` if it isn't.
#[inline] #[inline]
pub fn downcast_ref<T: 'static>(&self) -> Option<&T> { pub fn downcast_ref<T: Reflect + 'static>(&self) -> Option<&T> {
if self.is::<T>() { if self.is::<T>() {
unsafe { unsafe {
// Get the raw representation of the trait object // Get the raw representation of the trait object
@ -60,7 +61,7 @@ impl Actor {
/// Returns some mutable reference to the boxed value if it is of type `T`, or /// Returns some mutable reference to the boxed value if it is of type `T`, or
/// `None` if it isn't. /// `None` if it isn't.
#[inline] #[inline]
pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> { pub fn downcast_mut<T: Reflect + 'static>(&mut self) -> Option<&mut T> {
if self.is::<T>() { if self.is::<T>() {
unsafe { unsafe {
// Get the raw representation of the trait object // Get the raw representation of the trait object
@ -168,13 +169,13 @@ impl ActorRegistry {
} }
/// Find an actor by registered name /// Find an actor by registered name
pub fn find<'a, T: 'static>(&'a self, name: &str) -> &'a T { pub fn find<'a, T: Reflect + 'static>(&'a self, name: &str) -> &'a T {
let actor = self.actors.get(&name.to_string()).unwrap(); let actor = self.actors.get(&name.to_string()).unwrap();
actor.downcast_ref::<T>().unwrap() actor.downcast_ref::<T>().unwrap()
} }
/// Find an actor by registered name /// Find an actor by registered name
pub fn find_mut<'a, T: 'static>(&'a mut self, name: &str) -> &'a mut T { pub fn find_mut<'a, T: Reflect + 'static>(&'a mut self, name: &str) -> &'a mut T {
let actor = self.actors.get_mut(&name.to_string()).unwrap(); let actor = self.actors.get_mut(&name.to_string()).unwrap();
actor.downcast_mut::<T>().unwrap() actor.downcast_mut::<T>().unwrap()
} }

View file

@ -18,7 +18,6 @@ use collections::BTreeMap;
use core::cell::RefCell; use core::cell::RefCell;
use rustc_serialize::json::{self, Json, ToJson}; use rustc_serialize::json::{self, Json, ToJson};
use std::net::TcpStream; use std::net::TcpStream;
use std::num::Float;
use std::sync::mpsc::{channel, Sender}; use std::sync::mpsc::{channel, Sender};
#[derive(RustcEncodable)] #[derive(RustcEncodable)]
@ -251,7 +250,7 @@ impl Actor for ConsoleActor {
m.insert("type".to_string(), "Infinity".to_string().to_json()); m.insert("type".to_string(), "Infinity".to_string().to_json());
} }
Json::Object(m) Json::Object(m)
} else if val == Float::neg_zero() { } else if val == 0. && val.is_sign_negative() {
let mut m = BTreeMap::new(); let mut m = BTreeMap::new();
m.insert("type".to_string(), "-0".to_string().to_json()); m.insert("type".to_string(), "-0".to_string().to_json());
Json::Object(m) Json::Object(m)

View file

@ -16,7 +16,6 @@ use msg::constellation_msg::PipelineId;
use rustc_serialize::json::{self, Json, ToJson}; use rustc_serialize::json::{self, Json, ToJson};
use std::cell::RefCell; use std::cell::RefCell;
use std::net::TcpStream; use std::net::TcpStream;
use std::num::Float;
use std::sync::mpsc::{channel, Sender}; use std::sync::mpsc::{channel, Sender};
pub struct InspectorActor { pub struct InspectorActor {

View file

@ -2,15 +2,14 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use core::iter::FromIterator;
use msg::constellation_msg::PipelineId; use msg::constellation_msg::PipelineId;
use rustc_serialize::{json, Encoder, Encodable}; use rustc_serialize::{json, Encoder, Encodable};
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::{HashMap, VecDeque}; use std::collections::{HashMap, VecDeque};
use std::mem;
use std::net::TcpStream; use std::net::TcpStream;
use std::old_io::timer::sleep; use std::thread::sleep_ms;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::time::duration::Duration;
use std::sync::mpsc::{channel, Sender, Receiver}; use std::sync::mpsc::{channel, Sender, Receiver};
use time::PreciseTime; use time::PreciseTime;
@ -117,7 +116,7 @@ impl Encodable for HighResolutionStamp {
} }
} }
static DEFAULT_TIMELINE_DATA_PULL_TIMEOUT: usize = 200; //ms static DEFAULT_TIMELINE_DATA_PULL_TIMEOUT: u32 = 200; //ms
impl TimelineActor { impl TimelineActor {
pub fn new(name: String, pub fn new(name: String,
@ -214,7 +213,7 @@ impl TimelineActor {
} }
emitter.send(); emitter.send();
sleep(Duration::milliseconds(DEFAULT_TIMELINE_DATA_PULL_TIMEOUT as i64)); sleep_ms(DEFAULT_TIMELINE_DATA_PULL_TIMEOUT);
} }
}); });
} }
@ -344,7 +343,7 @@ impl Emitter {
let end_time = PreciseTime::now(); let end_time = PreciseTime::now();
let reply = MarkersEmitterReply { let reply = MarkersEmitterReply {
__type__: "markers".to_string(), __type__: "markers".to_string(),
markers: Vec::from_iter(self.markers.drain()), markers: mem::replace(&mut self.markers, Vec::new()),
from: self.from.clone(), from: self.from.clone(),
endTime: HighResolutionStamp::new(self.start_stamp, end_time), endTime: HighResolutionStamp::new(self.start_stamp, end_time),
}; };

View file

@ -11,10 +11,7 @@
#![crate_type = "rlib"] #![crate_type = "rlib"]
#![feature(box_syntax, core, rustc_private)] #![feature(box_syntax, core, rustc_private)]
#![feature(collections, std_misc)] #![feature(collections)]
#![feature(io)]
#![feature(net)]
#![feature(old_io)]
#![allow(non_snake_case)] #![allow(non_snake_case)]
@ -24,7 +21,7 @@ extern crate log;
extern crate collections; extern crate collections;
extern crate core; extern crate core;
extern crate devtools_traits; extern crate devtools_traits;
extern crate "rustc-serialize" as rustc_serialize; extern crate rustc_serialize;
extern crate msg; extern crate msg;
extern crate time; extern crate time;
extern crate util; extern crate util;
@ -46,6 +43,7 @@ use util::task::spawn_named;
use std::borrow::ToOwned; use std::borrow::ToOwned;
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::HashMap; use std::collections::HashMap;
use std::error::Error;
use std::sync::mpsc::{channel, Receiver, Sender, RecvError}; use std::sync::mpsc::{channel, Receiver, Sender, RecvError};
use std::net::{TcpListener, TcpStream, Shutdown}; use std::net::{TcpListener, TcpStream, Shutdown};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
@ -128,7 +126,7 @@ fn run_server(sender: Sender<DevtoolsControlMsg>,
'outer: loop { 'outer: loop {
match stream.read_json_packet() { match stream.read_json_packet() {
Ok(json_packet) => { Ok(Some(json_packet)) => {
match actors.lock().unwrap().handle_message(json_packet.as_object().unwrap(), match actors.lock().unwrap().handle_message(json_packet.as_object().unwrap(),
&mut stream) { &mut stream) {
Ok(()) => {}, Ok(()) => {},
@ -139,6 +137,10 @@ fn run_server(sender: Sender<DevtoolsControlMsg>,
} }
} }
} }
Ok(None) => {
println!("error: EOF");
break 'outer
}
Err(e) => { Err(e) => {
println!("error: {}", e.description()); println!("error: {}", e.description());
break 'outer break 'outer
@ -244,7 +246,7 @@ fn run_server(sender: Sender<DevtoolsControlMsg>,
id: PipelineId, id: PipelineId,
actor_pipelines: &HashMap<PipelineId, String>) -> String { actor_pipelines: &HashMap<PipelineId, String>) -> String {
let actors = actors.lock().unwrap(); let actors = actors.lock().unwrap();
let ref tab_actor_name = (*actor_pipelines)[id]; let ref tab_actor_name = (*actor_pipelines)[&id];
let tab_actor = actors.find::<TabActor>(tab_actor_name); let tab_actor = actors.find::<TabActor>(tab_actor_name);
let console_actor_name = tab_actor.console.clone(); let console_actor_name = tab_actor.console.clone();
return console_actor_name; return console_actor_name;

View file

@ -8,13 +8,12 @@
use rustc_serialize::{json, Encodable}; use rustc_serialize::{json, Encodable};
use rustc_serialize::json::Json; use rustc_serialize::json::Json;
use std::io::{self, Read, ReadExt, Write, ErrorKind}; use std::io::{self, Read, Write};
use std::net::TcpStream; use std::net::TcpStream;
use std::num;
pub trait JsonPacketStream { pub trait JsonPacketStream {
fn write_json_packet<'a, T: Encodable>(&mut self, obj: &T); fn write_json_packet<'a, T: Encodable>(&mut self, obj: &T);
fn read_json_packet(&mut self) -> io::Result<Json>; fn read_json_packet(&mut self) -> io::Result<Option<Json>>;
} }
impl JsonPacketStream for TcpStream { impl JsonPacketStream for TcpStream {
@ -26,25 +25,25 @@ impl JsonPacketStream for TcpStream {
self.write_all(s.as_bytes()).unwrap(); self.write_all(s.as_bytes()).unwrap();
} }
fn read_json_packet<'a>(&mut self) -> io::Result<Json> { fn read_json_packet<'a>(&mut self) -> io::Result<Option<Json>> {
// https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport // https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport
// In short, each JSON packet is [ascii length]:[JSON data of given length] // In short, each JSON packet is [ascii length]:[JSON data of given length]
let mut buffer = vec!(); let mut buffer = vec!();
loop { loop {
let mut buf = [0]; let mut buf = [0];
let byte = match try!(self.read(&mut buf)) { let byte = match try!(self.read(&mut buf)) {
0 => return Err(io::Error::new(ErrorKind::Other, "EOF", None)), 0 => return Ok(None), // EOF
1 => buf[0], 1 => buf[0],
_ => unreachable!(), _ => unreachable!(),
}; };
match byte { match byte {
b':' => { b':' => {
let packet_len_str = String::from_utf8(buffer).unwrap(); let packet_len_str = String::from_utf8(buffer).unwrap();
let packet_len = num::from_str_radix(&packet_len_str, 10).unwrap(); let packet_len = u64::from_str_radix(&packet_len_str, 10).unwrap();
let mut packet = String::new(); let mut packet = String::new();
self.take(packet_len).read_to_string(&mut packet).unwrap(); self.take(packet_len).read_to_string(&mut packet).unwrap();
println!("{}", packet); println!("{}", packet);
return Ok(Json::from_str(&packet).unwrap()) return Ok(Some(Json::from_str(&packet).unwrap()))
}, },
c => buffer.push(c), c => buffer.push(c),
} }

View file

@ -9,12 +9,10 @@
#![crate_name = "devtools_traits"] #![crate_name = "devtools_traits"]
#![crate_type = "rlib"] #![crate_type = "rlib"]
#![feature(net)]
#![allow(non_snake_case)] #![allow(non_snake_case)]
extern crate msg; extern crate msg;
extern crate "rustc-serialize" as rustc_serialize; extern crate rustc_serialize;
extern crate url; extern crate url;
extern crate util; extern crate util;
extern crate time; extern crate time;

View file

@ -61,7 +61,6 @@ git = "https://github.com/servo/rust-core-text"
[dependencies.skia] [dependencies.skia]
git = "https://github.com/servo/skia" git = "https://github.com/servo/skia"
branch = "upstream-2014-06-16"
[dependencies.script_traits] [dependencies.script_traits]
path = "../script_traits" path = "../script_traits"

View file

@ -40,7 +40,7 @@ use util::linked_list::prepend_from;
use util::geometry::{self, Au, MAX_RECT, ZERO_RECT}; use util::geometry::{self, Au, MAX_RECT, ZERO_RECT};
use util::mem::HeapSizeOf; use util::mem::HeapSizeOf;
use util::range::Range; use util::range::Range;
use util::smallvec::{SmallVec, SmallVec8}; use util::smallvec::SmallVec8;
use std::fmt; use std::fmt;
use std::slice::Iter; use std::slice::Iter;
use std::sync::Arc; use std::sync::Arc;
@ -305,8 +305,7 @@ impl StackingContext {
for kid in display_list.children.iter() { for kid in display_list.children.iter() {
positioned_children.push((*kid).clone()); positioned_children.push((*kid).clone());
} }
positioned_children.as_slice_mut() positioned_children.sort_by(|this, other| this.z_index.cmp(&other.z_index));
.sort_by(|this, other| this.z_index.cmp(&other.z_index));
// Set up our clip rect and transform. // Set up our clip rect and transform.
let old_transform = paint_subcontext.draw_target.get_transform(); let old_transform = paint_subcontext.draw_target.get_transform();

View file

@ -10,7 +10,6 @@ use azure::azure_hl::{FilterNode, FilterType, LinearTransferAttribute, LinearTra
use azure::azure_hl::{Matrix5x4, TableTransferAttribute, TableTransferInput}; use azure::azure_hl::{Matrix5x4, TableTransferAttribute, TableTransferInput};
use azure::azure_hl::{GaussianBlurAttribute, GaussianBlurInput}; use azure::azure_hl::{GaussianBlurAttribute, GaussianBlurInput};
use std::num::Float;
use style::computed_values::filter; use style::computed_values::filter;
use util::geometry::Au; use util::geometry::Au;

View file

@ -9,7 +9,7 @@ use std::slice;
use std::rc::Rc; use std::rc::Rc;
use std::cell::RefCell; use std::cell::RefCell;
use util::cache::HashCache; use util::cache::HashCache;
use util::smallvec::{SmallVec, SmallVec8}; use util::smallvec::SmallVec8;
use style::computed_values::{font_stretch, font_variant, font_weight}; use style::computed_values::{font_stretch, font_variant, font_weight};
use style::properties::style_structs::Font as FontStyle; use style::properties::style_structs::Font as FontStyle;
use std::sync::Arc; use std::sync::Arc;
@ -185,7 +185,7 @@ impl Font {
pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> {
let codepoint = match self.variant { let codepoint = match self.variant {
font_variant::T::small_caps => codepoint.to_uppercase(), font_variant::T::small_caps => codepoint.to_uppercase().next().unwrap(), //FIXME: #5938
font_variant::T::normal => codepoint, font_variant::T::normal => codepoint,
}; };
self.handle.glyph_index(codepoint) self.handle.glyph_index(codepoint)
@ -222,7 +222,8 @@ impl FontGroup {
assert!(self.fonts.len() > 0); assert!(self.fonts.len() > 0);
// TODO(Issue #177): Actually fall back through the FontGroup when a font is unsuitable. // TODO(Issue #177): Actually fall back through the FontGroup when a font is unsuitable.
TextRun::new(&mut *self.fonts.get(0).borrow_mut(), text.clone(), options) let mut font_borrow = self.fonts[0].borrow_mut();
TextRun::new(&mut *font_borrow, text.clone(), options)
} }
} }

View file

@ -191,7 +191,7 @@ impl FontCache {
let s = self.local_families.get_mut(family_name).unwrap(); let s = self.local_families.get_mut(family_name).unwrap();
if s.templates.len() == 0 { if s.templates.len() == 0 {
get_variations_for_family(&family_name, |path| { get_variations_for_family(family_name, |path| {
s.add_template(&path, None); s.add_template(&path, None);
}); });
} }

View file

@ -15,7 +15,7 @@ use platform::font_template::FontTemplateData;
use util::cache::HashCache; use util::cache::HashCache;
use util::fnv::FnvHasher; use util::fnv::FnvHasher;
use util::geometry::Au; use util::geometry::Au;
use util::smallvec::{SmallVec, SmallVec8}; use util::smallvec::SmallVec8;
use std::borrow::{self, ToOwned}; use std::borrow::{self, ToOwned};
use std::cell::RefCell; use std::cell::RefCell;
@ -45,7 +45,7 @@ fn create_scaled_font(template: &Arc<FontTemplateData>, pt_size: Au) -> ScaledFo
ScaledFont::new(BackendType::Skia, &cgfont, pt_size.to_subpx() as AzFloat) ScaledFont::new(BackendType::Skia, &cgfont, pt_size.to_subpx() as AzFloat)
} }
static SMALL_CAPS_SCALE_FACTOR: f64 = 0.8; // Matches FireFox (see gfxFont.h) static SMALL_CAPS_SCALE_FACTOR: f32 = 0.8; // Matches FireFox (see gfxFont.h)
struct LayoutFontCacheEntry { struct LayoutFontCacheEntry {
family: String, family: String,
@ -160,7 +160,7 @@ impl FontContext {
let mut fonts = SmallVec8::new(); let mut fonts = SmallVec8::new();
for family in style.font_family.iter() { for family in style.font_family.0.iter() {
// GWTODO: Check on real pages if this is faster as Vec() or HashMap(). // GWTODO: Check on real pages if this is faster as Vec() or HashMap().
let mut cache_hit = false; let mut cache_hit = false;
for cached_font_entry in self.layout_font_cache.iter() { for cached_font_entry in self.layout_font_cache.iter() {

View file

@ -6,12 +6,10 @@
#![feature(box_syntax)] #![feature(box_syntax)]
#![feature(collections)] #![feature(collections)]
#![feature(core)] #![feature(core)]
#![cfg_attr(any(target_os="linux", target_os = "android"), feature(io))]
#![feature(plugin)] #![feature(plugin)]
#![feature(rustc_private)] #![feature(rustc_private)]
#![feature(std_misc)] #![feature(std_misc)]
#![feature(unicode)] #![feature(str_char)]
#![feature(unsafe_destructor)]
#![plugin(plugins)] #![plugin(plugins)]
@ -28,8 +26,7 @@ extern crate stb_image;
extern crate png; extern crate png;
extern crate profile_traits; extern crate profile_traits;
extern crate script_traits; extern crate script_traits;
extern crate "rustc-serialize" as rustc_serialize; extern crate rustc_serialize;
extern crate unicode;
extern crate net_traits; extern crate net_traits;
#[macro_use] #[macro_use]
extern crate util; extern crate util;

View file

@ -34,7 +34,6 @@ use png::PixelsByColorType;
use std::default::Default; use std::default::Default;
use std::f32; use std::f32;
use std::mem; use std::mem;
use std::num::Float;
use std::ptr; use std::ptr;
use std::sync::Arc; use std::sync::Arc;
use style::computed_values::{border_style, filter, image_rendering, mix_blend_mode}; use style::computed_values::{border_style, filter, image_rendering, mix_blend_mode};

View file

@ -33,7 +33,6 @@ use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender, channel}; use std::sync::mpsc::{Receiver, Sender, channel};
use util::geometry::{Au, ZERO_POINT}; use util::geometry::{Au, ZERO_POINT};
use util::opts; use util::opts;
use util::smallvec::SmallVec;
use util::task::spawn_named_with_send_on_failure; use util::task::spawn_named_with_send_on_failure;
use util::task_state; use util::task_state;
use util::task::spawn_named; use util::task::spawn_named;

View file

@ -28,7 +28,6 @@ use freetype::tt_os2::TT_OS2;
use libc::c_char; use libc::c_char;
use std::mem; use std::mem;
use std::num::Float;
use std::ptr; use std::ptr;
use std::sync::Arc; use std::sync::Arc;
@ -56,7 +55,6 @@ pub struct FontHandle {
pub handle: FontContextHandle pub handle: FontContextHandle
} }
#[unsafe_destructor]
impl Drop for FontHandle { impl Drop for FontHandle {
fn drop(&mut self) { fn drop(&mut self) {
assert!(!self.face.is_null()); assert!(!self.face.is_null());

View file

@ -27,7 +27,6 @@ use core_text::font::CTFont;
use core_text::font_descriptor::{SymbolicTraitAccessors, TraitAccessors}; use core_text::font_descriptor::{SymbolicTraitAccessors, TraitAccessors};
use core_text::font_descriptor::{kCTFontDefaultOrientation}; use core_text::font_descriptor::{kCTFontDefaultOrientation};
use std::num::Float;
use std::ptr; use std::ptr;
use std::sync::Arc; use std::sync::Arc;

View file

@ -34,7 +34,7 @@ impl FontTemplateData {
} }
}, },
None => { None => {
Some(core_text::font::new_from_name(&identifier, 0.0).unwrap()) Some(core_text::font::new_from_name(identifier, 0.0).unwrap())
} }
}; };

View file

@ -6,8 +6,6 @@ use geom::point::Point2D;
use std::cmp::{Ordering, PartialOrd}; use std::cmp::{Ordering, PartialOrd};
use std::iter::repeat; use std::iter::repeat;
use std::mem; use std::mem;
use std::num::{ToPrimitive, NumCast};
use std::ops::{Add, Sub, Mul, Neg, Div, Rem, BitAnd, BitOr, BitXor, Shl, Shr, Not};
use std::u16; use std::u16;
use std::vec::Vec; use std::vec::Vec;
use util::geometry::Au; use util::geometry::Au;
@ -156,10 +154,9 @@ fn is_simple_glyph_id(id: GlyphId) -> bool {
} }
fn is_simple_advance(advance: Au) -> bool { fn is_simple_advance(advance: Au) -> bool {
match advance.to_u32() { advance >= Au(0) && {
Some(unsigned_au) => let unsigned_au = advance.0 as u32;
(unsigned_au & (GLYPH_ADVANCE_MASK >> GLYPH_ADVANCE_SHIFT)) == unsigned_au, (unsigned_au & (GLYPH_ADVANCE_MASK >> GLYPH_ADVANCE_SHIFT)) == unsigned_au
None => false
} }
} }
@ -171,7 +168,7 @@ impl GlyphEntry {
// getter methods // getter methods
#[inline(always)] #[inline(always)]
fn advance(&self) -> Au { fn advance(&self) -> Au {
NumCast::from((self.value & GLYPH_ADVANCE_MASK) >> GLYPH_ADVANCE_SHIFT).unwrap() Au(((self.value & GLYPH_ADVANCE_MASK) >> GLYPH_ADVANCE_SHIFT) as i32)
} }
fn id(&self) -> GlyphId { fn id(&self) -> GlyphId {
@ -731,7 +728,7 @@ impl<'a> GlyphStore {
// FIXME(pcwalton): This can overflow for very large font-sizes. // FIXME(pcwalton): This can overflow for very large font-sizes.
let advance = let advance =
((entry.value & GLYPH_ADVANCE_MASK) >> GLYPH_ADVANCE_SHIFT) + ((entry.value & GLYPH_ADVANCE_MASK) >> GLYPH_ADVANCE_SHIFT) +
Au::from_frac_px(space).to_u32().unwrap(); Au::from_frac_px(space).0 as u32;
entry.value = (entry.value & !GLYPH_ADVANCE_MASK) | entry.value = (entry.value & !GLYPH_ADVANCE_MASK) |
(advance << GLYPH_ADVANCE_SHIFT); (advance << GLYPH_ADVANCE_SHIFT);
} }

View file

@ -154,7 +154,6 @@ pub struct Shaper {
font_and_shaping_options: Box<FontAndShapingOptions>, font_and_shaping_options: Box<FontAndShapingOptions>,
} }
#[unsafe_destructor]
impl Drop for Shaper { impl Drop for Shaper {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe {

View file

@ -43,9 +43,6 @@ path = "../profile_traits"
[dependencies.util] [dependencies.util]
path = "../util" path = "../util"
[dependencies.cssparser]
git = "https://github.com/servo/rust-cssparser"
[dependencies.selectors] [dependencies.selectors]
git = "https://github.com/servo/rust-selectors" git = "https://github.com/servo/rust-selectors"
@ -70,4 +67,4 @@ url = "0.2.16"
bitflags = "*" bitflags = "*"
rustc-serialize = "0.3" rustc-serialize = "0.3"
libc = "*" libc = "*"
cssparser = "0.3.1"

View file

@ -31,7 +31,7 @@ pub fn start_transitions_if_applicable(new_animations_sender: &Sender<Animation>
property_animation.update(new_style, 0.0); property_animation.update(new_style, 0.0);
// Kick off the animation. // Kick off the animation.
let now = clock_ticks::precise_time_s(); let now = clock_ticks::precise_time_s() as f32;
let animation_style = new_style.get_animation(); let animation_style = new_style.get_animation();
let start_time = now + animation_style.transition_delay.0.get_mod(i).seconds(); let start_time = now + animation_style.transition_delay.0.get_mod(i).seconds();
new_animations_sender.send(Animation { new_animations_sender.send(Animation {
@ -66,7 +66,7 @@ pub fn recalc_style_for_animation(flow: &mut Flow, animation: &Animation) {
return return
} }
let now = clock_ticks::precise_time_s(); let now = clock_ticks::precise_time_s() as f32;
let mut progress = (now - animation.start_time) / animation.duration(); let mut progress = (now - animation.start_time) / animation.duration();
if progress > 1.0 { if progress > 1.0 {
progress = 1.0 progress = 1.0
@ -91,7 +91,7 @@ pub fn recalc_style_for_animation(flow: &mut Flow, animation: &Animation) {
/// Handles animation updates. /// Handles animation updates.
pub fn tick_all_animations(layout_task: &LayoutTask, rw_data: &mut LayoutTaskData) { pub fn tick_all_animations(layout_task: &LayoutTask, rw_data: &mut LayoutTaskData) {
let running_animations = mem::replace(&mut rw_data.running_animations, Vec::new()); let running_animations = mem::replace(&mut rw_data.running_animations, Vec::new());
let now = clock_ticks::precise_time_s(); let now = clock_ticks::precise_time_s() as f32;
for running_animation in running_animations.into_iter() { for running_animation in running_animations.into_iter() {
layout_task.tick_animation(&running_animation, rw_data); layout_task.tick_animation(&running_animation, rw_data);

View file

@ -1480,13 +1480,12 @@ impl FlowConstructionUtils for FlowRef {
/// ///
/// This must not be public because only the layout constructor can do this. /// This must not be public because only the layout constructor can do this.
fn add_new_child(&mut self, mut new_child: FlowRef) { fn add_new_child(&mut self, mut new_child: FlowRef) {
let base = flow::mut_base(&mut **self);
{ {
let kid_base = flow::mut_base(&mut *new_child); let kid_base = flow::mut_base(&mut *new_child);
kid_base.parallel.parent = parallel::mut_owned_flow_to_unsafe_flow(self); kid_base.parallel.parent = parallel::mut_owned_flow_to_unsafe_flow(self);
} }
let base = flow::mut_base(&mut **self);
base.children.push_back(new_child); base.children.push_back(new_child);
let _ = base.parallel.children_count.fetch_add(1, Ordering::Relaxed); let _ = base.parallel.children_count.fetch_add(1, Ordering::Relaxed);
} }

View file

@ -34,7 +34,7 @@ use style::selector_matching::{Stylist, DeclarationBlock};
use util::arc_ptr_eq; use util::arc_ptr_eq;
use util::cache::{LRUCache, SimpleHashCache}; use util::cache::{LRUCache, SimpleHashCache};
use util::opts; use util::opts;
use util::smallvec::{SmallVec, SmallVec16}; use util::smallvec::SmallVec16;
use util::vec::ForgetfulSink; use util::vec::ForgetfulSink;
pub struct ApplicableDeclarations { pub struct ApplicableDeclarations {
@ -689,7 +689,7 @@ impl<'ln> MatchMethods for LayoutNode<'ln> {
let mut damage = self.cascade_node_pseudo_element( let mut damage = self.cascade_node_pseudo_element(
layout_context, layout_context,
parent_style, parent_style,
applicable_declarations.normal.as_slice(), &applicable_declarations.normal,
&mut layout_data.shared_data.style, &mut layout_data.shared_data.style,
applicable_declarations_cache, applicable_declarations_cache,
new_animations_sender, new_animations_sender,

View file

@ -39,8 +39,6 @@ use png::{self, PixelsByColorType};
use std::cmp; use std::cmp;
use std::default::Default; use std::default::Default;
use std::iter::repeat; use std::iter::repeat;
use std::num::Float;
use std::num::ToPrimitive;
use std::sync::Arc; use std::sync::Arc;
use std::sync::mpsc::channel; use std::sync::mpsc::channel;
use style::computed_values::filter::Filter; use style::computed_values::filter::Filter;
@ -247,13 +245,13 @@ pub trait FragmentDisplayListBuilding {
fn handle_overlapping_radii(size: &Size2D<Au>, radii: &BorderRadii<Au>) -> BorderRadii<Au> { fn handle_overlapping_radii(size: &Size2D<Au>, radii: &BorderRadii<Au>) -> BorderRadii<Au> {
// No two corners' border radii may add up to more than the length of the edge // No two corners' border radii may add up to more than the length of the edge
// between them. To prevent that, all radii are scaled down uniformly. // between them. To prevent that, all radii are scaled down uniformly.
fn scale_factor(radius_a: Au, radius_b: Au, edge_length: Au) -> f64 { fn scale_factor(radius_a: Au, radius_b: Au, edge_length: Au) -> f32 {
let required = radius_a + radius_b; let required = radius_a + radius_b;
if required <= edge_length { if required <= edge_length {
1.0 1.0
} else { } else {
to_frac_px(edge_length) / to_frac_px(required) edge_length.to_frac32_px() / required.to_frac32_px()
} }
} }
@ -503,10 +501,10 @@ impl FragmentDisplayListBuilding for Fragment {
// between the starting point and the ending point. // between the starting point and the ending point.
let delta = match gradient.angle_or_corner { let delta = match gradient.angle_or_corner {
AngleOrCorner::Angle(angle) => { AngleOrCorner::Angle(angle) => {
Point2D(Au((angle.radians().sin() * Point2D(Au::from_frac32_px(angle.radians().sin() *
absolute_bounds.size.width.to_f64().unwrap() / 2.0) as i32), absolute_bounds.size.width.to_frac32_px() / 2.0),
Au((-angle.radians().cos() * Au::from_frac32_px(-angle.radians().cos() *
absolute_bounds.size.height.to_f64().unwrap() / 2.0) as i32)) absolute_bounds.size.height.to_frac32_px() / 2.0))
} }
AngleOrCorner::Corner(horizontal, vertical) => { AngleOrCorner::Corner(horizontal, vertical) => {
let x_factor = match horizontal { let x_factor = match horizontal {
@ -517,14 +515,14 @@ impl FragmentDisplayListBuilding for Fragment {
VerticalDirection::Top => -1, VerticalDirection::Top => -1,
VerticalDirection::Bottom => 1, VerticalDirection::Bottom => 1,
}; };
Point2D(Au(x_factor * absolute_bounds.size.width.to_i32().unwrap() / 2), Point2D(absolute_bounds.size.width * x_factor / 2,
Au(y_factor * absolute_bounds.size.height.to_i32().unwrap() / 2)) absolute_bounds.size.height * y_factor / 2)
} }
}; };
// This is the length of the gradient line. // This is the length of the gradient line.
let length = Au((delta.x.to_f64().unwrap() * 2.0).hypot(delta.y.to_f64().unwrap() * 2.0) let length = Au::from_frac32_px(
as i32); (delta.x.to_frac32_px() * 2.0).hypot(delta.y.to_frac32_px() * 2.0));
// Determine the position of each stop per CSS-IMAGES § 3.4. // Determine the position of each stop per CSS-IMAGES § 3.4.
// //

View file

@ -55,7 +55,6 @@ use rustc_serialize::{Encoder, Encodable};
use std::fmt; use std::fmt;
use std::iter::Zip; use std::iter::Zip;
use std::mem; use std::mem;
use std::num::FromPrimitive;
use std::raw; use std::raw;
use std::slice::IterMut; use std::slice::IterMut;
use std::sync::Arc; use std::sync::Arc;
@ -582,13 +581,13 @@ impl FlowFlags {
#[inline] #[inline]
pub fn text_align(self) -> text_align::T { pub fn text_align(self) -> text_align::T {
FromPrimitive::from_u32((self & TEXT_ALIGN).bits() >> TEXT_ALIGN_SHIFT).unwrap() text_align::T::from_u32((self & TEXT_ALIGN).bits() >> TEXT_ALIGN_SHIFT).unwrap()
} }
#[inline] #[inline]
pub fn set_text_align(&mut self, value: text_align::T) { pub fn set_text_align(&mut self, value: text_align::T) {
*self = (*self & !TEXT_ALIGN) | *self = (*self & !TEXT_ALIGN) |
FlowFlags::from_bits((value as u32) << TEXT_ALIGN_SHIFT).unwrap(); FlowFlags::from_bits(value.to_u32() << TEXT_ALIGN_SHIFT).unwrap();
} }
#[inline] #[inline]
@ -876,7 +875,6 @@ impl Encodable for BaseFlow {
} }
} }
#[unsafe_destructor]
impl Drop for BaseFlow { impl Drop for BaseFlow {
fn drop(&mut self) { fn drop(&mut self) {
if self.strong_ref_count.load(Ordering::SeqCst) != 0 && if self.strong_ref_count.load(Ordering::SeqCst) != 0 &&

View file

@ -78,7 +78,8 @@ impl DerefMut for FlowRef {
impl Drop for FlowRef { impl Drop for FlowRef {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe {
if self.object.vtable.is_null() { if self.object.vtable.is_null() ||
self.object.vtable as usize == mem::POST_DROP_USIZE {
return return
} }
if flow::base(&**self).strong_ref_count().fetch_sub(1, Ordering::Release) != 1 { if flow::base(&**self).strong_ref_count().fetch_sub(1, Ordering::Release) != 1 {
@ -102,7 +103,7 @@ impl Drop for FlowRef {
let object_align = vtable[2]; let object_align = vtable[2];
let fake_data = heap::allocate(object_size, object_align); let fake_data = heap::allocate(object_size, object_align);
ptr::copy(fake_data, flow_ref.object.data as *const u8, object_size); ptr::copy(flow_ref.object.data as *const u8, fake_data, object_size);
let fake_box = raw::TraitObject { vtable: flow_ref.object.vtable, data: fake_data as *mut () }; let fake_box = raw::TraitObject { vtable: flow_ref.object.vtable, data: fake_data as *mut () };
let fake_flow = mem::transmute::<raw::TraitObject, Box<Flow>>(fake_box); let fake_flow = mem::transmute::<raw::TraitObject, Box<Flow>>(fake_box);
@ -181,7 +182,8 @@ impl Clone for WeakFlowRef {
impl Drop for WeakFlowRef { impl Drop for WeakFlowRef {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe {
if self.object.vtable.is_null() { if self.object.vtable.is_null() ||
self.object.vtable as usize == mem::POST_DROP_USIZE {
return return
} }

View file

@ -34,7 +34,6 @@ use std::borrow::ToOwned;
use std::cmp::{max, min}; use std::cmp::{max, min};
use std::collections::LinkedList; use std::collections::LinkedList;
use std::fmt; use std::fmt;
use std::num::ToPrimitive;
use std::str::FromStr; use std::str::FromStr;
use std::sync::mpsc::Sender; use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
@ -51,7 +50,6 @@ use url::Url;
use util::geometry::{self, Au, ZERO_POINT}; use util::geometry::{self, Au, ZERO_POINT};
use util::logical_geometry::{LogicalRect, LogicalSize, LogicalMargin, WritingMode}; use util::logical_geometry::{LogicalRect, LogicalSize, LogicalMargin, WritingMode};
use util::range::*; use util::range::*;
use util::smallvec::SmallVec;
use util::str::is_whitespace; use util::str::is_whitespace;
use util; use util;
@ -453,8 +451,8 @@ impl ReplacedImageFragmentInfo {
if intrinsic_height == Au(0) { if intrinsic_height == Au(0) {
intrinsic_width intrinsic_width
} else { } else {
let ratio = intrinsic_width.to_f32().unwrap() / let ratio = intrinsic_width.to_frac32_px() /
intrinsic_height.to_f32().unwrap(); intrinsic_height.to_frac32_px();
let specified_height = ReplacedImageFragmentInfo::style_length( let specified_height = ReplacedImageFragmentInfo::style_length(
style_block_size, style_block_size,
@ -468,7 +466,7 @@ impl ReplacedImageFragmentInfo {
style_min_block_size, style_min_block_size,
style_max_block_size, style_max_block_size,
Au(0)); Au(0));
Au((specified_height.to_f32().unwrap() * ratio) as i32) Au::from_frac32_px(specified_height.to_frac32_px() * ratio)
} }
}, },
MaybeAuto::Specified(w) => w, MaybeAuto::Specified(w) => w,
@ -505,8 +503,8 @@ impl ReplacedImageFragmentInfo {
MaybeAuto::Auto => { MaybeAuto::Auto => {
let intrinsic_width = fragment_inline_size; let intrinsic_width = fragment_inline_size;
let intrinsic_height = fragment_block_size; let intrinsic_height = fragment_block_size;
let scale = intrinsic_width.to_f32().unwrap() / inline_size.to_f32().unwrap(); let scale = intrinsic_width.to_frac32_px() / inline_size.to_frac32_px();
Au((intrinsic_height.to_f32().unwrap() / scale) as i32) Au::from_frac32_px(intrinsic_height.to_frac32_px() / scale)
}, },
MaybeAuto::Specified(h) => { MaybeAuto::Specified(h) => {
h h

View file

@ -21,7 +21,7 @@ use std::sync::Arc;
use style::computed_values::content::ContentItem; use style::computed_values::content::ContentItem;
use style::computed_values::{display, list_style_type}; use style::computed_values::{display, list_style_type};
use style::properties::ComputedValues; use style::properties::ComputedValues;
use util::smallvec::{SmallVec, SmallVec8}; use util::smallvec::SmallVec8;
// Decimal styles per CSS-COUNTER-STYLES § 6.1: // Decimal styles per CSS-COUNTER-STYLES § 6.1:
static DECIMAL: [char; 10] = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ]; static DECIMAL: [char; 10] = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ];
@ -530,9 +530,7 @@ fn push_alphabetic_representation(mut value: i32, system: &[char], accumulator:
value = ((value as usize) / system.len()) as i32; value = ((value as usize) / system.len()) as i32;
} }
for i in (0..string.len()).rev() { accumulator.extend(string.iter().cloned().rev())
accumulator.push(*string.get(i))
}
} }
/// Pushes the string that represents the value rendered using the given *numeric system* onto the /// Pushes the string that represents the value rendered using the given *numeric system* onto the
@ -554,8 +552,6 @@ fn push_numeric_representation(mut value: i32, system: &[char], accumulator: &mu
} }
// Step 3. // Step 3.
for &ch in string.iter().rev() { accumulator.extend(string.iter().cloned().rev())
accumulator.push(ch)
}
} }

View file

@ -210,7 +210,10 @@ impl<'a> LayoutDamageComputation for &'a mut (Flow + 'a) {
.insert(self_base.restyle_damage.damage_for_child( .insert(self_base.restyle_damage.damage_for_child(
is_absolutely_positioned, is_absolutely_positioned,
child_is_absolutely_positioned)); child_is_absolutely_positioned));
special_damage.insert(kid.compute_layout_damage()); {
let kid: &mut Flow = kid;
special_damage.insert(kid.compute_layout_damage());
}
self_base.restyle_damage self_base.restyle_damage
.insert(flow::base(kid).restyle_damage.damage_for_parent( .insert(flow::base(kid).restyle_damage.damage_for_parent(
child_is_absolutely_positioned)); child_is_absolutely_positioned));

View file

@ -25,8 +25,6 @@ use gfx::text::text_run::TextRun;
use std::cmp::max; use std::cmp::max;
use std::fmt; use std::fmt;
use std::mem; use std::mem;
use std::num::ToPrimitive;
use std::ops::{Add, Sub, Mul, Div, Rem, Neg, Shl, Shr, Not, BitOr, BitAnd, BitXor};
use std::sync::Arc; use std::sync::Arc;
use std::u16; use std::u16;
use style::computed_values::{display, overflow_x, text_align, text_justify, text_overflow}; use style::computed_values::{display, overflow_x, text_align, text_justify, text_overflow};
@ -38,8 +36,8 @@ use util::range::{Range, RangeIndex};
use util; use util;
// From gfxFontConstants.h in Firefox // From gfxFontConstants.h in Firefox
static FONT_SUBSCRIPT_OFFSET_RATIO: f64 = 0.20; static FONT_SUBSCRIPT_OFFSET_RATIO: f32 = 0.20;
static FONT_SUPERSCRIPT_OFFSET_RATIO: f64 = 0.34; static FONT_SUPERSCRIPT_OFFSET_RATIO: f32 = 0.34;
/// `Line`s are represented as offsets into the child list, rather than /// `Line`s are represented as offsets into the child list, rather than
/// as an object that "owns" fragments. Choosing a different set of line /// as an object that "owns" fragments. Choosing a different set of line
@ -928,7 +926,7 @@ impl InlineFlow {
text_align::T::left | text_align::T::right => unreachable!() text_align::T::left | text_align::T::right => unreachable!()
} }
for fragment_index in line.range.begin()..line.range.end() { for fragment_index in line.range.each_index() {
let fragment = fragments.get_mut(fragment_index.to_usize()); let fragment = fragments.get_mut(fragment_index.to_usize());
let size = fragment.border_box.size; let size = fragment.border_box.size;
fragment.border_box = LogicalRect::new(fragment.style.writing_mode, fragment.border_box = LogicalRect::new(fragment.style.writing_mode,
@ -1017,7 +1015,7 @@ impl InlineFlow {
line_distance_from_flow_block_start: Au, line_distance_from_flow_block_start: Au,
baseline_distance_from_block_start: Au, baseline_distance_from_block_start: Au,
largest_depth_below_baseline: Au) { largest_depth_below_baseline: Au) {
for fragment_index in line.range.begin()..line.range.end() { for fragment_index in line.range.each_index() {
// If any of the inline styles say `top` or `bottom`, adjust the vertical align // If any of the inline styles say `top` or `bottom`, adjust the vertical align
// appropriately. // appropriately.
// //
@ -1295,7 +1293,7 @@ impl Flow for InlineFlow {
let (mut largest_block_size_for_top_fragments, let (mut largest_block_size_for_top_fragments,
mut largest_block_size_for_bottom_fragments) = (Au(0), Au(0)); mut largest_block_size_for_bottom_fragments) = (Au(0), Au(0));
for fragment_index in line.range.begin()..line.range.end() { for fragment_index in line.range.each_index() {
let fragment = &mut self.fragments.fragments[fragment_index.to_usize()]; let fragment = &mut self.fragments.fragments[fragment_index.to_usize()];
let InlineMetrics { let InlineMetrics {

View file

@ -73,7 +73,6 @@ use util::geometry::{Au, MAX_RECT};
use util::logical_geometry::LogicalPoint; use util::logical_geometry::LogicalPoint;
use util::mem::HeapSizeOf; use util::mem::HeapSizeOf;
use util::opts; use util::opts;
use util::smallvec::SmallVec;
use util::task::spawn_named_with_send_on_failure; use util::task::spawn_named_with_send_on_failure;
use util::task_state; use util::task_state;
use util::workqueue::WorkQueue; use util::workqueue::WorkQueue;
@ -1097,7 +1096,7 @@ impl LayoutRPC for LayoutRPCImpl {
/// Requests the node containing the point of interest. /// Requests the node containing the point of interest.
fn hit_test(&self, _: TrustedNodeAddress, point: Point2D<f32>) -> Result<HitTestResponse, ()> { fn hit_test(&self, _: TrustedNodeAddress, point: Point2D<f32>) -> Result<HitTestResponse, ()> {
let point = Point2D(Au::from_frac_px(point.x as f64), Au::from_frac_px(point.y as f64)); let point = Point2D(Au::from_frac32_px(point.x), Au::from_frac32_px(point.y));
let resp = { let resp = {
let &LayoutRPCImpl(ref rw_data) = self; let &LayoutRPCImpl(ref rw_data) = self;
let rw_data = rw_data.lock().unwrap(); let rw_data = rw_data.lock().unwrap();
@ -1124,7 +1123,7 @@ impl LayoutRPC for LayoutRPCImpl {
fn mouse_over(&self, _: TrustedNodeAddress, point: Point2D<f32>) fn mouse_over(&self, _: TrustedNodeAddress, point: Point2D<f32>)
-> Result<MouseOverResponse, ()> { -> Result<MouseOverResponse, ()> {
let mut mouse_over_list: Vec<DisplayItemMetadata> = vec!(); let mut mouse_over_list: Vec<DisplayItemMetadata> = vec!();
let point = Point2D(Au::from_frac_px(point.x as f64), Au::from_frac_px(point.y as f64)); let point = Point2D(Au::from_frac32_px(point.x), Au::from_frac32_px(point.y));
{ {
let &LayoutRPCImpl(ref rw_data) = self; let &LayoutRPCImpl(ref rw_data) = self;
let rw_data = rw_data.lock().unwrap(); let rw_data = rw_data.lock().unwrap();

View file

@ -6,13 +6,12 @@
#![feature(box_syntax)] #![feature(box_syntax)]
#![feature(collections)] #![feature(collections)]
#![feature(core)] #![feature(core)]
#![feature(io)] #![feature(filling_drop)]
#![feature(plugin)] #![feature(plugin)]
#![feature(rustc_private)] #![feature(rustc_private)]
#![feature(std_misc)] #![feature(std_misc)]
#![feature(str_char)]
#![feature(thread_local)] #![feature(thread_local)]
#![feature(unicode)]
#![feature(unsafe_destructor)]
#![feature(unsafe_no_drop_flag)] #![feature(unsafe_no_drop_flag)]
#![deny(unsafe_code)] #![deny(unsafe_code)]
@ -29,7 +28,7 @@ extern crate bitflags;
#[macro_use] #[macro_use]
#[no_link] #[no_link]
extern crate "plugins" as servo_plugins; extern crate plugins as servo_plugins;
extern crate net_traits; extern crate net_traits;
#[macro_use] #[macro_use]
extern crate profile_traits; extern crate profile_traits;
@ -37,7 +36,7 @@ extern crate profile_traits;
#[macro_use] #[macro_use]
extern crate util; extern crate util;
extern crate "rustc-serialize" as rustc_serialize; extern crate rustc_serialize;
extern crate alloc; extern crate alloc;
extern crate azure; extern crate azure;
extern crate canvas; extern crate canvas;

View file

@ -434,8 +434,8 @@ impl ToGfxMatrix for ComputedMatrix {
self.m12 as f32, self.m12 as f32,
self.m21 as f32, self.m21 as f32,
self.m22 as f32, self.m22 as f32,
self.m31.to_au(containing_size.width).to_subpx() as f32, self.m31.to_au(containing_size.width).to_frac32_px(),
self.m32.to_au(containing_size.height).to_subpx() as f32) self.m32.to_au(containing_size.height).to_frac32_px())
} }
} }
@ -446,7 +446,7 @@ trait ToAu {
impl ToAu for LengthAndPercentage { impl ToAu for LengthAndPercentage {
#[inline] #[inline]
fn to_au(&self, containing_size: Au) -> Au { fn to_au(&self, containing_size: Au) -> Au {
self.length + Au::from_frac_px(self.percentage * containing_size.to_subpx()) self.length + Au::from_frac32_px(self.percentage * containing_size.to_frac32_px())
} }
} }

View file

@ -82,7 +82,10 @@ pub fn traverse_flow_tree_preorder(root: &mut FlowRef,
if opts::get().bubble_inline_sizes_separately { if opts::get().bubble_inline_sizes_separately {
let bubble_inline_sizes = BubbleISizes { layout_context: &layout_context }; let bubble_inline_sizes = BubbleISizes { layout_context: &layout_context };
root.traverse_postorder(&bubble_inline_sizes); {
let root: &mut Flow = root;
root.traverse_postorder(&bubble_inline_sizes);
}
} }
let assign_inline_sizes = AssignISizes { layout_context: &layout_context }; let assign_inline_sizes = AssignISizes { layout_context: &layout_context };

View file

@ -430,8 +430,8 @@ impl Flow for TableFlow {
// if there are any, or among all the columns if all are specified. // if there are any, or among all the columns if all are specified.
self.column_computed_inline_sizes.clear(); self.column_computed_inline_sizes.clear();
if num_unspecified_inline_sizes == 0 { if num_unspecified_inline_sizes == 0 {
let ratio = content_inline_size.to_subpx() / let ratio = content_inline_size.to_frac32_px() /
total_column_inline_size.to_subpx(); total_column_inline_size.to_frac32_px();
for column_inline_size in self.column_intrinsic_inline_sizes.iter() { for column_inline_size in self.column_intrinsic_inline_sizes.iter() {
self.column_computed_inline_sizes.push(ColumnComputedInlineSize { self.column_computed_inline_sizes.push(ColumnComputedInlineSize {
size: column_inline_size.minimum_length.scale_by(ratio), size: column_inline_size.minimum_length.scale_by(ratio),

View file

@ -590,7 +590,7 @@ impl SelectedAutoLayoutCandidateGuess {
/// Computes the weight needed to linearly interpolate `middle` between two guesses `low` and /// Computes the weight needed to linearly interpolate `middle` between two guesses `low` and
/// `high` as specified by INTRINSIC § 4.3. /// `high` as specified by INTRINSIC § 4.3.
fn weight(low: Au, middle: Au, high: Au) -> CSSFloat { fn weight(low: Au, middle: Au, high: Au) -> CSSFloat {
(middle - low).to_subpx() / (high - low).to_subpx() (middle - low).to_frac32_px() / (high - low).to_frac32_px()
} }
/// Linearly interpolates between two guesses, as specified by INTRINSIC § 4.3. /// Linearly interpolates between two guesses, as specified by INTRINSIC § 4.3.
@ -653,9 +653,9 @@ impl ExcessInlineSizeDistributionInfo {
// do? // do?
if !column_intrinsic_inline_size.constrained && if !column_intrinsic_inline_size.constrained &&
column_intrinsic_inline_size.percentage == 0.0 { column_intrinsic_inline_size.percentage == 0.0 {
column_intrinsic_inline_size.preferred.to_subpx() / column_intrinsic_inline_size.preferred.to_frac32_px() /
self.preferred_inline_size_of_nonconstrained_columns_with_no_percentage self.preferred_inline_size_of_nonconstrained_columns_with_no_percentage
.to_subpx() .to_frac32_px()
} else { } else {
0.0 0.0
} }
@ -663,8 +663,8 @@ impl ExcessInlineSizeDistributionInfo {
1.0 / (self.count_of_nonconstrained_columns_with_no_percentage as CSSFloat) 1.0 / (self.count_of_nonconstrained_columns_with_no_percentage as CSSFloat)
} else if self.preferred_inline_size_of_constrained_columns_with_no_percentage > } else if self.preferred_inline_size_of_constrained_columns_with_no_percentage >
Au(0) { Au(0) {
column_intrinsic_inline_size.preferred.to_subpx() / column_intrinsic_inline_size.preferred.to_frac32_px() /
self.preferred_inline_size_of_constrained_columns_with_no_percentage.to_subpx() self.preferred_inline_size_of_constrained_columns_with_no_percentage.to_frac32_px()
} else if self.total_percentage > 0.0 { } else if self.total_percentage > 0.0 {
column_intrinsic_inline_size.percentage / self.total_percentage column_intrinsic_inline_size.percentage / self.total_percentage
} else { } else {
@ -684,7 +684,7 @@ impl ExcessInlineSizeDistributionInfo {
/// An intermediate column size assignment. /// An intermediate column size assignment.
struct IntermediateColumnInlineSize { struct IntermediateColumnInlineSize {
size: Au, size: Au,
percentage: f64, percentage: f32,
} }
fn initial_computed_inline_size(block: &mut BlockFlow, fn initial_computed_inline_size(block: &mut BlockFlow,

View file

@ -27,7 +27,7 @@ use util::geometry::Au;
use util::linked_list::split_off_head; use util::linked_list::split_off_head;
use util::logical_geometry::{LogicalSize, WritingMode}; use util::logical_geometry::{LogicalSize, WritingMode};
use util::range::{Range, RangeIndex}; use util::range::{Range, RangeIndex};
use util::smallvec::{SmallVec, SmallVec1}; use util::smallvec::SmallVec1;
/// A stack-allocated object for scanning an inline flow into `TextRun`-containing `TextFragment`s. /// A stack-allocated object for scanning an inline flow into `TextRun`-containing `TextFragment`s.
pub struct TextRunScanner { pub struct TextRunScanner {
@ -185,7 +185,7 @@ impl TextRunScanner {
}; };
// FIXME(https://github.com/rust-lang/rust/issues/23338) // FIXME(https://github.com/rust-lang/rust/issues/23338)
let mut font = fontgroup.fonts.get(0).borrow_mut(); let mut font = fontgroup.fonts[0].borrow_mut();
Arc::new(box TextRun::new(&mut *font, run_text, &options)) Arc::new(box TextRun::new(&mut *font, run_text, &options))
}; };
@ -193,7 +193,7 @@ impl TextRunScanner {
debug!("TextRunScanner: pushing {} fragment(s)", self.clump.len()); debug!("TextRunScanner: pushing {} fragment(s)", self.clump.len());
for (logical_offset, old_fragment) in for (logical_offset, old_fragment) in
mem::replace(&mut self.clump, LinkedList::new()).into_iter().enumerate() { mem::replace(&mut self.clump, LinkedList::new()).into_iter().enumerate() {
let mut range = *new_ranges.get(logical_offset); let mut range = new_ranges[logical_offset];
if range.is_empty() { if range.is_empty() {
debug!("Elided an `SpecificFragmentInfo::UnscannedText` because it was \ debug!("Elided an `SpecificFragmentInfo::UnscannedText` because it was \
zero-length after compression"); zero-length after compression");
@ -238,14 +238,14 @@ impl TextRunScanner {
let length = string.len(); let length = string.len();
let original = mem::replace(string, String::with_capacity(length)); let original = mem::replace(string, String::with_capacity(length));
for character in original.chars() { for character in original.chars() {
string.push(character.to_uppercase()) string.extend(character.to_uppercase())
} }
} }
text_transform::T::lowercase => { text_transform::T::lowercase => {
let length = string.len(); let length = string.len();
let original = mem::replace(string, String::with_capacity(length)); let original = mem::replace(string, String::with_capacity(length));
for character in original.chars() { for character in original.chars() {
string.push(character.to_lowercase()) string.extend(character.to_lowercase())
} }
} }
text_transform::T::capitalize => { text_transform::T::capitalize => {
@ -258,7 +258,7 @@ impl TextRunScanner {
// //
// http://dev.w3.org/csswg/css-text/#typographic-letter-unit // http://dev.w3.org/csswg/css-text/#typographic-letter-unit
if capitalize_next_letter && character.is_alphabetic() { if capitalize_next_letter && character.is_alphabetic() {
string.push(character.to_uppercase()); string.extend(character.to_uppercase());
capitalize_next_letter = false; capitalize_next_letter = false;
continue continue
} }
@ -308,7 +308,7 @@ pub fn font_metrics_for_style(font_context: &mut FontContext, font_style: Arc<Fo
-> FontMetrics { -> FontMetrics {
let fontgroup = font_context.get_layout_font_group_for_style(font_style); let fontgroup = font_context.get_layout_font_group_for_style(font_style);
// FIXME(https://github.com/rust-lang/rust/issues/23338) // FIXME(https://github.com/rust-lang/rust/issues/23338)
let font = fontgroup.fonts.get(0).borrow(); let font = fontgroup.fonts[0].borrow();
font.metrics.clone() font.metrics.clone()
} }

View file

@ -71,11 +71,11 @@ use style::computed_values::content::ContentItem;
use style::computed_values::{content, display, white_space}; use style::computed_values::{content, display, white_space};
use selectors::matching::DeclarationBlock; use selectors::matching::DeclarationBlock;
use selectors::parser::{NamespaceConstraint, AttrSelector}; use selectors::parser::{NamespaceConstraint, AttrSelector};
use selectors::smallvec::VecLike;
use style::legacy::{IntegerAttribute, LengthAttribute}; use style::legacy::{IntegerAttribute, LengthAttribute};
use style::legacy::{UnsignedIntegerAttribute}; use style::legacy::{UnsignedIntegerAttribute};
use style::node::{TElement, TElementAttributes, TNode}; use style::node::{TElement, TElementAttributes, TNode};
use style::properties::{PropertyDeclaration, PropertyDeclarationBlock}; use style::properties::{PropertyDeclaration, PropertyDeclarationBlock};
use util::smallvec::VecLike;
use url::Url; use url::Url;
/// Allows some convenience methods on generic layout nodes. /// Allows some convenience methods on generic layout nodes.

View file

@ -22,7 +22,7 @@ git = "https://github.com/servo/rust-png"
[dependencies] [dependencies]
url = "0.2.16" url = "0.2.16"
time = "0.1.17" time = "0.1.17"
openssl="0.5.1" openssl="0.6.1"
rustc-serialize = "0.3" rustc-serialize = "0.3"
cookie="*" cookie="*"
regex = "0.1.14" regex = "0.1.14"

View file

@ -14,7 +14,6 @@ use hyper::http::RawStatus;
use hyper::mime::{Mime, TopLevel, SubLevel}; use hyper::mime::{Mime, TopLevel, SubLevel};
use util::resource_files::resources_dir_path; use util::resource_files::resources_dir_path;
use std::borrow::IntoCow;
use std::fs::PathExt; use std::fs::PathExt;
use std::sync::Arc; use std::sync::Arc;
@ -26,7 +25,7 @@ pub fn factory(mut load_data: LoadData, start_chan: LoadConsumer, classifier: Ar
content_type: Some(ContentType(Mime(TopLevel::Text, SubLevel::Html, vec![]))), content_type: Some(ContentType(Mime(TopLevel::Text, SubLevel::Html, vec![]))),
charset: Some("utf-8".to_string()), charset: Some("utf-8".to_string()),
headers: None, headers: None,
status: Some(RawStatus(200, "OK".into_cow())), status: Some(RawStatus(200, "OK".into())),
}); });
chan.send(Done(Ok(()))).unwrap(); chan.send(Done(Ok(()))).unwrap();
return return

View file

@ -9,12 +9,10 @@ use net_traits::CookieSource;
use pub_domains::PUB_DOMAINS; use pub_domains::PUB_DOMAINS;
use cookie_rs; use cookie_rs;
use time::{Tm, now, at, Timespec}; use time::{Tm, now, at, Duration};
use url::Url; use url::Url;
use std::borrow::ToOwned; use std::borrow::ToOwned;
use std::i64;
use std::net::{Ipv4Addr, Ipv6Addr}; use std::net::{Ipv4Addr, Ipv6Addr};
use std::time::Duration;
use std::str::FromStr; use std::str::FromStr;
/// A stored cookie that wraps the definition in cookie-rs. This is used to implement /// A stored cookie that wraps the definition in cookie-rs. This is used to implement
@ -27,7 +25,7 @@ pub struct Cookie {
pub persistent: bool, pub persistent: bool,
pub creation_time: Tm, pub creation_time: Tm,
pub last_access: Tm, pub last_access: Tm,
pub expiry_time: Tm, pub expiry_time: Option<Tm>,
} }
impl Cookie { impl Cookie {
@ -36,9 +34,11 @@ impl Cookie {
-> Option<Cookie> { -> Option<Cookie> {
// Step 3 // Step 3
let (persistent, expiry_time) = match (&cookie.max_age, &cookie.expires) { let (persistent, expiry_time) = match (&cookie.max_age, &cookie.expires) {
(&Some(max_age), _) => (true, at(now().to_timespec() + Duration::seconds(max_age as i64))), (&Some(max_age), _) => {
(_, &Some(expires)) => (true, expires), (true, Some(at(now().to_timespec() + Duration::seconds(max_age as i64))))
_ => (false, at(Timespec::new(i64::MAX, 0))) }
(_, &Some(expires)) => (true, Some(expires)),
_ => (false, None)
}; };
let url_host = request.host().map(|host| host.serialize()).unwrap_or("".to_owned()); let url_host = request.host().map(|host| host.serialize()).unwrap_or("".to_owned());
@ -68,7 +68,7 @@ impl Cookie {
// Step 7 // Step 7
let mut path = cookie.path.unwrap_or("".to_owned()); let mut path = cookie.path.unwrap_or("".to_owned());
if path.is_empty() || path.char_at(0) != '/' { if path.is_empty() || path.as_bytes()[0] != b'/' {
let url_path = request.serialize_path(); let url_path = request.serialize_path();
let url_path = url_path.as_ref().map(|path| &**path); let url_path = url_path.as_ref().map(|path| &**path);
path = Cookie::default_path(url_path.unwrap_or("")).to_owned(); path = Cookie::default_path(url_path.unwrap_or("")).to_owned();
@ -117,7 +117,7 @@ impl Cookie {
pub fn path_match(request_path: &str, cookie_path: &str) -> bool { pub fn path_match(request_path: &str, cookie_path: &str) -> bool {
request_path == cookie_path || request_path == cookie_path ||
( request_path.starts_with(cookie_path) && ( request_path.starts_with(cookie_path) &&
( request_path.ends_with("/") || request_path.char_at(cookie_path.len() - 1) == '/' ) ( request_path.ends_with("/") || request_path.as_bytes()[cookie_path.len() - 1] == b'/' )
) )
} }
@ -127,7 +127,7 @@ impl Cookie {
return true; return true;
} }
if string.ends_with(domain_string) if string.ends_with(domain_string)
&& string.char_at(string.len()-domain_string.len()-1) == '.' && string.as_bytes()[string.len()-domain_string.len()-1] == b'.'
&& Ipv4Addr::from_str(string).is_err() && Ipv4Addr::from_str(string).is_err()
&& Ipv6Addr::from_str(string).is_err() { && Ipv6Addr::from_str(string).is_err() {
return true; return true;

View file

@ -11,7 +11,8 @@ use rustc_serialize::base64::FromBase64;
use hyper::mime::Mime; use hyper::mime::Mime;
use std::sync::Arc; use std::sync::Arc;
use url::{percent_decode, SchemeData}; use url::percent_encoding::percent_decode;
use url::SchemeData;
pub fn factory(load_data: LoadData, senders: LoadConsumer, _classifier: Arc<MIMEClassifier>) { pub fn factory(load_data: LoadData, senders: LoadConsumer, _classifier: Arc<MIMEClassifier>) {
// NB: we don't spawn a new task. // NB: we don't spawn a new task.
@ -39,7 +40,7 @@ pub fn load(load_data: LoadData, start_chan: LoadConsumer) {
}, },
None => () None => ()
} }
let parts: Vec<&str> = scheme_data.splitn(1, ',').collect(); let parts: Vec<&str> = scheme_data.splitn(2, ',').collect();
if parts.len() != 2 { if parts.len() != 2 {
start_sending(start_chan, metadata).send(Done(Err("invalid data uri".to_string()))).unwrap(); start_sending(start_chan, metadata).send(Done(Err("invalid data uri".to_string()))).unwrap();
return; return;

View file

@ -101,7 +101,6 @@ pub trait CORSCache {
/// A simple, vector-based CORS Cache /// A simple, vector-based CORS Cache
#[derive(Clone)] #[derive(Clone)]
#[unstable = "This might later be replaced with a HashMap-like entity, though that requires a separate Origin struct"]
pub struct BasicCORSCache(Vec<CORSCacheEntry>); pub struct BasicCORSCache(Vec<CORSCacheEntry>);
impl BasicCORSCache { impl BasicCORSCache {

View file

@ -28,7 +28,6 @@ pub enum TerminationReason {
/// The response body can still be pushed to after fetch /// The response body can still be pushed to after fetch
/// This provides a way to store unfinished response bodies /// This provides a way to store unfinished response bodies
#[unstable = "I haven't yet decided exactly how the interface for this will be"]
#[derive(Clone)] #[derive(Clone)]
pub enum ResponseBody { pub enum ResponseBody {
Empty, // XXXManishearth is this necessary, or is Done(vec![]) enough? Empty, // XXXManishearth is this necessary, or is Done(vec![]) enough?
@ -36,14 +35,12 @@ pub enum ResponseBody {
Done(Vec<u8>), Done(Vec<u8>),
} }
#[unstable = "I haven't yet decided exactly how the interface for this will be"]
pub enum ResponseMsg { pub enum ResponseMsg {
Chunk(Vec<u8>), Chunk(Vec<u8>),
Finished, Finished,
Errored Errored
} }
#[unstable = "I haven't yet decided exactly how the interface for this will be"]
pub struct ResponseLoader { pub struct ResponseLoader {
response: Response, response: Response,
chan: Receiver<ResponseMsg> chan: Receiver<ResponseMsg>

View file

@ -8,6 +8,7 @@ use mime_classifier::MIMEClassifier;
use resource_task::{start_sending, start_sending_sniffed, ProgressSender}; use resource_task::{start_sending, start_sending_sniffed, ProgressSender};
use std::borrow::ToOwned; use std::borrow::ToOwned;
use std::error::Error;
use std::fs::File; use std::fs::File;
use std::io::Read; use std::io::Read;
use std::path::PathBuf; use std::path::PathBuf;

View file

@ -19,21 +19,21 @@ use hyper::mime::{Mime, TopLevel, SubLevel};
use hyper::net::HttpConnector; use hyper::net::HttpConnector;
use hyper::status::{StatusCode, StatusClass}; use hyper::status::{StatusCode, StatusClass};
use std::error::Error; use std::error::Error;
use openssl::ssl::{SslContext, SslVerifyMode}; use openssl::ssl::{SslContext, SSL_VERIFY_PEER};
use std::io::{self, Read, Write}; use std::io::{self, Read, Write};
use std::sync::Arc; use std::sync::Arc;
use std::sync::mpsc::{Sender, channel}; use std::sync::mpsc::{Sender, channel};
use std::thunk::Invoke;
use util::task::spawn_named; use util::task::spawn_named;
use util::resource_files::resources_dir_path; use util::resource_files::resources_dir_path;
use util::opts; use util::opts;
use url::{Url, UrlParser}; use url::{Url, UrlParser};
use std::borrow::ToOwned; use std::borrow::ToOwned;
use std::boxed::FnBox;
pub fn factory(cookies_chan: Sender<ControlMsg>) pub fn factory(cookies_chan: Sender<ControlMsg>)
-> Box<Invoke<(LoadData, LoadConsumer, Arc<MIMEClassifier>)> + Send> { -> Box<FnBox(LoadData, LoadConsumer, Arc<MIMEClassifier>) + Send> {
box move |(load_data, senders, classifier)| { box move |load_data, senders, classifier| {
spawn_named("http_loader".to_owned(), move || load(load_data, senders, classifier, cookies_chan)) spawn_named("http_loader".to_owned(), move || load(load_data, senders, classifier, cookies_chan))
} }
} }
@ -114,20 +114,20 @@ fn load(mut load_data: LoadData, start_chan: LoadConsumer, classifier: Arc<MIMEC
info!("requesting {}", url.serialize()); info!("requesting {}", url.serialize());
fn verifier(ssl: &mut SslContext) { fn verifier(ssl: &mut SslContext) {
ssl.set_verify(SslVerifyMode::SslVerifyPeer, None); ssl.set_verify(SSL_VERIFY_PEER, None);
let mut certs = resources_dir_path(); let mut certs = resources_dir_path();
certs.push("certs"); certs.push("certs");
ssl.set_CA_file(&certs); ssl.set_CA_file(&certs).unwrap();
}; };
let ssl_err_string = "[UnknownError { library: \"SSL routines\", \ let ssl_err_string = "Some(OpenSslErrors([UnknownError { library: \"SSL routines\", \
function: \"SSL3_GET_SERVER_CERTIFICATE\", \ function: \"SSL3_GET_SERVER_CERTIFICATE\", \
reason: \"certificate verify failed\" }]"; reason: \"certificate verify failed\" }]))";
let mut connector = if opts::get().nossl { let mut connector = if opts::get().nossl {
HttpConnector(None) HttpConnector(None)
} else { } else {
HttpConnector(Some(box verifier as Box<FnMut(&mut SslContext)>)) HttpConnector(Some(box verifier as Box<FnMut(&mut SslContext) + Send>))
}; };
let mut req = match Request::with_connector(load_data.method.clone(), url.clone(), &mut connector) { let mut req = match Request::with_connector(load_data.method.clone(), url.clone(), &mut connector) {
@ -135,7 +135,8 @@ reason: \"certificate verify failed\" }]";
Err(HttpError::HttpIoError(ref io_error)) if ( Err(HttpError::HttpIoError(ref io_error)) if (
io_error.kind() == io::ErrorKind::Other && io_error.kind() == io::ErrorKind::Other &&
io_error.description() == "Error in OpenSSL" && io_error.description() == "Error in OpenSSL" &&
io_error.detail() == Some(ssl_err_string.to_owned()) // FIXME: This incredibly hacky. Make it more robust, and at least test it.
format!("{:?}", io_error.cause()) == ssl_err_string
) => { ) => {
let mut image = resources_dir_path(); let mut image = resources_dir_path();
image.push("badcert.html"); image.push("badcert.html");

View file

@ -6,9 +6,6 @@
#![feature(box_syntax)] #![feature(box_syntax)]
#![feature(collections)] #![feature(collections)]
#![feature(core)] #![feature(core)]
#![feature(io)]
#![cfg_attr(test, feature(net))]
#![feature(path)]
#![feature(path_ext)] #![feature(path_ext)]
#![feature(plugin)] #![feature(plugin)]
#![feature(rustc_private)] #![feature(rustc_private)]
@ -18,7 +15,7 @@
#![plugin(regex_macros)] #![plugin(regex_macros)]
extern crate net_traits; extern crate net_traits;
extern crate "cookie" as cookie_rs; extern crate cookie as cookie_rs;
extern crate collections; extern crate collections;
extern crate flate2; extern crate flate2;
extern crate geom; extern crate geom;
@ -27,7 +24,7 @@ extern crate png;
#[macro_use] #[macro_use]
extern crate log; extern crate log;
extern crate openssl; extern crate openssl;
extern crate "rustc-serialize" as rustc_serialize; extern crate rustc_serialize;
extern crate util; extern crate util;
extern crate time; extern crate time;
extern crate url; extern crate url;

View file

@ -22,7 +22,7 @@ use hyper::header::{ContentType, Header, SetCookie, UserAgent};
use hyper::mime::{Mime, TopLevel, SubLevel}; use hyper::mime::{Mime, TopLevel, SubLevel};
use std::borrow::ToOwned; use std::borrow::ToOwned;
use std::boxed; use std::boxed::{self, FnBox};
use std::collections::HashMap; use std::collections::HashMap;
use std::env; use std::env;
use std::fs::File; use std::fs::File;
@ -30,7 +30,6 @@ use std::io::{BufReader, Read};
use std::str::FromStr; use std::str::FromStr;
use std::sync::Arc; use std::sync::Arc;
use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::mpsc::{channel, Receiver, Sender};
use std::thunk::Invoke;
static mut HOST_TABLE: Option<*mut HashMap<String, String>> = None; static mut HOST_TABLE: Option<*mut HashMap<String, String>> = None;
@ -48,7 +47,7 @@ pub fn global_init() {
let mut lines = String::new(); let mut lines = String::new();
match file.read_to_string(&mut lines) { match file.read_to_string(&mut lines) {
Ok(()) => (), Ok(_) => (),
Err(_) => return, Err(_) => return,
}; };
@ -239,8 +238,8 @@ impl ResourceManager {
self.user_agent.as_ref().map(|ua| load_data.headers.set(UserAgent(ua.clone()))); self.user_agent.as_ref().map(|ua| load_data.headers.set(UserAgent(ua.clone())));
fn from_factory(factory: fn(LoadData, LoadConsumer, Arc<MIMEClassifier>)) fn from_factory(factory: fn(LoadData, LoadConsumer, Arc<MIMEClassifier>))
-> Box<Invoke<(LoadData, LoadConsumer, Arc<MIMEClassifier>)> + Send> { -> Box<FnBox(LoadData, LoadConsumer, Arc<MIMEClassifier>) + Send> {
box move |(load_data, senders, classifier)| { box move |load_data, senders, classifier| {
factory(load_data, senders, classifier) factory(load_data, senders, classifier)
} }
} }
@ -259,6 +258,6 @@ impl ResourceManager {
}; };
debug!("resource_task: loading url: {}", load_data.url.serialize()); debug!("resource_task: loading url: {}", load_data.url.serialize());
loader.invoke((load_data, consumer, self.mime_classifier.clone())); loader.call_box((load_data, consumer, self.mime_classifier.clone()));
} }
} }

View file

@ -4,7 +4,6 @@
use png; use png;
use stb_image::image as stb_image2; use stb_image::image as stb_image2;
use std::iter::range_step;
use util::vec::byte_swap; use util::vec::byte_swap;
// FIXME: Images must not be copied every frame. Instead we should atomically // FIXME: Images must not be copied every frame. Instead we should atomically
@ -14,7 +13,7 @@ pub type Image = png::Image;
// TODO(pcwalton): Speed up with SIMD, or better yet, find some way to not do this. // TODO(pcwalton): Speed up with SIMD, or better yet, find some way to not do this.
fn byte_swap_and_premultiply(data: &mut [u8]) { fn byte_swap_and_premultiply(data: &mut [u8]) {
let length = data.len(); let length = data.len();
for i in range_step(0, length, 4) { for i in (0..length).step_by(4) {
let r = data[i + 2]; let r = data[i + 2];
let g = data[i + 1]; let g = data[i + 1];
let b = data[i + 0]; let b = data[i + 0];

View file

@ -4,8 +4,9 @@
#![feature(box_syntax)] #![feature(box_syntax)]
#![feature(collections)] #![feature(collections)]
#![feature(core)]
#![feature(rustc_private)] #![feature(rustc_private)]
#![feature(slice_patterns)]
#![feature(step_by)]
extern crate geom; extern crate geom;
extern crate hyper; extern crate hyper;
@ -22,7 +23,6 @@ use hyper::method::Method;
use hyper::mime::{Mime, Attr}; use hyper::mime::{Mime, Attr};
use url::Url; use url::Url;
use std::borrow::IntoCow;
use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::mpsc::{channel, Receiver, Sender};
pub mod image_cache_task; pub mod image_cache_task;
@ -169,7 +169,7 @@ impl Metadata {
charset: None, charset: None,
headers: None, headers: None,
// https://fetch.spec.whatwg.org/#concept-response-status-message // https://fetch.spec.whatwg.org/#concept-response-status-message
status: Some(RawStatus(200, "OK".into_cow())), status: Some(RawStatus(200, "OK".into())),
} }
} }

View file

@ -11,17 +11,17 @@ use syntax::parse::token;
pub fn expand_lower<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) pub fn expand_lower<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult + 'cx> { -> Box<base::MacResult + 'cx> {
expand_cased(cx, sp, tts, |c| { c.to_lowercase() }) expand_cased(cx, sp, tts, |s| { s.to_lowercase() })
} }
pub fn expand_upper<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) pub fn expand_upper<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult + 'cx> { -> Box<base::MacResult + 'cx> {
expand_cased(cx, sp, tts, |c| { c.to_uppercase() }) expand_cased(cx, sp, tts, |s| { s.to_uppercase() })
} }
fn expand_cased<'cx, T>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree], transform: T) fn expand_cased<'cx, T>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree], transform: T)
-> Box<base::MacResult + 'cx> -> Box<base::MacResult + 'cx>
where T: Fn(char) -> char where T: Fn(&str) -> String
{ {
let es = match base::get_exprs_from_tts(cx, sp, tts) { let es = match base::get_exprs_from_tts(cx, sp, tts) {
Some(e) => e, Some(e) => e,
@ -47,8 +47,7 @@ fn expand_cased<'cx, T>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree],
}; };
match (res, it.count()) { match (res, it.count()) {
(Some((s, span)), 0) => { (Some((s, span)), 0) => {
let new_s = s.chars().map(transform).collect::<String>(); base::MacEager::expr(cx.expr_str(span, token::intern_and_get_ident(&transform(&s))))
base::MacEager::expr(cx.expr_str(span, token::intern_and_get_ident(&new_s)))
} }
(_, rest) => { (_, rest) => {
if rest > 0 { if rest > 0 {

View file

@ -47,15 +47,16 @@ pub fn expand_jstraceable(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item:
], ],
associated_types: vec![], associated_types: vec![],
}; };
trait_def.expand(cx, mitem, item, |a| push(a)) trait_def.expand(cx, mitem, item, push)
} }
// Mostly copied from syntax::ext::deriving::hash // Mostly copied from syntax::ext::deriving::hash
/// Defines how the implementation for `trace()` is to be generated /// Defines how the implementation for `trace()` is to be generated
fn jstraceable_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> { fn jstraceable_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let state_expr = match substr.nonself_args { let state_expr = if substr.nonself_args.len() == 1 {
[ref state_expr] => state_expr, &substr.nonself_args[0]
_ => cx.span_bug(trait_span, "incorrect number of arguments in `jstraceable`") } else {
cx.span_bug(trait_span, "incorrect number of arguments in `jstraceable`")
}; };
let trace_ident = substr.method_ident; let trace_ident = substr.method_ident;
let call_trace = |span, thing_expr| { let call_trace = |span, thing_expr| {

View file

@ -12,7 +12,7 @@
//! - `#[dom_struct]` : Implies `#[privatize]`,`#[jstraceable]`, and `#[must_root]`. //! - `#[dom_struct]` : Implies `#[privatize]`,`#[jstraceable]`, and `#[must_root]`.
//! Use this for structs that correspond to a DOM type //! Use this for structs that correspond to a DOM type
#![feature(plugin_registrar, quote, plugin, box_syntax, rustc_private, unicode)] #![feature(plugin_registrar, quote, plugin, box_syntax, rustc_private, collections)]
#[macro_use] #[macro_use]
extern crate syntax; extern crate syntax;

View file

@ -33,7 +33,7 @@ fn lint_unrooted_ty(cx: &Context, ty: &ast::Ty, warning: &str) {
ast::TyVec(ref t) | ast::TyFixedLengthVec(ref t, _) | ast::TyVec(ref t) | ast::TyFixedLengthVec(ref t, _) |
ast::TyPtr(ast::MutTy { ty: ref t, ..}) | ast::TyRptr(_, ast::MutTy { ty: ref t, ..}) => lint_unrooted_ty(cx, &**t, warning), ast::TyPtr(ast::MutTy { ty: ref t, ..}) | ast::TyRptr(_, ast::MutTy { ty: ref t, ..}) => lint_unrooted_ty(cx, &**t, warning),
ast::TyPath(..) => { ast::TyPath(..) => {
match cx.tcx.def_map.borrow()[ty.id] { match cx.tcx.def_map.borrow()[&ty.id] {
def::PathResolution{ base_def: def::DefTy(def_id, _), .. } => { def::PathResolution{ base_def: def::DefTy(def_id, _), .. } => {
if ty::has_attr(cx.tcx, def_id, "must_root") { if ty::has_attr(cx.tcx, def_id, "must_root") {
cx.span_lint(UNROOTED_MUST_ROOT, ty.span, warning); cx.span_lint(UNROOTED_MUST_ROOT, ty.span, warning);
@ -78,11 +78,11 @@ impl LintPass for UnrootedPass {
fn check_fn(&mut self, cx: &Context, kind: visit::FnKind, decl: &ast::FnDecl, fn check_fn(&mut self, cx: &Context, kind: visit::FnKind, decl: &ast::FnDecl,
block: &ast::Block, _span: codemap::Span, id: ast::NodeId) { block: &ast::Block, _span: codemap::Span, id: ast::NodeId) {
match kind { match kind {
visit::FkItemFn(i, _, _, _) | visit::FkItemFn(i, _, _, _, _) |
visit::FkMethod(i, _, _) if i.as_str() == "new" || i.as_str() == "new_inherited" => { visit::FkMethod(i, _, _) if i.as_str() == "new" || i.as_str() == "new_inherited" => {
return; return;
}, },
visit::FkItemFn(_, _, style, _) => match style { visit::FkItemFn(_, _, style, _, _) => match style {
ast::Unsafety::Unsafe => return, ast::Unsafety::Unsafe => return,
_ => () _ => ()
}, },

View file

@ -69,15 +69,9 @@ pub fn match_lang_ty(cx: &Context, ty: &Ty, value: &str) -> bool {
pub fn unsafe_context(map: &ast_map::Map, id: ast::NodeId) -> bool { pub fn unsafe_context(map: &ast_map::Map, id: ast::NodeId) -> bool {
match map.find(map.get_parent(id)) { match map.find(map.get_parent(id)) {
Some(ast_map::NodeImplItem(itm)) => { Some(ast_map::NodeImplItem(itm)) => {
match *itm { match itm.node {
ast::MethodImplItem(ref meth) => match meth.node { ast::MethodImplItem(ref sig, _) => sig.unsafety == ast::Unsafety::Unsafe,
ast::MethDecl(_, _, _, _, style, _, _, _) => match style { _ => false
ast::Unsafety::Unsafe => true,
_ => false,
},
_ => false,
},
_ => false,
} }
}, },
Some(ast_map::NodeItem(itm)) => { Some(ast_map::NodeItem(itm)) => {

View file

@ -5,12 +5,8 @@
#![feature(box_syntax)] #![feature(box_syntax)]
#![feature(collections)] #![feature(collections)]
#![feature(core)] #![feature(core)]
#![cfg_attr(target_os="linux", feature(io))]
#![feature(old_io)]
#![cfg_attr(target_os="linux", feature(page_size))] #![cfg_attr(target_os="linux", feature(page_size))]
#![feature(rustc_private)] #![feature(rustc_private)]
#![feature(std_misc)]
#![cfg_attr(target_os="linux", feature(str_words))]
#[macro_use] extern crate log; #[macro_use] extern crate log;
@ -22,7 +18,7 @@ extern crate profile_traits;
extern crate regex; extern crate regex;
#[cfg(target_os="macos")] #[cfg(target_os="macos")]
extern crate task_info; extern crate task_info;
extern crate "time" as std_time; extern crate time as std_time;
extern crate util; extern crate util;
pub mod mem; pub mod mem;

View file

@ -9,9 +9,8 @@ use self::system_reporter::SystemReporter;
use std::borrow::ToOwned; use std::borrow::ToOwned;
use std::cmp::Ordering; use std::cmp::Ordering;
use std::collections::HashMap; use std::collections::HashMap;
use std::old_io::timer::sleep; use std::thread::sleep_ms;
use std::sync::mpsc::{channel, Receiver}; use std::sync::mpsc::{channel, Receiver};
use std::time::duration::Duration;
use util::task::spawn_named; use util::task::spawn_named;
pub struct Profiler { pub struct Profiler {
@ -28,11 +27,11 @@ impl Profiler {
// Create the timer thread if a period was provided. // Create the timer thread if a period was provided.
if let Some(period) = period { if let Some(period) = period {
let period_ms = Duration::milliseconds((period * 1000f64) as i64); let period_ms = (period * 1000.) as u32;
let chan = chan.clone(); let chan = chan.clone();
spawn_named("Memory profiler timer".to_owned(), move || { spawn_named("Memory profiler timer".to_owned(), move || {
loop { loop {
sleep(period_ms); sleep_ms(period_ms);
if chan.send(ProfilerMsg::Print).is_err() { if chan.send(ProfilerMsg::Print).is_err() {
break; break;
} }
@ -444,7 +443,7 @@ mod system_reporter {
let mut f = option_try!(File::open("/proc/self/statm").ok()); let mut f = option_try!(File::open("/proc/self/statm").ok());
let mut contents = String::new(); let mut contents = String::new();
option_try!(f.read_to_string(&mut contents).ok()); option_try!(f.read_to_string(&mut contents).ok());
let s = option_try!(contents.words().nth(field)); let s = option_try!(contents.split_whitespace().nth(field));
let npages = option_try!(s.parse::<usize>().ok()); let npages = option_try!(s.parse::<usize>().ok());
Some(npages * ::std::env::page_size()) Some(npages * ::std::env::page_size())
} }
@ -485,7 +484,7 @@ mod system_reporter {
use std::collections::HashMap; use std::collections::HashMap;
use std::collections::hash_map::Entry; use std::collections::hash_map::Entry;
use std::fs::File; use std::fs::File;
use std::io::{BufReader, BufReadExt}; use std::io::{BufReader, BufRead};
// The first line of an entry in /proc/<pid>/smaps looks just like an entry // The first line of an entry in /proc/<pid>/smaps looks just like an entry
// in /proc/<pid>/maps: // in /proc/<pid>/maps:

View file

@ -9,11 +9,8 @@ use profile_traits::time::{ProfilerCategory, ProfilerChan, ProfilerMsg, TimerMet
use std::borrow::ToOwned; use std::borrow::ToOwned;
use std::cmp::Ordering; use std::cmp::Ordering;
use std::f64; use std::f64;
use std::old_io::timer::sleep;
use std::iter::AdditiveIterator;
use std::num::Float;
use std::sync::mpsc::{channel, Receiver}; use std::sync::mpsc::{channel, Receiver};
use std::time::duration::Duration; use std::thread::sleep_ms;
use std_time::precise_time_ns; use std_time::precise_time_ns;
use util::task::spawn_named; use util::task::spawn_named;
@ -99,11 +96,11 @@ impl Profiler {
let (chan, port) = channel(); let (chan, port) = channel();
match period { match period {
Some(period) => { Some(period) => {
let period = Duration::milliseconds((period * 1000f64) as i64); let period = (period * 1000.) as u32;
let chan = chan.clone(); let chan = chan.clone();
spawn_named("Time profiler timer".to_owned(), move || { spawn_named("Time profiler timer".to_owned(), move || {
loop { loop {
sleep(period); sleep_ms(period);
if chan.send(ProfilerMsg::Print).is_err() { if chan.send(ProfilerMsg::Print).is_err() {
break; break;
} }
@ -192,7 +189,7 @@ impl Profiler {
let data_len = data.len(); let data_len = data.len();
if data_len > 0 { if data_len > 0 {
let (mean, median, min, max) = let (mean, median, min, max) =
(data.iter().map(|&x|x).sum() / (data_len as f64), (data.iter().map(|&x|x).sum::<f64>() / (data_len as f64),
data[data_len / 2], data[data_len / 2],
data.iter().fold(f64::INFINITY, |a, &b| a.min(b)), data.iter().fold(f64::INFINITY, |a, &b| a.min(b)),
data.iter().fold(-f64::INFINITY, |a, &b| a.max(b))); data.iter().fold(-f64::INFINITY, |a, &b| a.max(b)));

View file

@ -2,7 +2,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate "time" as std_time; extern crate time as std_time;
extern crate url; extern crate url;
use self::std_time::precise_time_ns; use self::std_time::precise_time_ns;

View file

@ -45,9 +45,6 @@ path = "../canvas"
[dependencies.webdriver_traits] [dependencies.webdriver_traits]
path = "../webdriver_traits" path = "../webdriver_traits"
[dependencies.cssparser]
git = "https://github.com/servo/rust-cssparser"
[dependencies.selectors] [dependencies.selectors]
git = "https://github.com/servo/rust-selectors" git = "https://github.com/servo/rust-selectors"
@ -80,3 +77,6 @@ bitflags = "*"
rustc-serialize = "*" rustc-serialize = "*"
libc = "*" libc = "*"
hyper = "0.3" hyper = "0.3"
cssparser = "0.3.1"
unicase = "0.1"
num = "0.1.24"

View file

@ -30,6 +30,7 @@ use hyper::header::{ContentType, Host};
use hyper::method::Method; use hyper::method::Method;
use hyper::status::StatusClass::Success; use hyper::status::StatusClass::Success;
use unicase::UniCase;
use url::{SchemeData, Url}; use url::{SchemeData, Url};
use util::task::spawn_named; use util::task::spawn_named;
@ -185,10 +186,10 @@ impl CORSRequest {
// Step 5 - 7 // Step 5 - 7
let mut header_names = vec!(); let mut header_names = vec!();
for header in self.headers.iter() { for header in self.headers.iter() {
header_names.push(header.name().to_ascii_lowercase()); header_names.push(header.name().to_owned());
} }
header_names.sort(); header_names.sort();
preflight.headers.set(AccessControlRequestHeaders(header_names)); preflight.headers.set(AccessControlRequestHeaders(header_names.into_iter().map(UniCase).collect()));
// Step 8 unnecessary, we don't use the request body // Step 8 unnecessary, we don't use the request body
// Step 9, 10 unnecessary, we're writing our own fetch code // Step 9, 10 unnecessary, we're writing our own fetch code
@ -446,8 +447,8 @@ fn is_simple_method(m: &Method) -> bool {
pub fn allow_cross_origin_request(req: &CORSRequest, headers: &Headers) -> bool { pub fn allow_cross_origin_request(req: &CORSRequest, headers: &Headers) -> bool {
//FIXME(seanmonstar): use req.headers.get::<AccessControlAllowOrigin>() //FIXME(seanmonstar): use req.headers.get::<AccessControlAllowOrigin>()
match headers.get() { match headers.get() {
Some(&AccessControlAllowOrigin::AllowStar) => true, // Not always true, depends on credentials mode Some(&AccessControlAllowOrigin::Any) => true, // Not always true, depends on credentials mode
Some(&AccessControlAllowOrigin::AllowOrigin(ref url)) => Some(&AccessControlAllowOrigin::Value(ref url)) =>
url.scheme == req.origin.scheme && url.scheme == req.origin.scheme &&
url.host() == req.origin.host() && url.host() == req.origin.host() &&
url.port() == req.origin.port(), url.port() == req.origin.port(),

View file

@ -14,7 +14,7 @@ use dom::node::window_from_node;
use std::borrow::ToOwned; use std::borrow::ToOwned;
/// Trait for elements with defined activation behavior /// Trait for elements with defined activation behavior
pub trait Activatable : Copy { pub trait Activatable {
fn as_element(&self) -> Temporary<Element>; fn as_element(&self) -> Temporary<Element>;
// Is this particular instance of the element activatable? // Is this particular instance of the element activatable?

View file

@ -56,15 +56,14 @@ use js::jsval::{UndefinedValue, NullValue, BooleanValue, Int32Value, UInt32Value
use js::jsval::{StringValue, ObjectValue, ObjectOrNullValue}; use js::jsval::{StringValue, ObjectValue, ObjectOrNullValue};
use libc; use libc;
use num::Float;
use std::borrow::ToOwned; use std::borrow::ToOwned;
use std::default; use std::default;
use std::marker::MarkerTrait;
use std::num::Float;
use std::slice; use std::slice;
/// A trait to retrieve the constants necessary to check if a `JSObject` /// A trait to retrieve the constants necessary to check if a `JSObject`
/// implements a given interface. /// implements a given interface.
pub trait IDLInterface: MarkerTrait { pub trait IDLInterface {
/// Returns the prototype ID. /// Returns the prototype ID.
fn get_prototype_id() -> PrototypeList::ID; fn get_prototype_id() -> PrototypeList::ID;
/// Returns the prototype depth, i.e., the number of interfaces this /// Returns the prototype depth, i.e., the number of interfaces this

View file

@ -641,7 +641,6 @@ impl<T: Reflectable> Root<T> {
} }
} }
#[unsafe_destructor]
impl<T: Reflectable> Drop for Root<T> { impl<T: Reflectable> Drop for Root<T> {
fn drop(&mut self) { fn drop(&mut self) {
self.root_list.unroot(self); self.root_list.unroot(self);

View file

@ -5,7 +5,7 @@
//! The `Finite<T>` struct. //! The `Finite<T>` struct.
use core::nonzero::Zeroable; use core::nonzero::Zeroable;
use std::num::Float; use num::Float;
use std::ops::Deref; use std::ops::Deref;
/// Encapsulates the IDL restricted float type. /// Encapsulates the IDL restricted float type.

View file

@ -110,7 +110,6 @@ impl<T: Reflectable> Clone for Trusted<T> {
} }
} }
#[unsafe_destructor]
impl<T: Reflectable> Drop for Trusted<T> { impl<T: Reflectable> Drop for Trusted<T> {
fn drop(&mut self) { fn drop(&mut self) {
let mut refcount = self.refcount.lock().unwrap(); let mut refcount = self.refcount.lock().unwrap();

View file

@ -56,7 +56,7 @@ use script_traits::UntrustedNodeAddress;
use msg::compositor_msg::ScriptListener; use msg::compositor_msg::ScriptListener;
use msg::constellation_msg::ConstellationChan; use msg::constellation_msg::ConstellationChan;
use net_traits::image::base::Image; use net_traits::image::base::Image;
use util::smallvec::{SmallVec1, SmallVec}; use util::smallvec::SmallVec1;
use util::str::{LengthOrPercentageOrAuto}; use util::str::{LengthOrPercentageOrAuto};
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
@ -64,7 +64,6 @@ use std::collections::hash_state::HashState;
use std::ffi::CString; use std::ffi::CString;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::intrinsics::return_address; use std::intrinsics::return_address;
use std::old_io::timer::Timer;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use std::rc::Rc; use std::rc::Rc;
use std::sync::Arc; use std::sync::Arc;
@ -252,7 +251,7 @@ no_jsmanaged_fields!(Receiver<T>);
no_jsmanaged_fields!(Rect<T>); no_jsmanaged_fields!(Rect<T>);
no_jsmanaged_fields!(Arc<T>); no_jsmanaged_fields!(Arc<T>);
no_jsmanaged_fields!(Image, ImageCacheChan, ImageCacheTask, ScriptControlChan); no_jsmanaged_fields!(Image, ImageCacheChan, ImageCacheTask, ScriptControlChan);
no_jsmanaged_fields!(Atom, Namespace, Timer); no_jsmanaged_fields!(Atom, Namespace);
no_jsmanaged_fields!(Trusted<T>); no_jsmanaged_fields!(Trusted<T>);
no_jsmanaged_fields!(PropertyDeclarationBlock); no_jsmanaged_fields!(PropertyDeclarationBlock);
no_jsmanaged_fields!(HashSet<T>); no_jsmanaged_fields!(HashSet<T>);
@ -444,7 +443,6 @@ impl<T: VecRootableType> RootedVec<T> {
} }
} }
#[unsafe_destructor]
impl<T: VecRootableType> Drop for RootedVec<T> { impl<T: VecRootableType> Drop for RootedVec<T> {
fn drop(&mut self) { fn drop(&mut self) {
RootedCollectionSet::remove(self); RootedCollectionSet::remove(self);

View file

@ -639,7 +639,7 @@ pub fn validate_and_extract(namespace: Option<DOMString>, qualified_name: &str)
let (prefix, local_name) = if qualified_name.contains(":") { let (prefix, local_name) = if qualified_name.contains(":") {
// Step 5. // Step 5.
let mut parts = qualified_name.splitn(1, ':'); let mut parts = qualified_name.splitn(2, ':');
let prefix = parts.next().unwrap(); let prefix = parts.next().unwrap();
debug_assert!(!prefix.is_empty()); debug_assert!(!prefix.is_empty());
let local_name = parts.next().unwrap(); let local_name = parts.next().unwrap();

View file

@ -12,10 +12,10 @@ use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;
use util::str::DOMString; use util::str::DOMString;
use num::ToPrimitive;
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
use std::borrow::ToOwned; use std::borrow::ToOwned;
use std::cmp::{min, max}; use std::cmp::{min, max};
use std::num::ToPrimitive;
#[jstraceable] #[jstraceable]
pub enum BlobTypeId { pub enum BlobTypeId {

View file

@ -36,9 +36,9 @@ use net_traits::image::base::Image;
use net_traits::image_cache_task::ImageCacheChan; use net_traits::image_cache_task::ImageCacheChan;
use png::PixelsByColorType; use png::PixelsByColorType;
use num::{Float, ToPrimitive};
use std::borrow::ToOwned; use std::borrow::ToOwned;
use std::cell::RefCell; use std::cell::RefCell;
use std::num::{Float, ToPrimitive};
use std::sync::{Arc}; use std::sync::{Arc};
use std::sync::mpsc::{channel, Sender}; use std::sync::mpsc::{channel, Sender};
@ -977,7 +977,6 @@ impl<'a> CanvasRenderingContext2DMethods for JSRef<'a, CanvasRenderingContext2D>
} }
} }
#[unsafe_destructor]
impl Drop for CanvasRenderingContext2D { impl Drop for CanvasRenderingContext2D {
fn drop(&mut self) { fn drop(&mut self) {
self.renderer.send(CanvasMsg::Common(CanvasCommonMsg::Close)).unwrap(); self.renderer.send(CanvasMsg::Common(CanvasCommonMsg::Close)).unwrap();

View file

@ -84,7 +84,6 @@ impl<'a> AutoWorkerReset<'a> {
} }
} }
#[unsafe_destructor]
impl<'a> Drop for AutoWorkerReset<'a> { impl<'a> Drop for AutoWorkerReset<'a> {
fn drop(&mut self) { fn drop(&mut self) {
*self.workerscope.worker.borrow_mut() = self.old_worker.clone(); *self.workerscope.worker.borrow_mut() = self.old_worker.clone();

View file

@ -81,6 +81,7 @@ use string_cache::{Atom, QualName};
use url::Url; use url::Url;
use js::jsapi::JSRuntime; use js::jsapi::JSRuntime;
use num::ToPrimitive;
use std::borrow::ToOwned; use std::borrow::ToOwned;
use std::collections::HashMap; use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::hash_map::Entry::{Occupied, Vacant};
@ -88,7 +89,6 @@ use std::ascii::AsciiExt;
use std::cell::{Cell, Ref}; use std::cell::{Cell, Ref};
use std::default::Default; use std::default::Default;
use std::sync::mpsc::channel; use std::sync::mpsc::channel;
use std::num::ToPrimitive;
use time; use time;
#[derive(PartialEq)] #[derive(PartialEq)]

View file

@ -10,7 +10,6 @@ use dom::bindings::num::Finite;
use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::window::Window; use dom::window::Window;
use util::geometry::Au; use util::geometry::Au;
use std::num::Float;
#[dom_struct] #[dom_struct]
pub struct DOMRect { pub struct DOMRect {

View file

@ -64,6 +64,7 @@ use style::properties::{PropertyDeclarationBlock, PropertyDeclaration, parse_sty
use style::properties::DeclaredValue::SpecifiedValue; use style::properties::DeclaredValue::SpecifiedValue;
use style::values::specified::CSSColor; use style::values::specified::CSSColor;
use util::namespace; use util::namespace;
use util::smallvec::VecLike;
use util::str::{DOMString, LengthOrPercentageOrAuto}; use util::str::{DOMString, LengthOrPercentageOrAuto};
use cssparser::Color; use cssparser::Color;
@ -74,16 +75,14 @@ use html5ever::serialize::TraversalScope::{IncludeNode, ChildrenOnly};
use html5ever::tree_builder::{NoQuirks, LimitedQuirks, Quirks}; use html5ever::tree_builder::{NoQuirks, LimitedQuirks, Quirks};
use selectors::matching::{matches, DeclarationBlock}; use selectors::matching::{matches, DeclarationBlock};
use selectors::parser::parse_author_origin_selector_list_from_str; use selectors::parser::parse_author_origin_selector_list_from_str;
use selectors::smallvec::VecLike;
use string_cache::{Atom, Namespace, QualName}; use string_cache::{Atom, Namespace, QualName};
use url::UrlParser; use url::UrlParser;
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
use std::borrow::{IntoCow, ToOwned}; use std::borrow::{Cow, ToOwned};
use std::cell::{Ref, RefMut}; use std::cell::{Ref, RefMut};
use std::default::Default; use std::default::Default;
use std::mem; use std::mem;
use std::old_io::Writer;
use std::sync::Arc; use std::sync::Arc;
#[dom_struct] #[dom_struct]
@ -257,7 +256,7 @@ impl RawLayoutElementHelpers for Element {
}; };
if let Some(color) = bgcolor { if let Some(color) = bgcolor {
hints.vec_push(from_declaration( hints.push(from_declaration(
PropertyDeclaration::BackgroundColor(SpecifiedValue( PropertyDeclaration::BackgroundColor(SpecifiedValue(
CSSColor { parsed: Color::RGBA(color), authored: None })))); CSSColor { parsed: Color::RGBA(color), authored: None }))));
} }
@ -1011,9 +1010,9 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
fn TagName(self) -> DOMString { fn TagName(self) -> DOMString {
let qualified_name = match self.prefix { let qualified_name = match self.prefix {
Some(ref prefix) => { Some(ref prefix) => {
(format!("{}:{}", &**prefix, &*self.local_name)).into_cow() Cow::Owned(format!("{}:{}", &**prefix, &*self.local_name))
}, },
None => self.local_name.into_cow() None => Cow::Borrowed(&*self.local_name)
}; };
if self.html_element_in_html_document() { if self.html_element_in_html_document() {
qualified_name.to_ascii_uppercase() qualified_name.to_ascii_uppercase()

View file

@ -87,7 +87,7 @@ impl<'a> FormDataMethods for JSRef<'a, FormData> {
// FIXME(https://github.com/rust-lang/rust/issues/23338) // FIXME(https://github.com/rust-lang/rust/issues/23338)
let data = self.data.borrow(); let data = self.data.borrow();
if data.contains_key(&name) { if data.contains_key(&name) {
match data[name][0].clone() { match data[&name][0].clone() {
FormDatum::StringData(ref s) => Some(eString(s.clone())), FormDatum::StringData(ref s) => Some(eString(s.clone())),
FormDatum::FileData(ref f) => { FormDatum::FileData(ref f) => {
Some(eFile(Unrooted::from_js(*f))) Some(eFile(Unrooted::from_js(*f)))

View file

@ -25,8 +25,8 @@ use dom::node::{Node, NodeHelpers, NodeTypeId, document_from_node, window_from_n
use dom::virtualmethods::VirtualMethods; use dom::virtualmethods::VirtualMethods;
use dom::window::WindowHelpers; use dom::window::WindowHelpers;
use num::ToPrimitive;
use std::default::Default; use std::default::Default;
use std::num::ToPrimitive;
use string_cache::Atom; use string_cache::Atom;
use util::str::DOMString; use util::str::DOMString;

View file

@ -167,10 +167,12 @@ impl HTMLCollection {
fn traverse(root: JSRef<Node>) fn traverse(root: JSRef<Node>)
-> FilterMap<Skip<TreeIterator>, -> FilterMap<Skip<TreeIterator>,
fn(Temporary<Node>) -> Option<Temporary<Element>>> { fn(Temporary<Node>) -> Option<Temporary<Element>>> {
fn to_temporary(node: Temporary<Node>) -> Option<Temporary<Element>> {
ElementCast::to_temporary(node)
}
root.traverse_preorder() root.traverse_preorder()
.skip(1) .skip(1)
.filter_map(ElementCast::to_temporary as .filter_map(to_temporary as fn(Temporary<Node>) -> Option<Temporary<Element>>)
fn(Temporary<Node>) -> Option<Temporary<Element>>)
} }
} }

View file

@ -176,7 +176,7 @@ fn to_snake_case(name: DOMString) -> DOMString {
for ch in name.chars() { for ch in name.chars() {
if ch.is_uppercase() { if ch.is_uppercase() {
attr_name.push('\x2d'); attr_name.push('\x2d');
attr_name.push(ch.to_lowercase()); attr_name.extend(ch.to_lowercase());
} else { } else {
attr_name.push(ch); attr_name.push(ch);
} }

View file

@ -33,7 +33,7 @@ impl ImageData {
if let Some(vec) = data { if let Some(vec) = data {
let js_object_data: *mut uint8_t = JS_GetUint8ClampedArrayData(js_object, cx); let js_object_data: *mut uint8_t = JS_GetUint8ClampedArrayData(js_object, cx);
ptr::copy_nonoverlapping(js_object_data, vec.as_ptr(), vec.len()) ptr::copy_nonoverlapping(vec.as_ptr(), js_object_data, vec.len())
} }
ImageData { ImageData {

View file

@ -450,7 +450,7 @@ fn key_location(key: constellation_msg::Key) -> u32 {
fn key_charcode(key: constellation_msg::Key, mods: constellation_msg::KeyModifiers) -> Option<u32> { fn key_charcode(key: constellation_msg::Key, mods: constellation_msg::KeyModifiers) -> Option<u32> {
let key = key_value(key, mods); let key = key_value(key, mods);
if key.len() == 1 { if key.len() == 1 {
Some(key.char_at(0) as u32) Some(key.chars().next().unwrap() as u32)
} else { } else {
None None
} }

View file

@ -179,7 +179,6 @@ impl NodeFlags {
} }
} }
#[unsafe_destructor]
impl Drop for Node { impl Drop for Node {
#[allow(unsafe_code)] #[allow(unsafe_code)]
fn drop(&mut self) { fn drop(&mut self) {
@ -987,8 +986,11 @@ impl<'a> NodeHelpers for JSRef<'a, Node> {
} }
fn child_elements(self) -> ChildElementIterator { fn child_elements(self) -> ChildElementIterator {
fn to_temporary(node: Temporary<Node>) -> Option<Temporary<Element>> {
ElementCast::to_temporary(node)
}
self.children() self.children()
.filter_map(ElementCast::to_temporary as fn(_) -> _) .filter_map(to_temporary as fn(_) -> _)
.peekable() .peekable()
} }

View file

@ -84,7 +84,7 @@ impl<'a> TextEncoderMethods for JSRef<'a, TextEncoder> {
let js_object: *mut JSObject = JS_NewUint8Array(cx, length); let js_object: *mut JSObject = JS_NewUint8Array(cx, length);
let js_object_data: *mut uint8_t = JS_GetUint8ArrayData(js_object, cx); let js_object_data: *mut uint8_t = JS_GetUint8ArrayData(js_object, cx);
ptr::copy_nonoverlapping(js_object_data, encoded.as_ptr(), length as usize); ptr::copy_nonoverlapping(encoded.as_ptr(), js_object_data, length as usize);
return js_object; return js_object;
} }
} }

View file

@ -28,7 +28,7 @@ pub fn load_script(head: JSRef<HTMLHeadElement>) {
p.push("user-agent-js"); p.push("user-agent-js");
p p
} else { } else {
PathBuf::new(path_str) PathBuf::from(path_str)
}; };
let mut files = read_dir(&path).ok().expect("Bad path passed to --userscripts") let mut files = read_dir(&path).ok().expect("Bad path passed to --userscripts")

View file

@ -61,7 +61,6 @@ impl WebGLRenderingContext {
} }
} }
#[unsafe_destructor]
impl Drop for WebGLRenderingContext { impl Drop for WebGLRenderingContext {
fn drop(&mut self) { fn drop(&mut self) {
self.renderer.send(CanvasMsg::Common(CanvasCommonMsg::Close)).unwrap(); self.renderer.send(CanvasMsg::Common(CanvasCommonMsg::Close)).unwrap();

View file

@ -61,7 +61,6 @@ use std::collections::HashSet;
use std::default::Default; use std::default::Default;
use std::ffi::CString; use std::ffi::CString;
use std::mem; use std::mem;
use std::num::Float;
use std::rc::Rc; use std::rc::Rc;
use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::mpsc::TryRecvError::{Empty, Disconnected}; use std::sync::mpsc::TryRecvError::{Empty, Disconnected};

View file

@ -56,15 +56,16 @@ use std::ascii::AsciiExt;
use std::borrow::ToOwned; use std::borrow::ToOwned;
use std::cell::{RefCell, Cell}; use std::cell::{RefCell, Cell};
use std::default::Default; use std::default::Default;
use std::old_io::Timer;
use std::str::FromStr; use std::str::FromStr;
use std::sync::{Mutex, Arc}; use std::sync::{Mutex, Arc};
use std::time::duration::Duration; use std::sync::mpsc::{channel, Sender, TryRecvError};
use std::thread::sleep_ms;
use time; use time;
use url::{Url, UrlParser}; use url::{Url, UrlParser};
use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams; use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams;
use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams::{eString, eURLSearchParams}; use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams::{eString, eURLSearchParams};
pub type SendParam = StringOrURLSearchParams; pub type SendParam = StringOrURLSearchParams;
#[derive(PartialEq, Copy, Clone)] #[derive(PartialEq, Copy, Clone)]
@ -140,7 +141,7 @@ pub struct XMLHttpRequest {
send_flag: Cell<bool>, send_flag: Cell<bool>,
global: GlobalField, global: GlobalField,
timer: DOMRefCell<Timer>, timeout_cancel: DOMRefCell<Option<Sender<()>>>,
fetch_time: Cell<i64>, fetch_time: Cell<i64>,
timeout_target: DOMRefCell<Option<Box<ScriptChan+Send>>>, timeout_target: DOMRefCell<Option<Box<ScriptChan+Send>>>,
generation_id: Cell<GenerationId>, generation_id: Cell<GenerationId>,
@ -174,7 +175,7 @@ impl XMLHttpRequest {
upload_events: Cell::new(false), upload_events: Cell::new(false),
global: GlobalField::from_rooted(&global), global: GlobalField::from_rooted(&global),
timer: DOMRefCell::new(Timer::new().unwrap()), timeout_cancel: DOMRefCell::new(None),
fetch_time: Cell::new(0), fetch_time: Cell::new(0),
timeout_target: DOMRefCell::new(None), timeout_target: DOMRefCell::new(None),
generation_id: Cell::new(GenerationId(0)), generation_id: Cell::new(GenerationId(0)),
@ -963,7 +964,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
let total = self.response_headers.borrow().get::<ContentLength>().map(|x| {**x as u64}); let total = self.response_headers.borrow().get::<ContentLength>().map(|x| {**x as u64});
self.dispatch_progress_event(false, type_, len, total); self.dispatch_progress_event(false, type_, len, total);
} }
fn set_timeout(self, timeout: u32) { fn set_timeout(self, duration_ms: u32) {
struct XHRTimeout { struct XHRTimeout {
xhr: TrustedXHRAddress, xhr: TrustedXHRAddress,
gen_id: GenerationId, gen_id: GenerationId,
@ -981,22 +982,23 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
// Sets up the object to timeout in a given number of milliseconds // Sets up the object to timeout in a given number of milliseconds
// This will cancel all previous timeouts // This will cancel all previous timeouts
let oneshot = self.timer.borrow_mut()
.oneshot(Duration::milliseconds(timeout as i64));
let timeout_target = (*self.timeout_target.borrow().as_ref().unwrap()).clone(); let timeout_target = (*self.timeout_target.borrow().as_ref().unwrap()).clone();
let global = self.global.root(); let global = self.global.root();
let xhr = Trusted::new(global.r().get_cx(), self, global.r().script_chan()); let xhr = Trusted::new(global.r().get_cx(), self, global.r().script_chan());
let gen_id = self.generation_id.get(); let gen_id = self.generation_id.get();
let (cancel_tx, cancel_rx) = channel();
*self.timeout_cancel.borrow_mut() = Some(cancel_tx);
spawn_named("XHR:Timer".to_owned(), move || { spawn_named("XHR:Timer".to_owned(), move || {
match oneshot.recv() { sleep_ms(duration_ms);
Ok(_) => { match cancel_rx.try_recv() {
Err(TryRecvError::Empty) => {
timeout_target.send(ScriptMsg::RunnableMsg(box XHRTimeout { timeout_target.send(ScriptMsg::RunnableMsg(box XHRTimeout {
xhr: xhr, xhr: xhr,
gen_id: gen_id, gen_id: gen_id,
})).unwrap(); })).unwrap();
}, },
Err(_) => { Err(TryRecvError::Disconnected) | Ok(()) => {
// This occurs if xhr.timeout (the sender) goes out of scope (i.e, xhr went out of scope) // This occurs if xhr.timeout_cancel (the sender) goes out of scope (i.e, xhr went out of scope)
// or if the oneshot timer was overwritten. The former case should not happen due to pinning. // or if the oneshot timer was overwritten. The former case should not happen due to pinning.
debug!("XHR timeout was overwritten or canceled") debug!("XHR timeout was overwritten or canceled")
} }
@ -1006,8 +1008,9 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
} }
fn cancel_timeout(self) { fn cancel_timeout(self) {
// oneshot() closes the previous channel, canceling the timeout if let Some(cancel_tx) = self.timeout_cancel.borrow_mut().take() {
self.timer.borrow_mut().oneshot(Duration::zero()); let _ = cancel_tx.send(());
}
} }
fn text_response(self) -> DOMString { fn text_response(self) -> DOMString {

View file

@ -0,0 +1,31 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/// A quick hack to work around the removal of [`std::old_io::timer::Timer`](
/// http://doc.rust-lang.org/1.0.0-beta/std/old_io/timer/struct.Timer.html )
use std::sync::mpsc::{channel, Receiver};
use std::thread::{spawn, sleep_ms};
pub fn oneshot(duration_ms: u32) -> Receiver<()> {
let (tx, rx) = channel();
spawn(move || {
sleep_ms(duration_ms);
let _ = tx.send(());
});
rx
}
pub fn periodic(duration_ms: u32) -> Receiver<()> {
let (tx, rx) = channel();
spawn(move || {
loop {
sleep_ms(duration_ms);
if tx.send(()).is_err() {
break
}
}
});
rx
}

View file

@ -16,7 +16,6 @@ use profile_traits::mem::{Reporter, ReportsChan};
use script_traits::{ScriptControlChan, OpaqueScriptLayoutChannel, UntrustedNodeAddress}; use script_traits::{ScriptControlChan, OpaqueScriptLayoutChannel, UntrustedNodeAddress};
use std::any::Any; use std::any::Any;
use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::mpsc::{channel, Receiver, Sender};
use std::boxed::BoxAny;
use style::animation::PropertyAnimation; use style::animation::PropertyAnimation;
use style::media_queries::MediaQueryList; use style::media_queries::MediaQueryList;
use style::stylesheets::Stylesheet; use style::stylesheets::Stylesheet;
@ -88,7 +87,7 @@ pub struct HitTestResponse(pub UntrustedNodeAddress);
pub struct MouseOverResponse(pub Vec<UntrustedNodeAddress>); pub struct MouseOverResponse(pub Vec<UntrustedNodeAddress>);
/// Why we're doing reflow. /// Why we're doing reflow.
#[derive(PartialEq, Copy, Debug)] #[derive(PartialEq, Copy, Clone, Debug)]
pub enum ReflowGoal { pub enum ReflowGoal {
/// We're reflowing in order to send a display list to the screen. /// We're reflowing in order to send a display list to the screen.
ForDisplay, ForDisplay,
@ -185,15 +184,15 @@ pub struct Animation {
/// A description of the property animation that is occurring. /// A description of the property animation that is occurring.
pub property_animation: PropertyAnimation, pub property_animation: PropertyAnimation,
/// The start time of the animation, as returned by `time::precise_time_s()`. /// The start time of the animation, as returned by `time::precise_time_s()`.
pub start_time: f64, pub start_time: f32,
/// The end time of the animation, as returned by `time::precise_time_s()`. /// The end time of the animation, as returned by `time::precise_time_s()`.
pub end_time: f64, pub end_time: f32,
} }
impl Animation { impl Animation {
/// Returns the duration of this animation in seconds. /// Returns the duration of this animation in seconds.
#[inline] #[inline]
pub fn duration(&self) -> f64 { pub fn duration(&self) -> f32 {
self.end_time - self.start_time self.end_time - self.start_time
} }
} }

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