Format remaining files

This commit is contained in:
Pyfisch 2018-11-06 13:01:35 +01:00
parent bf47f90da6
commit cb07debcb6
252 changed files with 5944 additions and 3744 deletions

View file

@ -30,31 +30,23 @@ mod platform {
// The minimum alignment guaranteed by the architecture. This value is used to
// add fast paths for low alignment values.
#[cfg(
all(
any(
target_arch = "arm",
target_arch = "mips",
target_arch = "mipsel",
target_arch = "powerpc"
)
)
)]
#[cfg(all(any(
target_arch = "arm",
target_arch = "mips",
target_arch = "mipsel",
target_arch = "powerpc"
)))]
const MIN_ALIGN: usize = 8;
#[cfg(
all(
any(
target_arch = "x86",
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "powerpc64",
target_arch = "powerpc64le",
target_arch = "mips64",
target_arch = "s390x",
target_arch = "sparc64"
)
)
)]
#[cfg(all(any(
target_arch = "x86",
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "powerpc64",
target_arch = "powerpc64le",
target_arch = "mips64",
target_arch = "s390x",
target_arch = "sparc64"
)))]
const MIN_ALIGN: usize = 16;
fn layout_to_flags(align: usize, size: usize) -> c_int {

View file

@ -74,7 +74,8 @@ impl BluetoothThreadFactory for IpcSender<BluetoothRequest> {
BluetoothAdapter::init()
} else {
BluetoothAdapter::init_mock()
}.ok();
}
.ok();
thread::Builder::new()
.name("BluetoothThread".to_owned())
.spawn(move || {
@ -465,8 +466,10 @@ impl BluetoothManager {
};
services.retain(|s| {
!uuid_is_blocklisted(&s.get_uuid().unwrap_or(String::new()), Blocklist::All) &&
self.allowed_services.get(device_id).map_or(false, |uuids| {
!uuid_is_blocklisted(&s.get_uuid().unwrap_or(String::new()), Blocklist::All) && self
.allowed_services
.get(device_id)
.map_or(false, |uuids| {
uuids.contains(&s.get_uuid().unwrap_or(String::new()))
})
});
@ -556,9 +559,9 @@ impl BluetoothManager {
}
fn characteristic_is_cached(&self, characteristic_id: &str) -> bool {
self.cached_characteristics.contains_key(characteristic_id) &&
self.characteristic_to_service
.contains_key(characteristic_id)
self.cached_characteristics.contains_key(characteristic_id) && self
.characteristic_to_service
.contains_key(characteristic_id)
}
// Descriptor

View file

@ -294,14 +294,16 @@ fn create_generic_access_service(
NUMBER_OF_DIGITALS_UUID.to_owned(),
vec![49],
)?;
number_of_digitals_descriptor_1.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])?;
number_of_digitals_descriptor_1
.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])?;
let number_of_digitals_descriptor_2 = create_descriptor_with_value(
&device_name_characteristic,
NUMBER_OF_DIGITALS_UUID.to_owned(),
vec![50],
)?;
number_of_digitals_descriptor_2.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])?;
number_of_digitals_descriptor_2
.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])?;
// Characteristic User Description Descriptor
let _characteristic_user_description = create_descriptor_with_value(

View file

@ -39,7 +39,7 @@ impl<'a> CanvasData<'a> {
size: Size2D<u32>,
webrender_api_sender: webrender_api::RenderApiSender,
antialias: AntialiasMode,
canvas_id: CanvasId
canvas_id: CanvasId,
) -> CanvasData<'a> {
let draw_target = CanvasData::create(size);
let path_builder = draw_target.create_path_builder();
@ -63,7 +63,7 @@ impl<'a> CanvasData<'a> {
image_size: Size2D<f64>,
dest_rect: Rect<f64>,
source_rect: Rect<f64>,
smoothing_enabled: bool
smoothing_enabled: bool,
) {
// We round up the floating pixel values to draw the pixels
let source_rect = source_rect.ceil();
@ -75,14 +75,22 @@ impl<'a> CanvasData<'a> {
};
let writer = |draw_target: &DrawTarget| {
write_image(&draw_target, image_data, source_rect.size, dest_rect,
smoothing_enabled, self.state.draw_options.composition,
self.state.draw_options.alpha);
write_image(
&draw_target,
image_data,
source_rect.size,
dest_rect,
smoothing_enabled,
self.state.draw_options.composition,
self.state.draw_options.alpha,
);
};
if self.need_to_draw_shadow() {
let rect = Rect::new(Point2D::new(dest_rect.origin.x as f32, dest_rect.origin.y as f32),
Size2D::new(dest_rect.size.width as f32, dest_rect.size.height as f32));
let rect = Rect::new(
Point2D::new(dest_rect.origin.x as f32, dest_rect.origin.y as f32),
Size2D::new(dest_rect.size.width as f32, dest_rect.size.height as f32),
);
self.draw_with_shadow(&rect, writer);
} else {
@ -103,7 +111,10 @@ impl<'a> CanvasData<'a> {
}
pub fn fill_text(&self, text: String, x: f64, y: f64, max_width: Option<f64>) {
error!("Unimplemented canvas2d.fillText. Values received: {}, {}, {}, {:?}.", text, x, y, max_width);
error!(
"Unimplemented canvas2d.fillText. Values received: {}, {}, {}, {:?}.",
text, x, y, max_width
);
}
pub fn fill_rect(&self, rect: &Rect<f32>) {
@ -111,7 +122,8 @@ impl<'a> CanvasData<'a> {
return; // Paint nothing if gradient size is zero.
}
let draw_rect = Rect::new(rect.origin,
let draw_rect = Rect::new(
rect.origin,
match self.state.fill_style {
Pattern::Surface(ref surface) => {
let surface_size = surface.size();
@ -119,21 +131,29 @@ impl<'a> CanvasData<'a> {
(true, true) => rect.size,
(true, false) => Size2D::new(rect.size.width, surface_size.height as f32),
(false, true) => Size2D::new(surface_size.width as f32, rect.size.height),
(false, false) => Size2D::new(surface_size.width as f32, surface_size.height as f32),
(false, false) => {
Size2D::new(surface_size.width as f32, surface_size.height as f32)
},
}
},
_ => rect.size,
}
},
);
if self.need_to_draw_shadow() {
self.draw_with_shadow(&draw_rect, |new_draw_target: &DrawTarget| {
new_draw_target.fill_rect(&draw_rect, self.state.fill_style.to_pattern_ref(),
Some(&self.state.draw_options));
new_draw_target.fill_rect(
&draw_rect,
self.state.fill_style.to_pattern_ref(),
Some(&self.state.draw_options),
);
});
} else {
self.drawtarget.fill_rect(&draw_rect, self.state.fill_style.to_pattern_ref(),
Some(&self.state.draw_options));
self.drawtarget.fill_rect(
&draw_rect,
self.state.fill_style.to_pattern_ref(),
Some(&self.state.draw_options),
);
}
}
@ -148,27 +168,40 @@ impl<'a> CanvasData<'a> {
if self.need_to_draw_shadow() {
self.draw_with_shadow(&rect, |new_draw_target: &DrawTarget| {
new_draw_target.stroke_rect(rect, self.state.stroke_style.to_pattern_ref(),
&self.state.stroke_opts, &self.state.draw_options);
new_draw_target.stroke_rect(
rect,
self.state.stroke_style.to_pattern_ref(),
&self.state.stroke_opts,
&self.state.draw_options,
);
});
} else if rect.size.width == 0. || rect.size.height == 0. {
let cap = match self.state.stroke_opts.line_join {
JoinStyle::Round => CapStyle::Round,
_ => CapStyle::Butt
_ => CapStyle::Butt,
};
let stroke_opts =
StrokeOptions::new(self.state.stroke_opts.line_width,
self.state.stroke_opts.line_join,
cap,
self.state.stroke_opts.miter_limit,
self.state.stroke_opts.mDashPattern);
self.drawtarget.stroke_line(rect.origin, rect.bottom_right(),
self.state.stroke_style.to_pattern_ref(),
&stroke_opts, &self.state.draw_options);
let stroke_opts = StrokeOptions::new(
self.state.stroke_opts.line_width,
self.state.stroke_opts.line_join,
cap,
self.state.stroke_opts.miter_limit,
self.state.stroke_opts.mDashPattern,
);
self.drawtarget.stroke_line(
rect.origin,
rect.bottom_right(),
self.state.stroke_style.to_pattern_ref(),
&stroke_opts,
&self.state.draw_options,
);
} else {
self.drawtarget.stroke_rect(rect, self.state.stroke_style.to_pattern_ref(),
&self.state.stroke_opts, &self.state.draw_options);
self.drawtarget.stroke_rect(
rect,
self.state.stroke_style.to_pattern_ref(),
&self.state.stroke_opts,
&self.state.draw_options,
);
}
}
@ -185,9 +218,11 @@ impl<'a> CanvasData<'a> {
return; // Paint nothing if gradient size is zero.
}
self.drawtarget.fill(&self.path_builder.finish(),
self.state.fill_style.to_pattern_ref(),
&self.state.draw_options);
self.drawtarget.fill(
&self.path_builder.finish(),
self.state.fill_style.to_pattern_ref(),
&self.state.draw_options,
);
}
pub fn stroke(&self) {
@ -195,10 +230,12 @@ impl<'a> CanvasData<'a> {
return; // Paint nothing if gradient size is zero.
}
self.drawtarget.stroke(&self.path_builder.finish(),
self.state.stroke_style.to_pattern_ref(),
&self.state.stroke_opts,
&self.state.draw_options);
self.drawtarget.stroke(
&self.path_builder.finish(),
self.state.stroke_style.to_pattern_ref(),
&self.state.stroke_opts,
&self.state.draw_options,
);
}
pub fn clip(&self) {
@ -210,7 +247,7 @@ impl<'a> CanvasData<'a> {
x: f64,
y: f64,
_fill_rule: FillRule,
chan: IpcSender<bool>
chan: IpcSender<bool>,
) {
let path = self.path_builder.finish();
let result = path.contains_point(x, y, &self.state.transform);
@ -227,19 +264,22 @@ impl<'a> CanvasData<'a> {
}
pub fn rect(&self, rect: &Rect<f32>) {
self.path_builder.move_to(Point2D::new(rect.origin.x, rect.origin.y));
self.path_builder.line_to(Point2D::new(rect.origin.x + rect.size.width, rect.origin.y));
self.path_builder.line_to(Point2D::new(rect.origin.x + rect.size.width,
rect.origin.y + rect.size.height));
self.path_builder.line_to(Point2D::new(rect.origin.x, rect.origin.y + rect.size.height));
self.path_builder
.move_to(Point2D::new(rect.origin.x, rect.origin.y));
self.path_builder
.line_to(Point2D::new(rect.origin.x + rect.size.width, rect.origin.y));
self.path_builder.line_to(Point2D::new(
rect.origin.x + rect.size.width,
rect.origin.y + rect.size.height,
));
self.path_builder.line_to(Point2D::new(
rect.origin.x,
rect.origin.y + rect.size.height,
));
self.path_builder.close();
}
pub fn quadratic_curve_to(
&self,
cp: &Point2D<AzFloat>,
endpoint: &Point2D<AzFloat>
) {
pub fn quadratic_curve_to(&self, cp: &Point2D<AzFloat>, endpoint: &Point2D<AzFloat>) {
self.path_builder.quadratic_curve_to(cp, endpoint)
}
@ -247,7 +287,7 @@ impl<'a> CanvasData<'a> {
&self,
cp1: &Point2D<AzFloat>,
cp2: &Point2D<AzFloat>,
endpoint: &Point2D<AzFloat>
endpoint: &Point2D<AzFloat>,
) {
self.path_builder.bezier_curve_to(cp1, cp2, endpoint)
}
@ -258,17 +298,13 @@ impl<'a> CanvasData<'a> {
radius: AzFloat,
start_angle: AzFloat,
end_angle: AzFloat,
ccw: bool
ccw: bool,
) {
self.path_builder.arc(*center, radius, start_angle, end_angle, ccw)
self.path_builder
.arc(*center, radius, start_angle, end_angle, ccw)
}
pub fn arc_to(
&self,
cp1: &Point2D<AzFloat>,
cp2: &Point2D<AzFloat>,
radius: AzFloat
) {
pub fn arc_to(&self, cp1: &Point2D<AzFloat>, cp2: &Point2D<AzFloat>, radius: AzFloat) {
let cp0 = self.path_builder.get_current_point();
let cp1 = *cp1;
let cp2 = *cp2;
@ -314,9 +350,17 @@ impl<'a> CanvasData<'a> {
let angle_end = (tp2.y - cy).atan2(tp2.x - cx);
self.line_to(&tp1);
if [cx, cy, angle_start, angle_end].iter().all(|x| x.is_finite()) {
self.arc(&Point2D::new(cx, cy), radius,
angle_start, angle_end, anticlockwise);
if [cx, cy, angle_start, angle_end]
.iter()
.all(|x| x.is_finite())
{
self.arc(
&Point2D::new(cx, cy),
radius,
angle_start,
angle_end,
anticlockwise,
);
}
}
@ -328,9 +372,17 @@ impl<'a> CanvasData<'a> {
rotation_angle: AzFloat,
start_angle: AzFloat,
end_angle: AzFloat,
ccw: bool
ccw: bool,
) {
self.path_builder.ellipse(*center, radius_x, radius_y, rotation_angle, start_angle, end_angle, ccw);
self.path_builder.ellipse(
*center,
radius_x,
radius_y,
rotation_angle,
start_angle,
end_angle,
ccw,
);
}
pub fn set_fill_style(&mut self, style: FillOrStrokeStyle) {
@ -371,7 +423,9 @@ impl<'a> CanvasData<'a> {
}
pub fn set_global_composition(&mut self, op: CompositionOrBlending) {
self.state.draw_options.set_composition_op(op.to_azure_style());
self.state
.draw_options
.set_composition_op(op.to_azure_style());
}
pub fn create(size: Size2D<u32>) -> DrawTarget {
@ -398,7 +452,13 @@ impl<'a> CanvasData<'a> {
#[allow(unsafe_code)]
pub fn send_pixels(&mut self, chan: IpcSender<Option<ByteBuf>>) {
let data = unsafe { self.drawtarget.snapshot().get_data_surface().data().to_vec() };
let data = unsafe {
self.drawtarget
.snapshot()
.get_data_surface()
.data()
.to_vec()
};
chan.send(Some(data.into())).unwrap();
}
@ -414,9 +474,9 @@ impl<'a> CanvasData<'a> {
is_opaque: false,
allow_mipmaps: false,
};
let data = webrender_api::ImageData::Raw(Arc::new(
unsafe { self.drawtarget.snapshot().get_data_surface().data().into() },
));
let data = webrender_api::ImageData::Raw(Arc::new(unsafe {
self.drawtarget.snapshot().get_data_surface().data().into()
}));
let mut txn = webrender_api::Transaction::new();
@ -424,15 +484,17 @@ impl<'a> CanvasData<'a> {
Some(image_key) => {
debug!("Updating image {:?}.", image_key);
txn.update_image(image_key, descriptor, data, None);
}
},
None => {
self.image_key = Some(self.webrender_api.generate_image_key());
debug!("New image {:?}.", self.image_key);
txn.add_image(self.image_key.unwrap(), descriptor, data, None);
}
},
}
if let Some(image_key) = mem::replace(&mut self.very_old_image_key, self.old_image_key.take()) {
if let Some(image_key) =
mem::replace(&mut self.very_old_image_key, self.old_image_key.take())
{
txn.delete_image(image_key);
}
@ -449,12 +511,15 @@ impl<'a> CanvasData<'a> {
assert_eq!(imagedata.len() % 4, 0);
assert_eq!(rect.size.area() as usize, imagedata.len() / 4);
pixels::byte_swap_and_premultiply_inplace(&mut imagedata);
let source_surface = self.drawtarget.create_source_surface_from_data(
&imagedata,
rect.size.to_i32(),
rect.size.width as i32 * 4,
SurfaceFormat::B8G8R8A8,
).unwrap();
let source_surface = self
.drawtarget
.create_source_surface_from_data(
&imagedata,
rect.size.to_i32(),
rect.size.width as i32 * 4,
SurfaceFormat::B8G8R8A8,
)
.unwrap();
self.drawtarget.copy_surface(
source_surface,
Rect::from_size(rect.size.to_i32()),
@ -481,15 +546,19 @@ impl<'a> CanvasData<'a> {
// https://html.spec.whatwg.org/multipage/#when-shadows-are-drawn
fn need_to_draw_shadow(&self) -> bool {
self.state.shadow_color.a != 0.0f32 &&
(self.state.shadow_offset_x != 0.0f64 ||
self.state.shadow_offset_y != 0.0f64 ||
self.state.shadow_blur != 0.0f64)
(self.state.shadow_offset_x != 0.0f64 ||
self.state.shadow_offset_y != 0.0f64 ||
self.state.shadow_blur != 0.0f64)
}
fn create_draw_target_for_shadow(&self, source_rect: &Rect<f32>) -> DrawTarget {
let draw_target = self.drawtarget.create_similar_draw_target(&Size2D::new(source_rect.size.width as i32,
source_rect.size.height as i32),
self.drawtarget.get_format());
let draw_target = self.drawtarget.create_similar_draw_target(
&Size2D::new(
source_rect.size.width as i32,
source_rect.size.height as i32,
),
self.drawtarget.get_format(),
);
let matrix = Transform2D::identity()
.pre_translate(-source_rect.origin.to_vector().cast())
.pre_mul(&self.state.transform);
@ -498,19 +567,26 @@ impl<'a> CanvasData<'a> {
}
fn draw_with_shadow<F>(&self, rect: &Rect<f32>, draw_shadow_source: F)
where F: FnOnce(&DrawTarget)
where
F: FnOnce(&DrawTarget),
{
let shadow_src_rect = self.state.transform.transform_rect(rect);
let new_draw_target = self.create_draw_target_for_shadow(&shadow_src_rect);
draw_shadow_source(&new_draw_target);
self.drawtarget.draw_surface_with_shadow(new_draw_target.snapshot(),
&Point2D::new(shadow_src_rect.origin.x as AzFloat,
shadow_src_rect.origin.y as AzFloat),
&self.state.shadow_color,
&Vector2D::new(self.state.shadow_offset_x as AzFloat,
self.state.shadow_offset_y as AzFloat),
(self.state.shadow_blur / 2.0f64) as AzFloat,
self.state.draw_options.composition);
self.drawtarget.draw_surface_with_shadow(
new_draw_target.snapshot(),
&Point2D::new(
shadow_src_rect.origin.x as AzFloat,
shadow_src_rect.origin.y as AzFloat,
),
&self.state.shadow_color,
&Vector2D::new(
self.state.shadow_offset_x as AzFloat,
self.state.shadow_offset_y as AzFloat,
),
(self.state.shadow_blur / 2.0f64) as AzFloat,
self.state.draw_options.composition,
);
}
/// It reads image data from the canvas
@ -519,11 +595,19 @@ impl<'a> CanvasData<'a> {
#[allow(unsafe_code)]
pub fn read_pixels(&self, read_rect: Rect<u32>, canvas_size: Size2D<u32>) -> Vec<u8> {
let canvas_rect = Rect::from_size(canvas_size);
if canvas_rect.intersection(&read_rect).map_or(true, |rect| rect.is_empty()) {
if canvas_rect
.intersection(&read_rect)
.map_or(true, |rect| rect.is_empty())
{
return vec![];
}
let data_surface = self.drawtarget.snapshot().get_data_surface();
pixels::get_rect(unsafe { data_surface.data() }, canvas_size.to_u32(), read_rect.to_u32()).into_owned()
pixels::get_rect(
unsafe { data_surface.data() },
canvas_size.to_u32(),
read_rect.to_u32(),
)
.into_owned()
}
}
@ -562,7 +646,13 @@ impl<'a> CanvasPaintState<'a> {
draw_options: DrawOptions::new(1.0, CompositionOp::Over, antialias),
fill_style: Pattern::Color(ColorPattern::new(Color::black())),
stroke_style: Pattern::Color(ColorPattern::new(Color::black())),
stroke_opts: StrokeOptions::new(1.0, JoinStyle::MiterOrBevel, CapStyle::Butt, 10.0, &[]),
stroke_opts: StrokeOptions::new(
1.0,
JoinStyle::MiterOrBevel,
CapStyle::Butt,
10.0,
&[],
),
transform: Transform2D::identity(),
shadow_offset_x: 0.0,
shadow_offset_y: 0.0,
@ -594,10 +684,10 @@ fn write_image(
dest_rect: Rect<f64>,
smoothing_enabled: bool,
composition_op: CompositionOp,
global_alpha: f32
global_alpha: f32,
) {
if image_data.is_empty() {
return
return;
}
let image_rect = Rect::new(Point2D::zero(), image_size);
@ -612,12 +702,14 @@ fn write_image(
};
let image_size = image_size.to_i32();
let source_surface = draw_target.create_source_surface_from_data(
&image_data,
image_size,
image_size.width * 4,
SurfaceFormat::B8G8R8A8,
).unwrap();
let source_surface = draw_target
.create_source_surface_from_data(
&image_data,
image_size,
image_size.width * 4,
SurfaceFormat::B8G8R8A8,
)
.unwrap();
let draw_surface_options = DrawSurfaceOptions::new(filter, true);
let draw_options = DrawOptions::new(global_alpha, composition_op, AntialiasMode::None);
draw_target.draw_surface(
@ -635,8 +727,7 @@ pub trait PointToi32 {
impl PointToi32 for Point2D<f64> {
fn to_i32(&self) -> Point2D<i32> {
Point2D::new(self.x.to_i32().unwrap(),
self.y.to_i32().unwrap())
Point2D::new(self.x.to_i32().unwrap(), self.y.to_i32().unwrap())
}
}
@ -646,8 +737,7 @@ pub trait SizeToi32 {
impl SizeToi32 for Size2D<f64> {
fn to_i32(&self) -> Size2D<i32> {
Size2D::new(self.width.to_i32().unwrap(),
self.height.to_i32().unwrap())
Size2D::new(self.width.to_i32().unwrap(), self.height.to_i32().unwrap())
}
}
@ -658,19 +748,24 @@ pub trait RectToi32 {
impl RectToi32 for Rect<f64> {
fn to_i32(&self) -> Rect<i32> {
Rect::new(Point2D::new(self.origin.x.to_i32().unwrap(),
self.origin.y.to_i32().unwrap()),
Size2D::new(self.size.width.to_i32().unwrap(),
self.size.height.to_i32().unwrap()))
Rect::new(
Point2D::new(
self.origin.x.to_i32().unwrap(),
self.origin.y.to_i32().unwrap(),
),
Size2D::new(
self.size.width.to_i32().unwrap(),
self.size.height.to_i32().unwrap(),
),
)
}
fn ceil(&self) -> Rect<f64> {
Rect::new(Point2D::new(self.origin.x.ceil(),
self.origin.y.ceil()),
Size2D::new(self.size.width.ceil(),
self.size.height.ceil()))
Rect::new(
Point2D::new(self.origin.x.ceil(), self.origin.y.ceil()),
Size2D::new(self.size.width.ceil(), self.size.height.ceil()),
)
}
}
pub trait ToAzureStyle {
@ -682,12 +777,13 @@ impl ToAzureStyle for Rect<f64> {
type Target = Rect<AzFloat>;
fn to_azure_style(self) -> Rect<AzFloat> {
Rect::new(Point2D::new(self.origin.x as AzFloat, self.origin.y as AzFloat),
Size2D::new(self.size.width as AzFloat, self.size.height as AzFloat))
Rect::new(
Point2D::new(self.origin.x as AzFloat, self.origin.y as AzFloat),
Size2D::new(self.size.width as AzFloat, self.size.height as AzFloat),
)
}
}
impl ToAzureStyle for LineCapStyle {
type Target = CapStyle;
@ -717,17 +813,17 @@ impl ToAzureStyle for CompositionStyle {
fn to_azure_style(self) -> CompositionOp {
match self {
CompositionStyle::SrcIn => CompositionOp::In,
CompositionStyle::SrcOut => CompositionOp::Out,
CompositionStyle::SrcOver => CompositionOp::Over,
CompositionStyle::SrcAtop => CompositionOp::Atop,
CompositionStyle::DestIn => CompositionOp::DestIn,
CompositionStyle::DestOut => CompositionOp::DestOut,
CompositionStyle::SrcIn => CompositionOp::In,
CompositionStyle::SrcOut => CompositionOp::Out,
CompositionStyle::SrcOver => CompositionOp::Over,
CompositionStyle::SrcAtop => CompositionOp::Atop,
CompositionStyle::DestIn => CompositionOp::DestIn,
CompositionStyle::DestOut => CompositionOp::DestOut,
CompositionStyle::DestOver => CompositionOp::DestOver,
CompositionStyle::DestAtop => CompositionOp::DestAtop,
CompositionStyle::Copy => CompositionOp::Source,
CompositionStyle::Lighter => CompositionOp::Add,
CompositionStyle::Xor => CompositionOp::Xor,
CompositionStyle::Copy => CompositionOp::Source,
CompositionStyle::Lighter => CompositionOp::Add,
CompositionStyle::Xor => CompositionOp::Xor,
}
}
}
@ -737,20 +833,20 @@ impl ToAzureStyle for BlendingStyle {
fn to_azure_style(self) -> CompositionOp {
match self {
BlendingStyle::Multiply => CompositionOp::Multiply,
BlendingStyle::Screen => CompositionOp::Screen,
BlendingStyle::Overlay => CompositionOp::Overlay,
BlendingStyle::Darken => CompositionOp::Darken,
BlendingStyle::Lighten => CompositionOp::Lighten,
BlendingStyle::Multiply => CompositionOp::Multiply,
BlendingStyle::Screen => CompositionOp::Screen,
BlendingStyle::Overlay => CompositionOp::Overlay,
BlendingStyle::Darken => CompositionOp::Darken,
BlendingStyle::Lighten => CompositionOp::Lighten,
BlendingStyle::ColorDodge => CompositionOp::ColorDodge,
BlendingStyle::ColorBurn => CompositionOp::ColorBurn,
BlendingStyle::HardLight => CompositionOp::HardLight,
BlendingStyle::SoftLight => CompositionOp::SoftLight,
BlendingStyle::ColorBurn => CompositionOp::ColorBurn,
BlendingStyle::HardLight => CompositionOp::HardLight,
BlendingStyle::SoftLight => CompositionOp::SoftLight,
BlendingStyle::Difference => CompositionOp::Difference,
BlendingStyle::Exclusion => CompositionOp::Exclusion,
BlendingStyle::Hue => CompositionOp::Hue,
BlendingStyle::Exclusion => CompositionOp::Exclusion,
BlendingStyle::Hue => CompositionOp::Hue,
BlendingStyle::Saturation => CompositionOp::Saturation,
BlendingStyle::Color => CompositionOp::Color,
BlendingStyle::Color => CompositionOp::Color,
BlendingStyle::Luminosity => CompositionOp::Luminosity,
}
}
@ -778,32 +874,49 @@ impl ToAzurePattern for FillOrStrokeStyle {
Pattern::Color(ColorPattern::new(color.to_azure_style()))
},
FillOrStrokeStyle::LinearGradient(ref linear_gradient_style) => {
let gradient_stops: Vec<GradientStop> = linear_gradient_style.stops.iter().map(|s| {
GradientStop {
let gradient_stops: Vec<GradientStop> = linear_gradient_style
.stops
.iter()
.map(|s| GradientStop {
offset: s.offset as AzFloat,
color: s.color.to_azure_style()
}
}).collect();
color: s.color.to_azure_style(),
})
.collect();
Pattern::LinearGradient(LinearGradientPattern::new(
&Point2D::new(linear_gradient_style.x0 as AzFloat, linear_gradient_style.y0 as AzFloat),
&Point2D::new(linear_gradient_style.x1 as AzFloat, linear_gradient_style.y1 as AzFloat),
&Point2D::new(
linear_gradient_style.x0 as AzFloat,
linear_gradient_style.y0 as AzFloat,
),
&Point2D::new(
linear_gradient_style.x1 as AzFloat,
linear_gradient_style.y1 as AzFloat,
),
drawtarget.create_gradient_stops(&gradient_stops, ExtendMode::Clamp),
&Transform2D::identity(),
))
},
FillOrStrokeStyle::RadialGradient(ref radial_gradient_style) => {
let gradient_stops: Vec<GradientStop> = radial_gradient_style.stops.iter().map(|s| {
GradientStop {
let gradient_stops: Vec<GradientStop> = radial_gradient_style
.stops
.iter()
.map(|s| GradientStop {
offset: s.offset as AzFloat,
color: s.color.to_azure_style()
}
}).collect();
color: s.color.to_azure_style(),
})
.collect();
Pattern::RadialGradient(RadialGradientPattern::new(
&Point2D::new(radial_gradient_style.x0 as AzFloat, radial_gradient_style.y0 as AzFloat),
&Point2D::new(radial_gradient_style.x1 as AzFloat, radial_gradient_style.y1 as AzFloat),
radial_gradient_style.r0 as AzFloat, radial_gradient_style.r1 as AzFloat,
&Point2D::new(
radial_gradient_style.x0 as AzFloat,
radial_gradient_style.y0 as AzFloat,
),
&Point2D::new(
radial_gradient_style.x1 as AzFloat,
radial_gradient_style.y1 as AzFloat,
),
radial_gradient_style.r0 as AzFloat,
radial_gradient_style.r1 as AzFloat,
drawtarget.create_gradient_stops(&gradient_stops, ExtendMode::Clamp),
&Transform2D::identity(),
))
@ -822,7 +935,7 @@ impl ToAzurePattern for FillOrStrokeStyle {
surface_style.repeat_y,
&Transform2D::identity(),
))
}
},
})
}
}
@ -831,9 +944,11 @@ impl ToAzureStyle for RGBA {
type Target = Color;
fn to_azure_style(self) -> Color {
Color::rgba(self.red_f32() as AzFloat,
self.green_f32() as AzFloat,
self.blue_f32() as AzFloat,
self.alpha_f32() as AzFloat)
Color::rgba(
self.red_f32() as AzFloat,
self.green_f32() as AzFloat,
self.blue_f32() as AzFloat,
self.alpha_f32() as AzFloat,
)
}
}

View file

@ -12,13 +12,13 @@ use std::collections::HashMap;
use std::thread;
use webrender_api;
pub struct CanvasPaintThread <'a> {
pub struct CanvasPaintThread<'a> {
canvases: HashMap<CanvasId, CanvasData<'a>>,
next_canvas_id: CanvasId,
}
impl<'a> CanvasPaintThread <'a> {
fn new() -> CanvasPaintThread <'a> {
impl<'a> CanvasPaintThread<'a> {
fn new() -> CanvasPaintThread<'a> {
CanvasPaintThread {
canvases: HashMap::new(),
next_canvas_id: CanvasId(0),
@ -29,52 +29,49 @@ impl<'a> CanvasPaintThread <'a> {
/// communicate with it.
pub fn start() -> IpcSender<CanvasMsg> {
let (sender, receiver) = ipc::channel::<CanvasMsg>().unwrap();
thread::Builder::new().name("CanvasThread".to_owned()).spawn(move || {
let mut canvas_paint_thread = CanvasPaintThread::new();
loop {
match receiver.recv() {
Ok(msg) => {
match msg {
thread::Builder::new()
.name("CanvasThread".to_owned())
.spawn(move || {
let mut canvas_paint_thread = CanvasPaintThread::new();
loop {
match receiver.recv() {
Ok(msg) => match msg {
CanvasMsg::Canvas2d(message, canvas_id) => {
canvas_paint_thread.process_canvas_2d_message(message, canvas_id);
},
CanvasMsg::Close(canvas_id) =>{
CanvasMsg::Close(canvas_id) => {
canvas_paint_thread.canvases.remove(&canvas_id);
},
CanvasMsg::Create(creator, size, webrenderer_api_sender, antialias) => {
let canvas_id = canvas_paint_thread.create_canvas(
size,
webrenderer_api_sender,
antialias
antialias,
);
creator.send(canvas_id).unwrap();
},
CanvasMsg::Recreate(size, canvas_id) =>{
CanvasMsg::Recreate(size, canvas_id) => {
canvas_paint_thread.canvas(canvas_id).recreate(size);
},
CanvasMsg::FromScript(message, canvas_id) => {
match message {
FromScriptMsg::SendPixels(chan) => {
canvas_paint_thread.canvas(canvas_id).send_pixels(chan);
}
}
CanvasMsg::FromScript(message, canvas_id) => match message {
FromScriptMsg::SendPixels(chan) => {
canvas_paint_thread.canvas(canvas_id).send_pixels(chan);
},
},
CanvasMsg::FromLayout(message, canvas_id) => {
match message {
FromLayoutMsg::SendData(chan) => {
canvas_paint_thread.canvas(canvas_id).send_data(chan);
}
}
CanvasMsg::FromLayout(message, canvas_id) => match message {
FromLayoutMsg::SendData(chan) => {
canvas_paint_thread.canvas(canvas_id).send_data(chan);
},
},
CanvasMsg::Exit => break,
}
},
Err(e) => {
warn!("Error on CanvasPaintThread receive ({})", e);
},
Err(e) => {
warn!("Error on CanvasPaintThread receive ({})", e);
},
}
}
}
}).expect("Thread spawning failed");
})
.expect("Thread spawning failed");
sender
}
@ -83,7 +80,7 @@ impl<'a> CanvasPaintThread <'a> {
&mut self,
size: Size2D<u32>,
webrender_api_sender: webrender_api::RenderApiSender,
antialias: bool
antialias: bool,
) -> CanvasId {
let antialias = if antialias {
AntialiasMode::Default
@ -105,33 +102,17 @@ impl<'a> CanvasPaintThread <'a> {
Canvas2dMsg::FillText(text, x, y, max_width) => {
self.canvas(canvas_id).fill_text(text, x, y, max_width)
},
Canvas2dMsg::FillRect(ref rect) => {
self.canvas(canvas_id).fill_rect(rect)
},
Canvas2dMsg::StrokeRect(ref rect) => {
self.canvas(canvas_id).stroke_rect(rect)
},
Canvas2dMsg::ClearRect(ref rect) => {
self.canvas(canvas_id).clear_rect(rect)
},
Canvas2dMsg::BeginPath => {
self.canvas(canvas_id).begin_path()
},
Canvas2dMsg::ClosePath => {
self.canvas(canvas_id).close_path()
},
Canvas2dMsg::Fill => {
self.canvas(canvas_id).fill()
},
Canvas2dMsg::Stroke => {
self.canvas(canvas_id).stroke()
},
Canvas2dMsg::Clip => {
self.canvas(canvas_id).clip()
},
Canvas2dMsg::IsPointInPath(x, y, fill_rule, chan) => {
self.canvas(canvas_id).is_point_in_path(x, y, fill_rule, chan)
},
Canvas2dMsg::FillRect(ref rect) => self.canvas(canvas_id).fill_rect(rect),
Canvas2dMsg::StrokeRect(ref rect) => self.canvas(canvas_id).stroke_rect(rect),
Canvas2dMsg::ClearRect(ref rect) => self.canvas(canvas_id).clear_rect(rect),
Canvas2dMsg::BeginPath => self.canvas(canvas_id).begin_path(),
Canvas2dMsg::ClosePath => self.canvas(canvas_id).close_path(),
Canvas2dMsg::Fill => self.canvas(canvas_id).fill(),
Canvas2dMsg::Stroke => self.canvas(canvas_id).stroke(),
Canvas2dMsg::Clip => self.canvas(canvas_id).clip(),
Canvas2dMsg::IsPointInPath(x, y, fill_rule, chan) => self
.canvas(canvas_id)
.is_point_in_path(x, y, fill_rule, chan),
Canvas2dMsg::DrawImage(
imagedata,
image_size,
@ -156,12 +137,11 @@ impl<'a> CanvasPaintThread <'a> {
image_size,
dest_rect,
source_rect,
smoothing
smoothing,
) => {
let image_data = self.canvas(canvas_id).read_pixels(
source_rect.to_u32(),
image_size.to_u32(),
);
let image_data = self
.canvas(canvas_id)
.read_pixels(source_rect.to_u32(), image_size.to_u32());
self.canvas(other_canvas_id).draw_image(
image_data.into(),
source_rect.size,
@ -170,68 +150,34 @@ impl<'a> CanvasPaintThread <'a> {
smoothing,
);
},
Canvas2dMsg::MoveTo(ref point) => {
self.canvas(canvas_id).move_to(point)
},
Canvas2dMsg::LineTo(ref point) => {
self.canvas(canvas_id).line_to(point)
},
Canvas2dMsg::Rect(ref rect) => {
self.canvas(canvas_id).rect(rect)
},
Canvas2dMsg::MoveTo(ref point) => self.canvas(canvas_id).move_to(point),
Canvas2dMsg::LineTo(ref point) => self.canvas(canvas_id).line_to(point),
Canvas2dMsg::Rect(ref rect) => self.canvas(canvas_id).rect(rect),
Canvas2dMsg::QuadraticCurveTo(ref cp, ref pt) => {
self.canvas(canvas_id).quadratic_curve_to(cp, pt)
}
self.canvas(canvas_id).quadratic_curve_to(cp, pt)
},
Canvas2dMsg::BezierCurveTo(ref cp1, ref cp2, ref pt) => {
self.canvas(canvas_id).bezier_curve_to(cp1, cp2, pt)
}
self.canvas(canvas_id).bezier_curve_to(cp1, cp2, pt)
},
Canvas2dMsg::Arc(ref center, radius, start, end, ccw) => {
self.canvas(canvas_id).arc(center, radius, start, end, ccw)
}
self.canvas(canvas_id).arc(center, radius, start, end, ccw)
},
Canvas2dMsg::ArcTo(ref cp1, ref cp2, radius) => {
self.canvas(canvas_id).arc_to(cp1, cp2, radius)
}
Canvas2dMsg::Ellipse(ref center, radius_x, radius_y, rotation, start, end, ccw) => {
self.canvas(canvas_id).ellipse(
center,
radius_x,
radius_y,
rotation,
start,
end,
ccw
)
}
Canvas2dMsg::RestoreContext => {
self.canvas(canvas_id).restore_context_state()
},
Canvas2dMsg::SaveContext => {
self.canvas(canvas_id).save_context_state()
},
Canvas2dMsg::SetFillStyle(style) => {
self.canvas(canvas_id).set_fill_style(style)
},
Canvas2dMsg::SetStrokeStyle(style) => {
self.canvas(canvas_id).set_stroke_style(style)
},
Canvas2dMsg::SetLineWidth(width) => {
self.canvas(canvas_id).set_line_width(width)
},
Canvas2dMsg::SetLineCap(cap) => {
self.canvas(canvas_id).set_line_cap(cap)
},
Canvas2dMsg::SetLineJoin(join) => {
self.canvas(canvas_id).set_line_join(join)
},
Canvas2dMsg::SetMiterLimit(limit) => {
self.canvas(canvas_id).set_miter_limit(limit)
},
Canvas2dMsg::SetTransform(ref matrix) => {
self.canvas(canvas_id).set_transform(matrix)
},
Canvas2dMsg::SetGlobalAlpha(alpha) => {
self.canvas(canvas_id).set_global_alpha(alpha)
},
Canvas2dMsg::Ellipse(ref center, radius_x, radius_y, rotation, start, end, ccw) => self
.canvas(canvas_id)
.ellipse(center, radius_x, radius_y, rotation, start, end, ccw),
Canvas2dMsg::RestoreContext => self.canvas(canvas_id).restore_context_state(),
Canvas2dMsg::SaveContext => self.canvas(canvas_id).save_context_state(),
Canvas2dMsg::SetFillStyle(style) => self.canvas(canvas_id).set_fill_style(style),
Canvas2dMsg::SetStrokeStyle(style) => self.canvas(canvas_id).set_stroke_style(style),
Canvas2dMsg::SetLineWidth(width) => self.canvas(canvas_id).set_line_width(width),
Canvas2dMsg::SetLineCap(cap) => self.canvas(canvas_id).set_line_cap(cap),
Canvas2dMsg::SetLineJoin(join) => self.canvas(canvas_id).set_line_join(join),
Canvas2dMsg::SetMiterLimit(limit) => self.canvas(canvas_id).set_miter_limit(limit),
Canvas2dMsg::SetTransform(ref matrix) => self.canvas(canvas_id).set_transform(matrix),
Canvas2dMsg::SetGlobalAlpha(alpha) => self.canvas(canvas_id).set_global_alpha(alpha),
Canvas2dMsg::SetGlobalComposition(op) => {
self.canvas(canvas_id).set_global_composition(op)
},
@ -240,7 +186,8 @@ impl<'a> CanvasPaintThread <'a> {
sender.send(&pixels).unwrap();
},
Canvas2dMsg::PutImageData(rect, receiver) => {
self.canvas(canvas_id).put_image_data(receiver.recv().unwrap(), rect);
self.canvas(canvas_id)
.put_image_data(receiver.recv().unwrap(), rect);
},
Canvas2dMsg::SetShadowOffsetX(value) => {
self.canvas(canvas_id).set_shadow_offset_x(value)
@ -248,12 +195,10 @@ impl<'a> CanvasPaintThread <'a> {
Canvas2dMsg::SetShadowOffsetY(value) => {
self.canvas(canvas_id).set_shadow_offset_y(value)
},
Canvas2dMsg::SetShadowBlur(value) => {
self.canvas(canvas_id).set_shadow_blur(value)
},
Canvas2dMsg::SetShadowColor(ref color) => {
self.canvas(canvas_id).set_shadow_color(color.to_azure_style())
},
Canvas2dMsg::SetShadowBlur(value) => self.canvas(canvas_id).set_shadow_blur(value),
Canvas2dMsg::SetShadowColor(ref color) => self
.canvas(canvas_id)
.set_shadow_color(color.to_azure_style()),
}
}

View file

@ -48,7 +48,7 @@ impl GLContextFactory {
&self,
webgl_version: WebGLVersion,
size: Size2D<u32>,
attributes: GLContextAttributes
attributes: GLContextAttributes,
) -> Result<GLContextWrapper, &'static str> {
Ok(match *self {
GLContextFactory::Native(ref handle, ref dispatcher) => {
@ -63,7 +63,7 @@ impl GLContextFactory {
Some(handle),
dispatcher,
)?)
}
},
GLContextFactory::OSMesa(ref handle) => {
GLContextWrapper::OSMesa(GLContext::new_shared_with_dispatcher(
// FIXME(nox): Why are those i32 values?
@ -75,7 +75,7 @@ impl GLContextFactory {
Some(handle),
None,
)?)
}
},
})
}
@ -84,7 +84,7 @@ impl GLContextFactory {
&self,
webgl_version: WebGLVersion,
size: Size2D<u32>,
attributes: GLContextAttributes
attributes: GLContextAttributes,
) -> Result<GLContextWrapper, &'static str> {
Ok(match *self {
GLContextFactory::Native(..) => {
@ -98,7 +98,7 @@ impl GLContextFactory {
None,
None,
)?)
}
},
GLContextFactory::OSMesa(_) => {
GLContextWrapper::OSMesa(GLContext::new_shared_with_dispatcher(
// FIXME(nox): Why are those i32 values?
@ -110,7 +110,7 @@ impl GLContextFactory {
None,
None,
)?)
}
},
})
}
@ -122,7 +122,6 @@ impl GLContextFactory {
}
}
/// GLContextWrapper used to abstract NativeGLContext and OSMesaContext types
pub enum GLContextWrapper {
Native(GLContext<NativeGLContext>),
@ -134,10 +133,10 @@ impl GLContextWrapper {
match *self {
GLContextWrapper::Native(ref ctx) => {
ctx.make_current().unwrap();
}
},
GLContextWrapper::OSMesa(ref ctx) => {
ctx.make_current().unwrap();
}
},
}
}
@ -145,10 +144,10 @@ impl GLContextWrapper {
match *self {
GLContextWrapper::Native(ref ctx) => {
ctx.unbind().unwrap();
}
},
GLContextWrapper::OSMesa(ref ctx) => {
ctx.unbind().unwrap();
}
},
}
}
@ -156,26 +155,22 @@ impl GLContextWrapper {
&self,
cmd: WebGLCommand,
backtrace: WebGLCommandBacktrace,
state: &mut GLState
state: &mut GLState,
) {
match *self {
GLContextWrapper::Native(ref ctx) => {
WebGLImpl::apply(ctx, state, cmd, backtrace);
}
},
GLContextWrapper::OSMesa(ref ctx) => {
WebGLImpl::apply(ctx, state, cmd, backtrace);
}
},
}
}
pub fn gl(&self) -> &gl::Gl {
match *self {
GLContextWrapper::Native(ref ctx) => {
ctx.gl()
}
GLContextWrapper::OSMesa(ref ctx) => {
ctx.gl()
}
GLContextWrapper::Native(ref ctx) => ctx.gl(),
GLContextWrapper::OSMesa(ref ctx) => ctx.gl(),
}
}
@ -184,23 +179,29 @@ impl GLContextWrapper {
GLContextWrapper::Native(ref ctx) => {
let (real_size, texture_id) = {
let draw_buffer = ctx.borrow_draw_buffer().unwrap();
(draw_buffer.size(), draw_buffer.get_bound_texture_id().unwrap())
(
draw_buffer.size(),
draw_buffer.get_bound_texture_id().unwrap(),
)
};
let limits = ctx.borrow_limits().clone();
(real_size, texture_id, limits)
}
},
GLContextWrapper::OSMesa(ref ctx) => {
let (real_size, texture_id) = {
let draw_buffer = ctx.borrow_draw_buffer().unwrap();
(draw_buffer.size(), draw_buffer.get_bound_texture_id().unwrap())
(
draw_buffer.size(),
draw_buffer.get_bound_texture_id().unwrap(),
)
};
let limits = ctx.borrow_limits().clone();
(real_size, texture_id, limits)
}
},
}
}
@ -209,11 +210,11 @@ impl GLContextWrapper {
GLContextWrapper::Native(ref mut ctx) => {
// FIXME(nox): Why are those i32 values?
ctx.resize(size.to_i32())
}
},
GLContextWrapper::OSMesa(ref mut ctx) => {
// FIXME(nox): Why are those i32 values?
ctx.resize(size.to_i32())
}
},
}
}
}
@ -222,7 +223,7 @@ impl GLContextWrapper {
/// It's used in Windows to allow WGL GLContext sharing.
#[derive(Clone)]
pub struct MainThreadDispatcher {
compositor_proxy: Arc<Mutex<CompositorProxy>>
compositor_proxy: Arc<Mutex<CompositorProxy>>,
}
impl MainThreadDispatcher {
@ -234,6 +235,9 @@ impl MainThreadDispatcher {
}
impl GLContextDispatcher for MainThreadDispatcher {
fn dispatch(&self, f: Box<Fn() + Send>) {
self.compositor_proxy.lock().unwrap().send(compositor_thread::Msg::Dispatch(f));
self.compositor_proxy
.lock()
.unwrap()
.send(compositor_thread::Msg::Dispatch(f));
}
}

View file

@ -12,7 +12,8 @@ extern crate euclid;
extern crate fnv;
extern crate gleam;
extern crate ipc_channel;
#[macro_use] extern crate log;
#[macro_use]
extern crate log;
extern crate num_traits;
extern crate offscreen_gl_context;
extern crate pixels;

File diff suppressed because it is too large Load diff

View file

@ -22,7 +22,12 @@ pub struct CanvasId(pub u64);
#[derive(Deserialize, Serialize)]
pub enum CanvasMsg {
Canvas2d(Canvas2dMsg, CanvasId),
Create(IpcSender<CanvasId>, Size2D<u32>, webrender_api::RenderApiSender, bool),
Create(
IpcSender<CanvasId>,
Size2D<u32>,
webrender_api::RenderApiSender,
bool,
),
FromLayout(FromLayoutMsg, CanvasId),
FromScript(FromScriptMsg, CanvasId),
Recreate(Size2D<u32>, CanvasId),
@ -40,8 +45,7 @@ pub enum Canvas2dMsg {
Arc(Point2D<f32>, f32, f32, f32, bool),
ArcTo(Point2D<f32>, Point2D<f32>, f32),
DrawImage(Option<ByteBuf>, Size2D<f64>, Rect<f64>, Rect<f64>, bool),
DrawImageInOther(
CanvasId, Size2D<f64>, Rect<f64>, Rect<f64>, bool),
DrawImageInOther(CanvasId, Size2D<f64>, Rect<f64>, Rect<f64>, bool),
BeginPath,
BezierCurveTo(Point2D<f32>, Point2D<f32>, Point2D<f32>),
ClearRect(Rect<f32>),
@ -99,12 +103,17 @@ pub struct LinearGradientStyle {
pub y0: f64,
pub x1: f64,
pub y1: f64,
pub stops: Vec<CanvasGradientStop>
pub stops: Vec<CanvasGradientStop>,
}
impl LinearGradientStyle {
pub fn new(x0: f64, y0: f64, x1: f64, y1: f64, stops: Vec<CanvasGradientStop>)
-> LinearGradientStyle {
pub fn new(
x0: f64,
y0: f64,
x1: f64,
y1: f64,
stops: Vec<CanvasGradientStop>,
) -> LinearGradientStyle {
LinearGradientStyle {
x0: x0,
y0: y0,
@ -123,12 +132,19 @@ pub struct RadialGradientStyle {
pub x1: f64,
pub y1: f64,
pub r1: f64,
pub stops: Vec<CanvasGradientStop>
pub stops: Vec<CanvasGradientStop>,
}
impl RadialGradientStyle {
pub fn new(x0: f64, y0: f64, r0: f64, x1: f64, y1: f64, r1: f64, stops: Vec<CanvasGradientStop>)
-> RadialGradientStyle {
pub fn new(
x0: f64,
y0: f64,
r0: f64,
x1: f64,
y1: f64,
r1: f64,
stops: Vec<CanvasGradientStop>,
) -> RadialGradientStyle {
RadialGradientStyle {
x0: x0,
y0: y0,
@ -165,7 +181,6 @@ impl SurfaceStyle {
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum FillOrStrokeStyle {
Color(RGBA),
@ -256,18 +271,18 @@ impl FromStr for CompositionStyle {
fn from_str(string: &str) -> Result<CompositionStyle, ()> {
match string {
"source-in" => Ok(CompositionStyle::SrcIn),
"source-out" => Ok(CompositionStyle::SrcOut),
"source-over" => Ok(CompositionStyle::SrcOver),
"source-atop" => Ok(CompositionStyle::SrcAtop),
"destination-in" => Ok(CompositionStyle::DestIn),
"destination-out" => Ok(CompositionStyle::DestOut),
"source-in" => Ok(CompositionStyle::SrcIn),
"source-out" => Ok(CompositionStyle::SrcOut),
"source-over" => Ok(CompositionStyle::SrcOver),
"source-atop" => Ok(CompositionStyle::SrcAtop),
"destination-in" => Ok(CompositionStyle::DestIn),
"destination-out" => Ok(CompositionStyle::DestOut),
"destination-over" => Ok(CompositionStyle::DestOver),
"destination-atop" => Ok(CompositionStyle::DestAtop),
"copy" => Ok(CompositionStyle::Copy),
"lighter" => Ok(CompositionStyle::Lighter),
"xor" => Ok(CompositionStyle::Xor),
_ => Err(())
"copy" => Ok(CompositionStyle::Copy),
"lighter" => Ok(CompositionStyle::Lighter),
"xor" => Ok(CompositionStyle::Xor),
_ => Err(()),
}
}
}
@ -275,17 +290,17 @@ impl FromStr for CompositionStyle {
impl CompositionStyle {
pub fn to_str(&self) -> &str {
match *self {
CompositionStyle::SrcIn => "source-in",
CompositionStyle::SrcOut => "source-out",
CompositionStyle::SrcOver => "source-over",
CompositionStyle::SrcAtop => "source-atop",
CompositionStyle::DestIn => "destination-in",
CompositionStyle::DestOut => "destination-out",
CompositionStyle::SrcIn => "source-in",
CompositionStyle::SrcOut => "source-out",
CompositionStyle::SrcOver => "source-over",
CompositionStyle::SrcAtop => "source-atop",
CompositionStyle::DestIn => "destination-in",
CompositionStyle::DestOut => "destination-out",
CompositionStyle::DestOver => "destination-over",
CompositionStyle::DestAtop => "destination-atop",
CompositionStyle::Copy => "copy",
CompositionStyle::Lighter => "lighter",
CompositionStyle::Xor => "xor",
CompositionStyle::Copy => "copy",
CompositionStyle::Lighter => "lighter",
CompositionStyle::Xor => "xor",
}
}
}
@ -314,22 +329,22 @@ impl FromStr for BlendingStyle {
fn from_str(string: &str) -> Result<BlendingStyle, ()> {
match string {
"multiply" => Ok(BlendingStyle::Multiply),
"screen" => Ok(BlendingStyle::Screen),
"overlay" => Ok(BlendingStyle::Overlay),
"darken" => Ok(BlendingStyle::Darken),
"lighten" => Ok(BlendingStyle::Lighten),
"multiply" => Ok(BlendingStyle::Multiply),
"screen" => Ok(BlendingStyle::Screen),
"overlay" => Ok(BlendingStyle::Overlay),
"darken" => Ok(BlendingStyle::Darken),
"lighten" => Ok(BlendingStyle::Lighten),
"color-dodge" => Ok(BlendingStyle::ColorDodge),
"color-burn" => Ok(BlendingStyle::ColorBurn),
"hard-light" => Ok(BlendingStyle::HardLight),
"soft-light" => Ok(BlendingStyle::SoftLight),
"difference" => Ok(BlendingStyle::Difference),
"exclusion" => Ok(BlendingStyle::Exclusion),
"hue" => Ok(BlendingStyle::Hue),
"saturation" => Ok(BlendingStyle::Saturation),
"color" => Ok(BlendingStyle::Color),
"luminosity" => Ok(BlendingStyle::Luminosity),
_ => Err(())
"color-burn" => Ok(BlendingStyle::ColorBurn),
"hard-light" => Ok(BlendingStyle::HardLight),
"soft-light" => Ok(BlendingStyle::SoftLight),
"difference" => Ok(BlendingStyle::Difference),
"exclusion" => Ok(BlendingStyle::Exclusion),
"hue" => Ok(BlendingStyle::Hue),
"saturation" => Ok(BlendingStyle::Saturation),
"color" => Ok(BlendingStyle::Color),
"luminosity" => Ok(BlendingStyle::Luminosity),
_ => Err(()),
}
}
}
@ -337,20 +352,20 @@ impl FromStr for BlendingStyle {
impl BlendingStyle {
pub fn to_str(&self) -> &str {
match *self {
BlendingStyle::Multiply => "multiply",
BlendingStyle::Screen => "screen",
BlendingStyle::Overlay => "overlay",
BlendingStyle::Darken => "darken",
BlendingStyle::Lighten => "lighten",
BlendingStyle::Multiply => "multiply",
BlendingStyle::Screen => "screen",
BlendingStyle::Overlay => "overlay",
BlendingStyle::Darken => "darken",
BlendingStyle::Lighten => "lighten",
BlendingStyle::ColorDodge => "color-dodge",
BlendingStyle::ColorBurn => "color-burn",
BlendingStyle::HardLight => "hard-light",
BlendingStyle::SoftLight => "soft-light",
BlendingStyle::ColorBurn => "color-burn",
BlendingStyle::HardLight => "hard-light",
BlendingStyle::SoftLight => "soft-light",
BlendingStyle::Difference => "difference",
BlendingStyle::Exclusion => "exclusion",
BlendingStyle::Hue => "hue",
BlendingStyle::Exclusion => "exclusion",
BlendingStyle::Hue => "hue",
BlendingStyle::Saturation => "saturation",
BlendingStyle::Color => "color",
BlendingStyle::Color => "color",
BlendingStyle::Luminosity => "luminosity",
}
}

View file

@ -4,18 +4,20 @@
#![crate_name = "canvas_traits"]
#![crate_type = "rlib"]
#![deny(unsafe_code)]
extern crate cssparser;
extern crate euclid;
extern crate gleam;
extern crate ipc_channel;
#[macro_use] extern crate lazy_static;
#[macro_use]
extern crate lazy_static;
extern crate malloc_size_of;
#[macro_use] extern crate malloc_size_of_derive;
#[macro_use]
extern crate malloc_size_of_derive;
extern crate offscreen_gl_context;
#[macro_use] extern crate serde;
#[macro_use]
extern crate serde;
extern crate serde_bytes;
extern crate servo_config;
extern crate webrender_api;

View file

@ -134,13 +134,15 @@ impl WebGLMsgSender {
/// Send a WebGLCommand message
#[inline]
pub fn send(&self, command: WebGLCommand, backtrace: WebGLCommandBacktrace) -> WebGLSendResult {
self.sender.send(WebGLMsg::WebGLCommand(self.ctx_id, command, backtrace))
self.sender
.send(WebGLMsg::WebGLCommand(self.ctx_id, command, backtrace))
}
/// Send a WebVRCommand message
#[inline]
pub fn send_vr(&self, command: WebVRCommand) -> WebGLSendResult {
self.sender.send(WebGLMsg::WebVRCommand(self.ctx_id, command))
self.sender
.send(WebGLMsg::WebVRCommand(self.ctx_id, command))
}
/// Send a resize message
@ -150,7 +152,8 @@ impl WebGLMsgSender {
size: Size2D<u32>,
sender: WebGLSender<Result<(), String>>,
) -> WebGLSendResult {
self.sender.send(WebGLMsg::ResizeContext(self.ctx_id, size, sender))
self.sender
.send(WebGLMsg::ResizeContext(self.ctx_id, size, sender))
}
#[inline]
@ -160,7 +163,8 @@ impl WebGLMsgSender {
#[inline]
pub fn send_update_wr_image(&self, sender: WebGLSender<ImageKey>) -> WebGLSendResult {
self.sender.send(WebGLMsg::UpdateWebRenderImage(self.ctx_id, sender))
self.sender
.send(WebGLMsg::UpdateWebRenderImage(self.ctx_id, sender))
}
pub fn send_dom_to_texture(&self, command: DOMToTextureCommand) -> WebGLSendResult {
@ -290,11 +294,34 @@ pub enum WebGLCommand {
GetTexParameterInt(u32, TexParameterInt, WebGLSender<i32>),
TexParameteri(u32, u32, i32),
TexParameterf(u32, u32, f32),
DrawArrays { mode: u32, first: i32, count: i32 },
DrawArraysInstanced { mode: u32, first: i32, count: i32, primcount: i32 },
DrawElements { mode: u32, count: i32, type_: u32, offset: u32 },
DrawElementsInstanced { mode: u32, count: i32, type_: u32, offset: u32, primcount: i32 },
VertexAttribDivisor { index: u32, divisor: u32 },
DrawArrays {
mode: u32,
first: i32,
count: i32,
},
DrawArraysInstanced {
mode: u32,
first: i32,
count: i32,
primcount: i32,
},
DrawElements {
mode: u32,
count: i32,
type_: u32,
offset: u32,
},
DrawElementsInstanced {
mode: u32,
count: i32,
type_: u32,
offset: u32,
primcount: i32,
},
VertexAttribDivisor {
index: u32,
divisor: u32,
},
GetUniformBool(WebGLProgramId, i32, WebGLSender<bool>),
GetUniformBool2(WebGLProgramId, i32, WebGLSender<[bool; 2]>),
GetUniformBool3(WebGLProgramId, i32, WebGLSender<[bool; 3]>),
@ -309,7 +336,11 @@ pub enum WebGLCommand {
GetUniformFloat4(WebGLProgramId, i32, WebGLSender<[f32; 4]>),
GetUniformFloat9(WebGLProgramId, i32, WebGLSender<[f32; 9]>),
GetUniformFloat16(WebGLProgramId, i32, WebGLSender<[f32; 16]>),
InitializeFramebuffer { color: bool, depth: bool, stencil: bool },
InitializeFramebuffer {
color: bool,
depth: bool,
stencil: bool,
},
}
macro_rules! define_resource_id_struct {
@ -329,7 +360,6 @@ macro_rules! define_resource_id_struct {
self.0.get()
}
}
};
}
@ -340,7 +370,8 @@ macro_rules! define_resource_id {
#[allow(unsafe_code)]
impl<'de> ::serde::Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: ::serde::Deserializer<'de>
where
D: ::serde::Deserializer<'de>,
{
let id = u32::deserialize(deserializer)?;
if id == 0 {
@ -353,32 +384,33 @@ macro_rules! define_resource_id {
impl ::serde::Serialize for $name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: ::serde::Serializer
where
S: ::serde::Serializer,
{
self.get().serialize(serializer)
}
}
impl ::std::fmt::Debug for $name {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter)
-> Result<(), ::std::fmt::Error> {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
fmt.debug_tuple(stringify!($name))
.field(&self.get())
.finish()
.field(&self.get())
.finish()
}
}
impl ::std::fmt::Display for $name {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter)
-> Result<(), ::std::fmt::Error> {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
write!(fmt, "{}", self.get())
}
}
impl ::malloc_size_of::MallocSizeOf for $name {
fn size_of(&self, _ops: &mut ::malloc_size_of::MallocSizeOfOps) -> usize { 0 }
fn size_of(&self, _ops: &mut ::malloc_size_of::MallocSizeOfOps) -> usize {
0
}
}
}
};
}
define_resource_id!(WebGLBufferId);
@ -389,8 +421,9 @@ define_resource_id!(WebGLProgramId);
define_resource_id!(WebGLShaderId);
define_resource_id!(WebGLVertexArrayId);
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord)]
#[derive(PartialEq, PartialOrd, Serialize)]
#[derive(
Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize,
)]
pub struct WebGLContextId(pub usize);
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
@ -423,7 +456,7 @@ pub enum WebVRCommand {
/// Submit the frame to a VR device using the specified texture coordinates.
SubmitFrame(WebVRDeviceId, [f32; 4], [f32; 4]),
/// Stop presenting to a VR device
Release(WebVRDeviceId)
Release(WebVRDeviceId),
}
// Trait object that handles WebVR commands.
@ -436,7 +469,13 @@ pub trait WebVRRenderHandler: Send {
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum DOMToTextureCommand {
/// Attaches a HTMLIFrameElement to a WebGLTexture.
Attach(WebGLContextId, WebGLTextureId, DocumentId, PipelineId, Size2D<i32>),
Attach(
WebGLContextId,
WebGLTextureId,
DocumentId,
PipelineId,
Size2D<i32>,
),
/// Releases the HTMLIFrameElement to WebGLTexture attachment.
Detach(WebGLTextureId),
/// Lock message used for a correct synchronization with WebRender GL flow.

View file

@ -18,43 +18,42 @@ use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
pub fn route_ipc_receiver_to_new_servo_receiver<T>(ipc_receiver: IpcReceiver<T>) -> Receiver<T>
where
T: for<'de> Deserialize<'de> + Serialize + Send + 'static
T: for<'de> Deserialize<'de> + Serialize + Send + 'static,
{
let (servo_sender, servo_receiver) = channel();
ROUTER.add_route(
ipc_receiver.to_opaque(),
Box::new(move |message| {
drop(servo_sender.send(message.to::<T>().unwrap()))
}),
Box::new(move |message| drop(servo_sender.send(message.to::<T>().unwrap()))),
);
servo_receiver
}
pub fn route_ipc_receiver_to_new_servo_sender<T>(ipc_receiver: IpcReceiver<T>, servo_sender: Sender<T>)
where
T: for<'de> Deserialize<'de> + Serialize + Send + 'static
pub fn route_ipc_receiver_to_new_servo_sender<T>(
ipc_receiver: IpcReceiver<T>,
servo_sender: Sender<T>,
) where
T: for<'de> Deserialize<'de> + Serialize + Send + 'static,
{
ROUTER.add_route(
ipc_receiver.to_opaque(),
Box::new(move |message| {
drop(servo_sender.send(message.to::<T>().unwrap()))
}),
Box::new(move |message| drop(servo_sender.send(message.to::<T>().unwrap()))),
)
}
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
let (base_sender, base_receiver) = crossbeam_channel::unbounded::<T>();
let is_disconnected = Arc::new(AtomicBool::new(false));
(Sender::new(base_sender, is_disconnected.clone()),
Receiver::new(base_receiver, is_disconnected))
(
Sender::new(base_sender, is_disconnected.clone()),
Receiver::new(base_receiver, is_disconnected),
)
}
#[derive(Debug, PartialEq)]
pub enum ChannelError {
ChannelClosedError
ChannelClosedError,
}
pub struct Receiver<T> {
@ -78,7 +77,10 @@ impl<T> Clone for Receiver<T> {
}
impl<T> Receiver<T> {
pub fn new(receiver: crossbeam_channel::Receiver<T>, is_disconnected: Arc<AtomicBool>) -> Receiver<T> {
pub fn new(
receiver: crossbeam_channel::Receiver<T>,
is_disconnected: Arc<AtomicBool>,
) -> Receiver<T> {
Receiver {
receiver,
is_disconnected,
@ -134,7 +136,10 @@ impl<T> Clone for Sender<T> {
}
impl<T> Sender<T> {
pub fn new(sender: crossbeam_channel::Sender<T>, is_disconnected: Arc<AtomicBool>) -> Sender<T> {
pub fn new(
sender: crossbeam_channel::Sender<T>,
is_disconnected: Arc<AtomicBool>,
) -> Sender<T> {
Sender {
sender,
is_disconnected,

View file

@ -36,7 +36,8 @@ fn main() {
.find(|pkg| {
pkg.get("name").and_then(|name| name.as_str()).unwrap_or("") ==
"webrender"
}).and_then(|pkg| pkg.get("source").and_then(|source| source.as_str()))
})
.and_then(|pkg| pkg.get("source").and_then(|source| source.as_str()))
.unwrap_or("unknown");
let parsed: Vec<&str> = source.split("#").collect();

View file

@ -498,7 +498,10 @@ impl<Window: WindowMethods> IOCompositor<Window> {
(Msg::GetScreenAvailSize(req), ShutdownState::NotShuttingDown) => {
if let Err(e) = req.send(self.embedder_coordinates.screen_avail) {
warn!("Sending response to get screen avail size failed ({:?}).", e);
warn!(
"Sending response to get screen avail size failed ({:?}).",
e
);
}
},
@ -839,7 +842,7 @@ impl<Window: WindowMethods> IOCompositor<Window> {
&mut self,
delta: ScrollLocation,
cursor: DeviceIntPoint,
phase: TouchEventType
phase: TouchEventType,
) {
match phase {
TouchEventType::Move => self.on_scroll_window_event(delta, cursor),
@ -852,11 +855,7 @@ impl<Window: WindowMethods> IOCompositor<Window> {
}
}
fn on_scroll_window_event(
&mut self,
scroll_location: ScrollLocation,
cursor: DeviceIntPoint
) {
fn on_scroll_window_event(&mut self, scroll_location: ScrollLocation, cursor: DeviceIntPoint) {
self.pending_scroll_zoom_events.push(ScrollZoomEvent {
magnification: 1.0,
scroll_location: scroll_location,
@ -1155,15 +1154,19 @@ impl<Window: WindowMethods> IOCompositor<Window> {
pub fn composite(&mut self) {
let target = self.composite_target;
match self.composite_specific_target(target) {
Ok(_) => if opts::get().output_file.is_some() || opts::get().exit_after_load {
println!("Shutting down the Constellation after generating an output file or exit flag specified");
self.start_shutting_down();
Ok(_) => {
if opts::get().output_file.is_some() || opts::get().exit_after_load {
println!("Shutting down the Constellation after generating an output file or exit flag specified");
self.start_shutting_down();
}
},
Err(e) => if opts::get().is_running_problem_test {
if e != UnableToComposite::NotReadyToPaintImage(
NotReadyToPaint::WaitingOnConstellation,
) {
println!("not ready to composite: {:?}", e);
Err(e) => {
if opts::get().is_running_problem_test {
if e != UnableToComposite::NotReadyToPaintImage(
NotReadyToPaint::WaitingOnConstellation,
) {
println!("not ready to composite: {:?}", e);
}
}
},
}
@ -1255,7 +1258,7 @@ impl<Window: WindowMethods> IOCompositor<Window> {
if let Some(pipeline) = self.pipeline(*id) {
// and inform the layout thread with the measured paint time.
let msg = LayoutControlMsg::PaintMetric(epoch, paint_time);
if let Err(e) = pipeline.layout_chan.send(msg) {
if let Err(e) = pipeline.layout_chan.send(msg) {
warn!("Sending PaintMetric message to layout failed ({:?}).", e);
}
}
@ -1445,7 +1448,8 @@ impl<Window: WindowMethods> IOCompositor<Window> {
val.as_ref()
.map(|dir| dir.join("capture_webrender").join(&capture_id))
.ok()
}).find(|val| match create_dir_all(&val) {
})
.find(|val| match create_dir_all(&val) {
Ok(_) => true,
Err(err) => {
eprintln!("Unable to create path '{:?}' for capture: {:?}", &val, err);

View file

@ -814,7 +814,8 @@ pub fn from_cmdline_args(args: &[String]) -> ArgumentParsingResult {
.or_else(|error| {
warn!("URL parsing failed ({:?}).", error);
Err(error)
}).ok()
})
.ok()
});
let tile_size: usize = match opt_match.opt_str("s") {
@ -940,7 +941,8 @@ pub fn from_cmdline_args(args: &[String]) -> ArgumentParsingResult {
r.parse().unwrap_or_else(|err| {
args_fail(&format!("Error parsing option: --resolution ({})", err))
})
}).collect();
})
.collect();
TypedSize2D::new(res[0], res[1])
},
None => TypedSize2D::new(1024, 740),
@ -970,7 +972,8 @@ pub fn from_cmdline_args(args: &[String]) -> ArgumentParsingResult {
.read_to_end(&mut contents)
.unwrap_or_else(|err| args_fail(&format!("Couldn't read {}: {}", filename, err)));
(contents, url)
}).collect();
})
.collect();
let do_not_use_native_titlebar = opt_match.opt_present("b") || !PREFS
.get("shell.native-titlebar.enabled")

View file

@ -192,7 +192,8 @@ fn init_user_prefs(path: &mut PathBuf) {
writeln!(
&mut stderr(),
"Error opening prefs.json from config directory"
).expect("failed printing to stderr");
)
.expect("failed printing to stderr");
}
}

View file

@ -718,9 +718,8 @@ where
match reg_host(&load_data.url) {
None => (None, None),
Some(host) => {
let event_loop = self
.event_loops.get(&host)
.and_then(|weak| weak.upgrade());
let event_loop =
self.event_loops.get(&host).and_then(|weak| weak.upgrade());
match event_loop {
None => (None, Some(host)),
Some(event_loop) => (Some(event_loop.clone()), None),
@ -855,7 +854,8 @@ where
is_private,
is_visible,
);
self.browsing_contexts.insert(browsing_context_id, browsing_context);
self.browsing_contexts
.insert(browsing_context_id, browsing_context);
// If this context is a nested container, attach it to parent pipeline.
if let Some(parent_pipeline_id) = parent_pipeline_id {
@ -866,7 +866,10 @@ where
}
fn add_pending_change(&mut self, change: SessionHistoryChange) {
self.handle_load_start_msg(change.top_level_browsing_context_id, change.browsing_context_id);
self.handle_load_start_msg(
change.top_level_browsing_context_id,
change.browsing_context_id,
);
self.pending_changes.push(change);
}
@ -1229,14 +1232,22 @@ where
.and_then(|pipeline| self.browsing_contexts.get(&pipeline.browsing_context_id))
.map(|ctx| (ctx.id, ctx.parent_pipeline_id));
if let Err(e) = sender.send(result) {
warn!("Sending reply to get browsing context info failed ({:?}).", e);
warn!(
"Sending reply to get browsing context info failed ({:?}).",
e
);
}
},
FromScriptMsg::GetTopForBrowsingContext(browsing_context_id, sender) => {
let result = self.browsing_contexts.get(&browsing_context_id)
let result = self
.browsing_contexts
.get(&browsing_context_id)
.and_then(|bc| Some(bc.top_level_id));
if let Err(e) = sender.send(result) {
warn!("Sending reply to get top for browsing context info failed ({:?}).", e);
warn!(
"Sending reply to get top for browsing context info failed ({:?}).",
e
);
}
},
FromScriptMsg::GetChildBrowsingContextId(browsing_context_id, index, sender) => {
@ -1641,11 +1652,14 @@ where
fn handle_new_top_level_browsing_context(
&mut self,
url: ServoUrl,
top_level_browsing_context_id: TopLevelBrowsingContextId
top_level_browsing_context_id: TopLevelBrowsingContextId,
) {
let window_size = self.window_size.initial_viewport;
let pipeline_id = PipelineId::new();
let msg = (Some(top_level_browsing_context_id), EmbedderMsg::BrowserCreated(top_level_browsing_context_id));
let msg = (
Some(top_level_browsing_context_id),
EmbedderMsg::BrowserCreated(top_level_browsing_context_id),
);
self.embedder_proxy.send(msg);
let browsing_context_id = BrowsingContextId::from(top_level_browsing_context_id);
let load_data = LoadData::new(url.clone(), None, None, None);
@ -1655,10 +1669,13 @@ where
// Register this new top-level browsing context id as a browser and set
// its focused browsing context to be itself.
self.browsers.insert(top_level_browsing_context_id, Browser {
focused_browsing_context_id: browsing_context_id,
session_history: JointSessionHistory::new(),
});
self.browsers.insert(
top_level_browsing_context_id,
Browser {
focused_browsing_context_id: browsing_context_id,
session_history: JointSessionHistory::new(),
},
);
self.new_pipeline(
pipeline_id,
@ -1718,11 +1735,12 @@ where
};
let parent_pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
Some(browsing_context) => browsing_context.parent_pipeline_id,
None => return warn!(
"Subframe {} loaded in closed browsing context {}.",
pipeline_id,
browsing_context_id,
),
None => {
return warn!(
"Subframe {} loaded in closed browsing context {}.",
pipeline_id, browsing_context_id,
)
},
};
let parent_pipeline_id = match parent_pipeline_id {
Some(parent_pipeline_id) => parent_pipeline_id,
@ -1779,7 +1797,8 @@ where
let (load_data, is_private) = {
// If no url is specified, reload.
let old_pipeline = load_info.old_pipeline_id
let old_pipeline = load_info
.old_pipeline_id
.and_then(|id| self.pipelines.get(&id));
let load_data = load_info.load_data.unwrap_or_else(|| {
let url = match old_pipeline {
@ -1792,23 +1811,25 @@ where
});
let is_parent_private = {
let parent_browsing_context_id =
match self.pipelines.get(&parent_pipeline_id) {
Some(pipeline) => pipeline.browsing_context_id,
None => return warn!(
let parent_browsing_context_id = match self.pipelines.get(&parent_pipeline_id) {
Some(pipeline) => pipeline.browsing_context_id,
None => {
return warn!(
"Script loaded url in iframe {} in closed parent pipeline {}.",
browsing_context_id,
parent_pipeline_id,
),
};
browsing_context_id, parent_pipeline_id,
)
},
};
let is_parent_private =
match self.browsing_contexts.get(&parent_browsing_context_id) {
Some(ctx) => ctx.is_private,
None => return warn!(
None => {
return warn!(
"Script loaded url in iframe {} in closed parent browsing context {}.",
browsing_context_id,
parent_browsing_context_id,
),
)
},
};
is_parent_private
};
@ -1820,10 +1841,12 @@ where
let (replace, window_size, is_visible) = {
let browsing_context = match self.browsing_contexts.get(&browsing_context_id) {
Some(ctx) => ctx,
None => return warn!(
"Script loaded url in iframe with closed browsing context {}.",
browsing_context_id,
),
None => {
return warn!(
"Script loaded url in iframe with closed browsing context {}.",
browsing_context_id,
)
},
};
let replace = if replace {
Some(NeedsToReload::No(browsing_context.pipeline_id))
@ -1876,19 +1899,22 @@ where
let load_data = LoadData::new(url.clone(), Some(parent_pipeline_id), None, None);
let (pipeline, is_private, is_visible) = {
let (script_sender, parent_browsing_context_id) =
match self.pipelines.get(&parent_pipeline_id) {
Some(pipeline) => (pipeline.event_loop.clone(), pipeline.browsing_context_id),
None => return warn!("Script loaded url in closed iframe {}.", parent_pipeline_id),
};
let (script_sender, parent_browsing_context_id) = match self
.pipelines
.get(&parent_pipeline_id)
{
Some(pipeline) => (pipeline.event_loop.clone(), pipeline.browsing_context_id),
None => return warn!("Script loaded url in closed iframe {}.", parent_pipeline_id),
};
let (is_parent_private, is_parent_visible) =
match self.browsing_contexts.get(&parent_browsing_context_id) {
Some(ctx) => (ctx.is_private, ctx.is_visible),
None => return warn!(
"New iframe {} loaded in closed parent browsing context {}.",
browsing_context_id,
parent_browsing_context_id,
),
None => {
return warn!(
"New iframe {} loaded in closed parent browsing context {}.",
browsing_context_id, parent_browsing_context_id,
)
},
};
let is_private = is_private || is_parent_private;
let pipeline = Pipeline::new(
@ -1923,9 +1949,11 @@ where
});
}
fn handle_script_new_auxiliary(&mut self,
load_info: AuxiliaryBrowsingContextLoadInfo,
layout_sender: IpcSender<LayoutControlMsg>) {
fn handle_script_new_auxiliary(
&mut self,
load_info: AuxiliaryBrowsingContextLoadInfo,
layout_sender: IpcSender<LayoutControlMsg>,
) {
let AuxiliaryBrowsingContextLoadInfo {
opener_pipeline_id,
new_top_level_browsing_context_id,
@ -1942,19 +1970,22 @@ where
let (script_sender, opener_browsing_context_id) =
match self.pipelines.get(&opener_pipeline_id) {
Some(pipeline) => (pipeline.event_loop.clone(), pipeline.browsing_context_id),
None => return warn!(
"Auxiliary loaded url in closed iframe {}.",
opener_pipeline_id
),
None => {
return warn!(
"Auxiliary loaded url in closed iframe {}.",
opener_pipeline_id
)
},
};
let (is_opener_private, is_opener_visible) =
match self.browsing_contexts.get(&opener_browsing_context_id) {
Some(ctx) => (ctx.is_private, ctx.is_visible),
None => return warn!(
"New auxiliary {} loaded in closed opener browsing context {}.",
new_browsing_context_id,
opener_browsing_context_id,
),
None => {
return warn!(
"New auxiliary {} loaded in closed opener browsing context {}.",
new_browsing_context_id, opener_browsing_context_id,
)
},
};
let pipeline = Pipeline::new(
new_pipeline_id,
@ -1966,7 +1997,7 @@ where
self.compositor_proxy.clone(),
url,
is_opener_visible,
load_data
load_data,
);
(pipeline, is_opener_private, is_opener_visible)
@ -1974,10 +2005,13 @@ where
assert!(!self.pipelines.contains_key(&new_pipeline_id));
self.pipelines.insert(new_pipeline_id, pipeline);
self.browsers.insert(new_top_level_browsing_context_id, Browser {
focused_browsing_context_id: new_browsing_context_id,
session_history: JointSessionHistory::new(),
});
self.browsers.insert(
new_top_level_browsing_context_id,
Browser {
focused_browsing_context_id: new_browsing_context_id,
session_history: JointSessionHistory::new(),
},
);
self.add_pending_change(SessionHistoryChange {
top_level_browsing_context_id: new_top_level_browsing_context_id,
browsing_context_id: new_browsing_context_id,
@ -2098,8 +2132,7 @@ where
// against future changes that might break things.
warn!(
"Pipeline {} loaded url in closed browsing context {}.",
source_id,
browsing_context_id,
source_id, browsing_context_id,
);
return None;
},
@ -2448,12 +2481,13 @@ where
// TODO: Save the sandbox state so it can be restored here.
let sandbox = IFrameSandboxState::IFrameUnsandboxed;
let (top_level_id,
old_pipeline_id,
parent_pipeline_id,
window_size,
is_private,
is_visible
let (
top_level_id,
old_pipeline_id,
parent_pipeline_id,
window_size,
is_private,
is_visible,
) = match self.browsing_contexts.get(&browsing_context_id) {
Some(ctx) => (
ctx.top_level_id,
@ -2651,18 +2685,19 @@ where
let event = CompositorEvent::KeyboardEvent(event);
let pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
Some(ctx) => ctx.pipeline_id,
None => return warn!(
"Got key event for nonexistent browsing context {}.",
browsing_context_id,
),
None => {
return warn!(
"Got key event for nonexistent browsing context {}.",
browsing_context_id,
)
},
};
let msg = ConstellationControlMsg::SendEvent(pipeline_id, event);
let result = match self.pipelines.get(&pipeline_id) {
Some(pipeline) => pipeline.event_loop.send(msg),
None => return debug!(
"Pipeline {:?} got key event after closure.",
pipeline_id
),
None => {
return debug!("Pipeline {:?} got key event after closure.", pipeline_id)
},
};
if let Err(e) = result {
self.handle_send_error(pipeline_id, e);
@ -2771,10 +2806,12 @@ where
Some(browser) => {
browser.focused_browsing_context_id = browsing_context_id;
},
None => return warn!(
"Browser {} for focus msg does not exist",
top_level_browsing_context_id
),
None => {
return warn!(
"Browser {} for focus msg does not exist",
top_level_browsing_context_id
)
},
};
// Focus parent iframes recursively
@ -2784,17 +2821,21 @@ where
fn focus_parent_pipeline(&mut self, browsing_context_id: BrowsingContextId) {
let parent_pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
Some(ctx) => ctx.parent_pipeline_id,
None => return warn!(
"Browsing context {:?} focus parent after closure.",
browsing_context_id
),
None => {
return warn!(
"Browsing context {:?} focus parent after closure.",
browsing_context_id
)
},
};
let parent_pipeline_id = match parent_pipeline_id {
Some(parent_id) => parent_id,
None => return debug!(
"Browsing context {:?} focus has no parent.",
browsing_context_id
),
None => {
return debug!(
"Browsing context {:?} focus has no parent.",
browsing_context_id
)
},
};
// Send a message to the parent of the provided browsing context (if it
@ -2864,7 +2905,12 @@ where
};
let parent_pipeline_id = match self.browsing_contexts.get(&browsing_context_id) {
Some(ctx) => ctx.parent_pipeline_id,
None => return warn!("Visibility change for closed browsing context {:?}.", pipeline_id),
None => {
return warn!(
"Visibility change for closed browsing context {:?}.",
pipeline_id
)
},
};
if let Some(parent_pipeline_id) = parent_pipeline_id {
@ -3294,7 +3340,7 @@ where
fn focused_browsing_context_is_descendant_of(
&self,
browsing_context_id: BrowsingContextId
browsing_context_id: BrowsingContextId,
) -> bool {
let focused_browsing_context_id = self
.active_browser_id
@ -3389,11 +3435,12 @@ where
// This is an existing browsing context.
None => match self.browsing_contexts.get(&change.browsing_context_id) {
Some(ctx) => ctx.parent_pipeline_id,
None => return warn!(
"Activated document {} after browsing context {} closure.",
change.new_pipeline_id,
change.browsing_context_id,
),
None => {
return warn!(
"Activated document {} after browsing context {} closure.",
change.new_pipeline_id, change.browsing_context_id,
)
},
},
};
if let Some(parent_pipeline_id) = parent_pipeline_id {
@ -3638,12 +3685,14 @@ where
new_size,
size_type,
));
let pipeline_ids = browsing_context.pipelines
let pipeline_ids = browsing_context
.pipelines
.iter()
.filter(|pipeline_id| **pipeline_id != pipeline.id);
for id in pipeline_ids {
if let Some(pipeline) = self.pipelines.get(&id) {
let _ = pipeline.event_loop
let _ = pipeline
.event_loop
.send(ConstellationControlMsg::ResizeInactive(
pipeline.id,
new_size,
@ -3757,11 +3806,12 @@ where
NeedsToReload::Yes(pipeline_id, load_data),
);
},
None => return warn!(
"Discarding pipeline {} after browser {} closure",
pipeline_id,
top_level_browsing_context_id,
),
None => {
return warn!(
"Discarding pipeline {} after browser {} closure",
pipeline_id, top_level_browsing_context_id,
)
},
};
self.close_pipeline(
pipeline_id,
@ -3844,8 +3894,10 @@ where
// Randomly close a pipeline -if --random-pipeline-closure-probability is set
fn maybe_close_random_pipeline(&mut self) {
match self.random_pipeline_closure {
Some((ref mut rng, probability)) => if probability <= rng.gen::<f32>() {
return;
Some((ref mut rng, probability)) => {
if probability <= rng.gen::<f32>() {
return;
}
},
_ => return,
};
@ -3881,7 +3933,8 @@ where
&mut self,
top_level_id: TopLevelBrowsingContextId,
) -> &mut JointSessionHistory {
&mut self.browsers
&mut self
.browsers
.entry(top_level_id)
// This shouldn't be necessary since `get_joint_session_history` is
// invoked for existing browsers but we need this to satisfy the

View file

@ -113,7 +113,9 @@ impl NetworkListener {
location_url: metadata.location_url.clone(),
headers: headers.clone().into_inner(),
referrer: metadata.referrer.clone(),
status_code: metadata.status.as_ref()
status_code: metadata
.status
.as_ref()
.map(|&(code, _)| code)
.unwrap_or(200),
});

View file

@ -240,10 +240,12 @@ impl Pipeline {
Err(e) => {
error!("Cast to ScriptToDevtoolsControlMsg failed ({}).", e)
},
Ok(message) => if let Err(e) =
devtools_chan.send(DevtoolsControlMsg::FromScript(message))
{
warn!("Sending to devtools failed ({:?})", e)
Ok(message) => {
if let Err(e) =
devtools_chan.send(DevtoolsControlMsg::FromScript(message))
{
warn!("Sending to devtools failed ({:?})", e)
}
},
},
),
@ -430,8 +432,7 @@ impl Pipeline {
/// Notify the script thread that this pipeline is visible.
pub fn notify_visibility(&self, is_visible: bool) {
let script_msg =
ConstellationControlMsg::ChangeFrameVisibilityStatus(self.id, is_visible);
let script_msg = ConstellationControlMsg::ChangeFrameVisibilityStatus(self.id, is_visible);
let compositor_msg = CompositorMsg::PipelineVisibilityChanged(self.id, is_visible);
let err = self.event_loop.send(script_msg);
if let Err(e) = err {

View file

@ -49,7 +49,8 @@ pub fn start_server(port: u16) -> Sender {
.name("debugger-websocket".to_owned())
.spawn(move || {
socket.listen(("127.0.0.1", port)).unwrap();
}).expect("Thread spawning failed");
})
.expect("Thread spawning failed");
while let Some(message) = receiver.recv() {
match message {
Message::ShutdownServer => {
@ -58,7 +59,8 @@ pub fn start_server(port: u16) -> Sender {
}
}
sender.shutdown().unwrap();
}).expect("Thread spawning failed");
})
.expect("Thread spawning failed");
Sender(sender)
}

View file

@ -126,7 +126,8 @@ impl Actor for ConsoleActor {
self.pipeline,
message_types,
chan,
)).unwrap();
))
.unwrap();
let messages = port
.recv()
.map_err(|_| ())?
@ -135,7 +136,8 @@ impl Actor for ConsoleActor {
let json_string = message.encode().unwrap();
let json = serde_json::from_str::<Value>(&json_string).unwrap();
json.as_object().unwrap().to_owned()
}).collect();
})
.collect();
let msg = GetCachedMessagesReply {
from: self.name(),
@ -196,7 +198,8 @@ impl Actor for ConsoleActor {
self.pipeline,
input.clone(),
chan,
)).unwrap();
))
.unwrap();
//TODO: extract conversion into protocol module or some other useful place
let result = match port.recv().map_err(|_| ())? {

View file

@ -42,7 +42,7 @@ impl Actor for DeviceActor {
value: SystemInfo {
apptype: "servo".to_string(),
platformVersion: "63.0".to_string(),
}
},
};
stream.write_json_packet(&msg);
ActorMessageStatus::Processed
@ -73,12 +73,11 @@ impl DeviceActor {
.into_iter()
.collect(),
),
)].into_iter()
)]
.into_iter()
.collect(),
),
}],
}
}
}

View file

@ -111,14 +111,16 @@ impl Actor for NodeActor {
.iter()
.map(|json_mod| {
serde_json::from_str(&serde_json::to_string(json_mod).unwrap()).unwrap()
}).collect();
})
.collect();
self.script_chan
.send(ModifyAttribute(
self.pipeline,
registry.actor_to_script(target.to_owned()),
modifications,
)).unwrap();
))
.unwrap();
let reply = ModifyAttributeReply { from: self.name() };
stream.write_json_packet(&reply);
ActorMessageStatus::Processed
@ -228,7 +230,8 @@ impl NodeInfoToProtocol for NodeInfo {
namespace: attr.namespace,
name: attr.name,
value: attr.value,
}).collect(),
})
.collect(),
pseudoClassLocks: vec![], //TODO get this data from script
@ -324,7 +327,8 @@ impl Actor for WalkerActor {
self.pipeline,
registry.actor_to_script(target.to_owned()),
tx,
)).unwrap();
))
.unwrap();
let children = rx.recv().unwrap().ok_or(())?;
let msg = ChildrenReply {
@ -334,7 +338,8 @@ impl Actor for WalkerActor {
.into_iter()
.map(|child| {
child.encode(registry, true, self.script_chan.clone(), self.pipeline)
}).collect(),
})
.collect(),
from: self.name(),
};
stream.write_json_packet(&msg);
@ -498,7 +503,8 @@ impl Actor for PageStyleActor {
self.pipeline,
registry.actor_to_script(target.to_owned()),
tx,
)).unwrap();
))
.unwrap();
let ComputedNodeLayout {
display,
position,

View file

@ -33,7 +33,7 @@ struct HttpRequest {
struct HttpResponse {
headers: Option<HeaderMap>,
status: Option<(StatusCode, String)>,
body: Option<Vec<u8>>
body: Option<Vec<u8>>,
}
pub struct NetworkEventActor {
@ -192,7 +192,10 @@ impl Actor for NetworkEventActor {
let value = &value.to_str().unwrap().to_string();
rawHeadersString = rawHeadersString + name.as_str() + ":" + &value + "\r\n";
headersSize += name.as_str().len() + value.len();
headers.push(Header { name: name.as_str().to_owned(), value: value.to_owned() });
headers.push(Header {
name: name.as_str().to_owned(),
value: value.to_owned(),
});
}
let msg = GetRequestHeadersReply {
from: self.name(),
@ -376,8 +379,13 @@ impl NetworkEventActor {
// TODO: Send the correct values for all these fields.
let hSizeOption = self.response.headers.as_ref().map(|headers| headers.len());
let hSize = hSizeOption.unwrap_or(0);
let (status_code, status_message) = self.response.status.as_ref()
.map_or((0, "".to_owned()), |(code, text)| (code.as_u16(), text.clone()));
let (status_code, status_message) = self
.response
.status
.as_ref()
.map_or((0, "".to_owned()), |(code, text)| {
(code.as_u16(), text.clone())
});
// TODO: Send the correct values for remoteAddress and remotePort and http_version.
ResponseStartMsg {
httpVersion: "HTTP/1.1".to_owned(),
@ -395,7 +403,7 @@ impl NetworkEventActor {
if let Some(ref headers) = self.response.headers {
mString = match headers.typed_get::<ContentType>() {
Some(ct) => ct.to_string(),
_ => "".to_owned()
_ => "".to_owned(),
};
}
// TODO: Set correct values when response's body is sent to the devtools in http_loader.
@ -436,10 +444,9 @@ impl NetworkEventActor {
}
pub fn request_headers(&self) -> RequestHeadersMsg {
let size = self.request
.headers
.iter()
.fold(0, |acc, (name, value)| acc + name.as_str().len() + value.len());
let size = self.request.headers.iter().fold(0, |acc, (name, value)| {
acc + name.as_str().len() + value.len()
});
RequestHeadersMsg {
headers: self.request.headers.len(),
headersSize: size,
@ -449,7 +456,7 @@ impl NetworkEventActor {
pub fn request_cookies(&self) -> RequestCookiesMsg {
let cookies_size = match self.request.headers.typed_get::<Cookie>() {
Some(ref cookie) => cookie.len(),
_ => 0
_ => 0,
};
RequestCookiesMsg {
cookies: cookies_size,

View file

@ -106,7 +106,8 @@ impl PerformanceActor {
vec![(
"type".to_owned(),
Value::String("canCurrentlyRecord".to_owned()),
)].into_iter()
)]
.into_iter()
.collect(),
),
response: Value::Object(
@ -117,7 +118,8 @@ impl PerformanceActor {
.into_iter()
.collect(),
),
)].into_iter()
)]
.into_iter()
.collect(),
),
}],

View file

@ -30,4 +30,3 @@ impl StyleSheetsActor {
StyleSheetsActor { name: name }
}
}

View file

@ -169,7 +169,8 @@ impl TimelineActor {
emitter.send(markers);
thread::sleep(Duration::from_millis(DEFAULT_TIMELINE_DATA_PULL_TIMEOUT));
}).expect("Thread spawning failed");
})
.expect("Thread spawning failed");
}
}
@ -195,7 +196,8 @@ impl Actor for TimelineActor {
self.pipeline,
self.marker_types.clone(),
tx,
)).unwrap();
))
.unwrap();
*self.stream.borrow_mut() = stream.try_clone().ok();
@ -248,7 +250,8 @@ impl Actor for TimelineActor {
.send(DropTimelineMarkers(
self.pipeline,
self.marker_types.clone(),
)).unwrap();
))
.unwrap();
if let Some(ref actor_name) = *self.framerate_actor.borrow() {
registry.drop_actor_later(actor_name.clone());

View file

@ -235,7 +235,17 @@ fn run_server(
let (pipeline, worker_id) = ids;
//TODO: move all this actor creation into a constructor method on BrowsingContextActor
let (target, console, emulation, inspector, timeline, profiler, performance, styleSheets, thread) = {
let (
target,
console,
emulation,
inspector,
timeline,
profiler,
performance,
styleSheets,
thread,
) = {
let console = ConsoleActor {
name: actors.new_name("console"),
script_chan: script_sender.clone(),
@ -347,7 +357,8 @@ fn run_server(
LogLevel::Warn => "warn",
LogLevel::Error => "error",
_ => "log",
}.to_owned(),
}
.to_owned(),
timeStamp: precise_time_ns(),
arguments: vec![console_message.message],
filename: console_message.filename,
@ -373,7 +384,12 @@ fn run_server(
Some(actors.find::<WorkerActor>(actor_name).console.clone())
} else {
let actor_name = (*actor_pipelines).get(&id)?;
Some(actors.find::<BrowsingContextActor>(actor_name).console.clone())
Some(
actors
.find::<BrowsingContextActor>(actor_name)
.console
.clone(),
)
}
}
@ -537,9 +553,11 @@ fn run_server(
sender_clone
.send(DevtoolsControlMsg::FromChrome(
ChromeToDevtoolsControlMsg::AddClient(stream.unwrap()),
)).unwrap();
))
.unwrap();
}
}).expect("Thread spawning failed");
})
.expect("Thread spawning failed");
while let Some(msg) = receiver.recv() {
match msg {

View file

@ -55,7 +55,8 @@ pub fn dom_struct(args: TokenStream, input: TokenStream) -> TokenStream {
&self.#ident
}
}
).into()
)
.into()
} else {
panic!("#[dom_struct] only applies to structs with named fields");
}

View file

@ -76,9 +76,9 @@ fn expand_dom_object(input: syn::DeriveInput) -> quote::Tokens {
}));
let mut generics = input.generics.clone();
generics
.params
.push(parse_quote!(__T: crate::dom::bindings::reflector::DomObject));
generics.params.push(parse_quote!(
__T: crate::dom::bindings::reflector::DomObject
));
let (impl_generics, _, where_clause) = generics.split_for_impl();

View file

@ -254,7 +254,8 @@ impl Font {
TEXT_SHAPING_PERFORMANCE_COUNTER
.fetch_add((end_time - start_time) as usize, Ordering::Relaxed);
Arc::new(glyphs)
}).clone();
})
.clone();
self.shaper = shaper;
result
}
@ -450,7 +451,8 @@ impl FontGroup {
iter::once(FontFamilyDescriptor::default())
.chain(fallback_font_families(codepoint).into_iter().map(|family| {
FontFamilyDescriptor::new(FontFamilyName::from(family), FontSearchScope::Local)
})).filter_map(|family| font_context.font(&self.descriptor, &family))
}))
.filter_map(|family| font_context.font(&self.descriptor, &family))
.find(predicate)
}
}

View file

@ -434,7 +434,8 @@ impl FontCache {
FontSearchScope::Local => {
self.find_font_in_local_family(&template_descriptor, &family_descriptor.name)
},
}.map(|t| self.get_font_template_info(t))
}
.map(|t| self.get_font_template_info(t))
}
}
@ -474,7 +475,8 @@ impl FontCacheThread {
cache.refresh_local_families();
cache.run();
}).expect("Thread spawning failed");
})
.expect("Thread spawning failed");
FontCacheThread { chan: chan }
}
@ -490,7 +492,8 @@ impl FontCacheThread {
LowercaseString::new(&family.name),
sources,
sender,
)).unwrap();
))
.unwrap();
}
pub fn exit(&self) {
@ -538,7 +541,8 @@ impl FontSource for FontCacheThread {
template_descriptor,
family_descriptor,
response_chan,
)).expect("failed to send message to font cache thread");
))
.expect("failed to send message to font cache thread");
let reply = response_port.recv();

View file

@ -133,7 +133,8 @@ impl<S: FontSource> FontContext<S> {
.and_then(|template_info| {
self.create_font(template_info, font_descriptor.to_owned())
.ok()
}).map(|font| Rc::new(RefCell::new(font)));
})
.map(|font| Rc::new(RefCell::new(font)));
self.font_cache.insert(cache_key, font.clone());
font

View file

@ -127,7 +127,11 @@ struct FontList {
impl FontList {
fn new() -> FontList {
// Possible paths containing the font mapping xml file.
let paths = ["/etc/fonts.xml", "/system/etc/system_fonts.xml", "/package/etc/fonts.xml"];
let paths = [
"/etc/fonts.xml",
"/system/etc/system_fonts.xml",
"/package/etc/fonts.xml",
];
// Try to load and parse paths until one of them success.
let mut result = None;
@ -213,7 +217,10 @@ impl FontList {
let alternatives = [
("sans-serif", "Roboto-Regular.ttf"),
("Droid Sans", "DroidSans.ttf"),
("Lomino", "/system/etc/ml/kali/Fonts/Lomino/Medium/LominoUI_Md.ttf"),
(
"Lomino",
"/system/etc/ml/kali/Fonts/Lomino/Medium/LominoUI_Md.ttf",
),
];
alternatives
@ -225,7 +232,8 @@ impl FontList {
filename: item.1.into(),
weight: None,
}],
}).collect()
})
.collect()
}
// All Android fonts are located in /system/fonts
@ -348,7 +356,8 @@ impl FontList {
.map(|f| Font {
filename: f.clone(),
weight: None,
}).collect();
})
.collect();
if !fonts.is_empty() {
out.push(FontFamily {

View file

@ -216,7 +216,8 @@ impl FontHandleMethods for FontHandle {
}
} else {
FontStretchKeyword::Normal
}.compute();
}
.compute();
FontStretch(NonNegative(percentage))
}

View file

@ -25,7 +25,8 @@ impl fmt::Debug for FontTemplateData {
.field(
"bytes",
&self.bytes.as_ref().map(|b| format!("[{} bytes]", b.len())),
).field("identifier", &self.identifier)
)
.field("identifier", &self.identifier)
.finish()
}
}

View file

@ -236,8 +236,7 @@ impl FontHandleMethods for FontHandle {
let count: CFIndex = 1;
let result = unsafe {
self
.ctfont
self.ctfont
.get_glyphs_for_characters(&characters[0], &mut glyphs[0], count)
};

View file

@ -51,7 +51,8 @@ impl fmt::Debug for FontTemplateData {
.font_data
.as_ref()
.map(|bytes| format!("[{} bytes]", bytes.len())),
).finish()
)
.finish()
}
}
@ -111,7 +112,8 @@ impl FontTemplateData {
.expect("No URL for Core Text font!")
.get_string()
.to_string(),
).expect("Couldn't parse Core Text font URL!")
)
.expect("Couldn't parse Core Text font URL!")
.as_url()
.to_file_path()
.expect("Core Text font didn't name a path!");

View file

@ -187,7 +187,8 @@ impl FontInfo {
8 => FontStretchKeyword::ExtraExpanded,
9 => FontStretchKeyword::UltraExpanded,
_ => return Err(()),
}.compute(),
}
.compute(),
));
let style = if italic_bool {
@ -224,7 +225,8 @@ impl FontInfo {
FontStretch::Expanded => FontStretchKeyword::Expanded,
FontStretch::ExtraExpanded => FontStretchKeyword::ExtraExpanded,
FontStretch::UltraExpanded => FontStretchKeyword::UltraExpanded,
}.compute(),
}
.compute(),
));
Ok(FontInfo {

View file

@ -24,7 +24,8 @@ impl fmt::Debug for FontTemplateData {
.bytes
.as_ref()
.map(|bytes| format!("[{} bytes]", bytes.len())),
).field("identifier", &self.identifier)
)
.field("identifier", &self.identifier)
.finish()
}
}

View file

@ -119,7 +119,8 @@ fn font_family(names: Vec<&str>) -> FontFamily {
name: Atom::from(name),
syntax: FamilyNameSyntax::Quoted,
})
}).collect();
})
.collect();
FontFamily(FontFamilyList::new(names.into_boxed_slice()))
}

View file

@ -41,7 +41,8 @@ fn test_font_template_descriptor() {
let mut template = FontTemplate::new(
Atom::from(filename),
Some(file.bytes().map(|b| b.unwrap()).collect()),
).unwrap();
)
.unwrap();
let context = FontContextHandle::new();

View file

@ -226,9 +226,9 @@ impl<'a> DetailedGlyphStore {
/* TODO: don't actually assert this until asserts are compiled
in/out based on severity, debug/release, etc. This assertion
would wreck the complexity of the lookup.
See Rust Issue #3647, #2228, #3627 for related information.
do self.detail_lookup.borrow |arr| {
assert !arr.contains(entry)
}
@ -541,7 +541,8 @@ impl<'a> GlyphStore {
data_for_glyphs[i].advance,
data_for_glyphs[i].offset,
)
}).collect();
})
.collect();
self.has_detailed_glyphs = true;
self.detail_store

View file

@ -380,7 +380,8 @@ impl<'a> TextRun {
);
remaining -= slice_advance;
slice_index
}).sum()
})
.sum()
}
/// Returns an iterator that will iterate over all slices of glyphs that represent natural

View file

@ -89,7 +89,10 @@ pub fn update_animation_state<E>(
},
};
debug!("update_animation_state({:?}): {:?}", still_running, running_animation);
debug!(
"update_animation_state({:?}): {:?}",
still_running, running_animation
);
if still_running {
animations_still_running.push(running_animation);
@ -97,11 +100,13 @@ pub fn update_animation_state<E>(
}
if let Animation::Transition(node, _, ref frame) = running_animation {
script_chan.send(ConstellationControlMsg::TransitionEnd(
node.to_untrusted_node_address(),
frame.property_animation.property_name().into(),
frame.duration,
)).unwrap();
script_chan
.send(ConstellationControlMsg::TransitionEnd(
node.to_untrusted_node_address(),
frame.property_animation.property_name().into(),
frame.duration,
))
.unwrap();
}
expired_animations
@ -150,7 +155,8 @@ pub fn update_animation_state<E>(
.send(ConstellationMsg::ChangeRunningAnimationsState(
pipeline_id,
animation_state,
)).unwrap();
))
.unwrap();
}
/// Recalculates style for a set of animations. This does *not* run with the DOM

View file

@ -1334,7 +1334,8 @@ impl BlockFlow {
self.fragment.style.writing_mode,
inline_size_for_float_placement,
block_size + self.fragment.margin.block_start_end(),
).convert(
)
.convert(
self.fragment.style.writing_mode,
self.base.floats.writing_mode,
),
@ -1361,7 +1362,8 @@ impl BlockFlow {
self.base.floats.writing_mode,
self.base.writing_mode,
container_size,
).start;
)
.start;
let margin_offset = LogicalPoint::new(
self.base.writing_mode,
Au(0),
@ -2626,7 +2628,8 @@ impl Flow for BlockFlow {
.early_absolute_position_info
.relative_containing_block_mode,
CoordinateSystem::Own,
).translate(&stacking_context_position.to_vector()),
)
.translate(&stacking_context_position.to_vector()),
);
}

View file

@ -185,7 +185,8 @@ impl InlineBlockSplit {
predecessors: mem::replace(
fragment_accumulator,
InlineFragmentsAccumulator::from_inline_node(node, style_context),
).to_intermediate_inline_fragments::<ConcreteThreadSafeLayoutNode>(style_context),
)
.to_intermediate_inline_fragments::<ConcreteThreadSafeLayoutNode>(style_context),
flow: flow,
};
@ -402,7 +403,7 @@ impl<'a, ConcreteThreadSafeLayoutNode: ThreadSafeLayoutNode>
&self.layout_context,
));
SpecificFragmentInfo::Image(image_info)
}
},
Some(LayoutNodeType::Element(LayoutElementType::HTMLMediaElement)) => {
let data = node.media_data().unwrap();
SpecificFragmentInfo::Media(Box::new(MediaFragmentInfo::new(data)))

View file

@ -590,7 +590,8 @@ impl ClippingRegion {
rect: complex.rect.translate(delta),
radii: complex.radii,
mode: complex.mode,
}).collect(),
})
.collect(),
}
}

View file

@ -922,7 +922,8 @@ impl Flow for FlexFlow {
.base
.flags
.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED)
}).map(|(index, flow)| FlexItem::new(index, flow))
})
.map(|(index, flow)| FlexItem::new(index, flow))
.collect();
items.sort_by_key(|item| item.order);

View file

@ -416,23 +416,28 @@ impl ImageFragmentInfo {
layout_context: &LayoutContext,
) -> ImageFragmentInfo {
// First use any image data present in the element...
let image_or_metadata = node.image_data().and_then(|(image, metadata)| {
match (image, metadata) {
let image_or_metadata = node
.image_data()
.and_then(|(image, metadata)| match (image, metadata) {
(Some(image), _) => Some(ImageOrMetadata::Image(image)),
(None, Some(metadata)) => Some(ImageOrMetadata::Metadata(metadata)),
_ => None,
}
}).or_else(|| url.and_then(|url| {
// Otherwise query the image cache for anything known about the associated source URL.
layout_context.get_or_request_image_or_meta(
node.opaque(),
url,
UsePlaceholder::Yes
).map(|result| match result {
ImageOrMetadataAvailable::ImageAvailable(i, _) => ImageOrMetadata::Image(i),
ImageOrMetadataAvailable::MetadataAvailable(m) => ImageOrMetadata::Metadata(m),
})
}));
.or_else(|| {
url.and_then(|url| {
// Otherwise query the image cache for anything known about the associated source URL.
layout_context
.get_or_request_image_or_meta(node.opaque(), url, UsePlaceholder::Yes)
.map(|result| match result {
ImageOrMetadataAvailable::ImageAvailable(i, _) => {
ImageOrMetadata::Image(i)
},
ImageOrMetadataAvailable::MetadataAvailable(m) => {
ImageOrMetadata::Metadata(m)
},
})
})
});
let current_pixel_density = density.unwrap_or(1f64);
@ -452,15 +457,13 @@ impl ImageFragmentInfo {
}),
)
},
Some(ImageOrMetadata::Metadata(m)) => {
(
None,
Some(ImageMetadata {
height: (m.height as f64 / current_pixel_density) as u32,
width: (m.width as f64 / current_pixel_density) as u32,
}),
)
},
Some(ImageOrMetadata::Metadata(m)) => (
None,
Some(ImageMetadata {
height: (m.height as f64 / current_pixel_density) as u32,
width: (m.width as f64 / current_pixel_density) as u32,
}),
),
None => (None, None),
};
@ -1012,7 +1015,7 @@ impl Fragment {
} else {
Au(0)
}
}
},
SpecificFragmentInfo::Media(ref info) => {
if let Some((_, width, _)) = info.current_frame {
Au::from_px(width as i32)
@ -1042,7 +1045,7 @@ impl Fragment {
} else {
Au(0)
}
}
},
SpecificFragmentInfo::Media(ref info) => {
if let Some((_, _, height)) = info.current_frame {
Au::from_px(height as i32)
@ -1174,17 +1177,21 @@ impl Fragment {
(_, Ordering::Equal) => (first_isize, first_bsize),
// When both rectangles grow (smaller than min sizes),
// Choose the larger one;
(Ordering::Greater, Ordering::Greater) => if first_isize > second_isize {
(first_isize, first_bsize)
} else {
(second_isize, second_bsize)
(Ordering::Greater, Ordering::Greater) => {
if first_isize > second_isize {
(first_isize, first_bsize)
} else {
(second_isize, second_bsize)
}
},
// When both rectangles shrink (larger than max sizes),
// Choose the smaller one;
(Ordering::Less, Ordering::Less) => if first_isize > second_isize {
(second_isize, second_bsize)
} else {
(first_isize, first_bsize)
(Ordering::Less, Ordering::Less) => {
if first_isize > second_isize {
(second_isize, second_bsize)
} else {
(first_isize, first_bsize)
}
},
// It does not matter which we choose here, because both sizes
// will be clamped to constraint;
@ -3173,7 +3180,8 @@ impl Fragment {
perspective_origin
.vertical
.to_used_value(stacking_relative_border_box.size.height),
).to_layout();
)
.to_layout();
let pre_transform = LayoutTransform::create_translation(
perspective_origin.x,

View file

@ -316,7 +316,8 @@ impl LineBreaker {
.map(|fragment| match fragment.specific {
SpecificFragmentInfo::ScannedText(ref info) => info.run.bidi_level,
_ => para_level,
}).collect();
})
.collect();
let mut lines = mem::replace(&mut self.lines, Vec::new());
@ -336,7 +337,8 @@ impl LineBreaker {
let start = FragmentIndex(run.start as isize);
let len = FragmentIndex(run.len() as isize);
(Range::new(start, len), levels[run.start])
}).collect(),
})
.collect(),
);
}
}
@ -1719,7 +1721,8 @@ impl Flow for InlineFlow {
debug_assert!(first_fragment_index < self.fragments.fragments.len());
let first_fragment = &self.fragments.fragments[first_fragment_index];
let padding_box_origin = (first_fragment.border_box -
first_fragment.style.logical_border_width()).start;
first_fragment.style.logical_border_width())
.start;
containing_block_positions.push(
padding_box_origin.to_physical(self.base.writing_mode, container_size),
);
@ -1733,7 +1736,8 @@ impl Flow for InlineFlow {
debug_assert!(first_fragment_index < self.fragments.fragments.len());
let first_fragment = &self.fragments.fragments[first_fragment_index];
let padding_box_origin = (first_fragment.border_box -
first_fragment.style.logical_border_width()).start;
first_fragment.style.logical_border_width())
.start;
containing_block_positions.push(
padding_box_origin.to_physical(self.base.writing_mode, container_size),
);
@ -1878,7 +1882,8 @@ impl Flow for InlineFlow {
relative_containing_block_size,
relative_containing_block_mode,
CoordinateSystem::Own,
).translate(&stacking_context_position.to_vector()),
)
.translate(&stacking_context_position.to_vector()),
)
}
}

View file

@ -257,7 +257,8 @@ impl Flow for ListItemFlow {
.early_absolute_position_info
.relative_containing_block_mode,
CoordinateSystem::Own,
).translate(&stacking_context_position.to_vector()),
)
.translate(&stacking_context_position.to_vector()),
);
}
}

View file

@ -505,10 +505,12 @@ pub fn style_length(
) -> MaybeAuto {
match container_size {
Some(length) => MaybeAuto::from_style(style_length, length),
None => if let LengthOrPercentageOrAuto::Length(length) = style_length {
MaybeAuto::Specified(Au::from(length))
} else {
MaybeAuto::Auto
None => {
if let LengthOrPercentageOrAuto::Length(length) = style_length {
MaybeAuto::Specified(Au::from(length))
} else {
MaybeAuto::Auto
}
},
}
}
@ -580,19 +582,23 @@ impl SizeConstraint {
) -> SizeConstraint {
let mut min_size = match container_size {
Some(container_size) => min_size.to_used_value(container_size),
None => if let LengthOrPercentage::Length(length) = min_size {
Au::from(length)
} else {
Au(0)
None => {
if let LengthOrPercentage::Length(length) = min_size {
Au::from(length)
} else {
Au(0)
}
},
};
let mut max_size = match container_size {
Some(container_size) => max_size.to_used_value(container_size),
None => if let LengthOrPercentageOrNone::Length(length) = max_size {
Some(Au::from(length))
} else {
None
None => {
if let LengthOrPercentageOrNone::Length(length) = max_size {
Some(Au::from(length))
} else {
None
}
},
};
// Make sure max size is not smaller than min size.

View file

@ -164,7 +164,8 @@ impl Flow for MulticolFlow {
LogicalSize::from_physical(
self.block_flow.base.writing_mode,
ctx.shared_context().viewport_size(),
).block
)
.block
}
},
});

View file

@ -603,7 +603,7 @@ impl FragmentBorderBoxIterator for ParentOffsetBorderBoxIterator {
// cause this assertion to fail sometimes, so it's
// commented out for now.
/*assert!(node.flags.contains(FIRST_FRAGMENT_OF_ELEMENT),
"First fragment of inline node found wasn't its first fragment!");*/
"First fragment of inline node found wasn't its first fragment!");*/
self.node_offset_box = Some(NodeOffsetBoxInfo {
offset: border_box.origin,
@ -840,12 +840,11 @@ where
let applies = true;
fn used_value_for_position_property<N: LayoutNode>(
layout_el: <N::ConcreteThreadSafeLayoutNode as ThreadSafeLayoutNode>::ConcreteThreadSafeLayoutElement,
layout_root: &mut Flow,
requested_node: N,
longhand_id: LonghandId,
) -> String
{
layout_el: <N::ConcreteThreadSafeLayoutNode as ThreadSafeLayoutNode>::ConcreteThreadSafeLayoutElement,
layout_root: &mut Flow,
requested_node: N,
longhand_id: LonghandId,
) -> String {
let maybe_data = layout_el.borrow_layout_data();
let position = maybe_data.map_or(Point2D::zero(), |data| {
match (*data).flow_construction_result {

View file

@ -197,7 +197,8 @@ impl Flow for TableCellFlow {
let specified_inline_size = MaybeAuto::from_style(
self.block_flow.fragment.style().content_inline_size(),
Au(0),
).specified_or_zero();
)
.specified_or_zero();
if self
.block_flow
.base

View file

@ -143,7 +143,8 @@ impl TableWrapperFlow {
);
total_guess = &total_guess + &guess;
guess
}).collect();
})
.collect();
// Assign inline sizes.
let selection =
@ -385,7 +386,8 @@ impl Flow for TableWrapperFlow {
size: column_intrinsic_inline_size.minimum_length,
percentage: column_intrinsic_inline_size.percentage,
},
).collect::<Vec<_>>();
)
.collect::<Vec<_>>();
// Our inline-size was set to the inline-size of the containing block by the flow's parent.
// Now compute the real value.
@ -753,17 +755,17 @@ impl ExcessInlineSizeDistributionInfo {
if !column_intrinsic_inline_size.constrained &&
column_intrinsic_inline_size.percentage == 0.0
{
self.preferred_inline_size_of_nonconstrained_columns_with_no_percentage =
self.preferred_inline_size_of_nonconstrained_columns_with_no_percentage +
column_intrinsic_inline_size.preferred;
self.preferred_inline_size_of_nonconstrained_columns_with_no_percentage = self
.preferred_inline_size_of_nonconstrained_columns_with_no_percentage +
column_intrinsic_inline_size.preferred;
self.count_of_nonconstrained_columns_with_no_percentage += 1
}
if column_intrinsic_inline_size.constrained &&
column_intrinsic_inline_size.percentage == 0.0
{
self.preferred_inline_size_of_constrained_columns_with_no_percentage =
self.preferred_inline_size_of_constrained_columns_with_no_percentage +
column_intrinsic_inline_size.preferred
self.preferred_inline_size_of_constrained_columns_with_no_percentage = self
.preferred_inline_size_of_constrained_columns_with_no_percentage +
column_intrinsic_inline_size.preferred
}
self.total_percentage += column_intrinsic_inline_size.percentage;
self.column_count += 1

View file

@ -687,9 +687,7 @@ impl<'le> ::selectors::Element for ServoLayoutElement<'le> {
type Impl = SelectorImpl;
fn opaque(&self) -> ::selectors::OpaqueElement {
::selectors::OpaqueElement::new(unsafe {
&*(self.as_node().opaque().0 as *const ())
})
::selectors::OpaqueElement::new(unsafe { &*(self.as_node().opaque().0 as *const ()) })
}
fn parent_element(&self) -> Option<ServoLayoutElement<'le>> {
@ -1272,9 +1270,7 @@ impl<'le> ::selectors::Element for ServoThreadSafeLayoutElement<'le> {
type Impl = SelectorImpl;
fn opaque(&self) -> ::selectors::OpaqueElement {
::selectors::OpaqueElement::new(unsafe {
&*(self.as_node().opaque().0 as *const ())
})
::selectors::OpaqueElement::new(unsafe { &*(self.as_node().opaque().0 as *const ()) })
}
fn parent_element(&self) -> Option<Self> {

View file

@ -334,7 +334,8 @@ impl LayoutThreadFactory for LayoutThread {
if let Some(content_process_shutdown_chan) = content_process_shutdown_chan {
let _ = content_process_shutdown_chan.send(());
}
}).expect("Thread spawning failed");
})
.expect("Thread spawning failed");
}
}
@ -507,8 +508,7 @@ impl LayoutThread {
// Ask the router to proxy IPC messages from the font cache thread to the layout thread.
let (ipc_font_cache_sender, ipc_font_cache_receiver) = ipc::channel().unwrap();
let font_cache_receiver =
route_ipc_receiver_to_new_servo_receiver(ipc_font_cache_receiver);
let font_cache_receiver = route_ipc_receiver_to_new_servo_receiver(ipc_font_cache_receiver);
LayoutThread {
id: id,
@ -769,7 +769,8 @@ impl LayoutThread {
.filter_map(|name| {
let id = PropertyId::parse_enabled_for_all_content(&*name).ok()?;
Some((name.clone(), id))
}).filter(|&(_, ref id)| !id.is_shorthand())
})
.filter(|&(_, ref id)| !id.is_shorthand())
.collect();
let registered_painter = RegisteredPainterImpl {
name: name.clone(),
@ -1249,7 +1250,8 @@ impl LayoutThread {
.send(ConstellationMsg::ViewportConstrained(
self.id,
constraints.clone(),
)).unwrap();
))
.unwrap();
}
if had_used_viewport_units {
if let Some(mut data) = element.mutate_data() {

View file

@ -88,7 +88,8 @@ fn malloc_size_of_derive(s: synstructure::Structure) -> quote::Tokens {
fn test_struct() {
let source = syn::parse_str(
"struct Foo<T> { bar: Bar, baz: T, #[ignore_malloc_size_of = \"\"] z: Arc<T> }",
).unwrap();
)
.unwrap();
let source = synstructure::Structure::new(&source);
let expanded = malloc_size_of_derive(source).to_string();

View file

@ -236,10 +236,9 @@ fn evict_one_cookie(is_secure_cookie: bool, cookies: &mut Vec<Cookie>) -> bool {
fn get_oldest_accessed(is_secure_cookie: bool, cookies: &mut Vec<Cookie>) -> Option<(usize, Tm)> {
let mut oldest_accessed: Option<(usize, Tm)> = None;
for (i, c) in cookies.iter().enumerate() {
if (c.cookie.secure().unwrap_or(false) == is_secure_cookie) &&
oldest_accessed
.as_ref()
.map_or(true, |a| c.last_access < a.1)
if (c.cookie.secure().unwrap_or(false) == is_secure_cookie) && oldest_accessed
.as_ref()
.map_or(true, |a| c.last_access < a.1)
{
oldest_accessed = Some((i, c.last_access));
}

View file

@ -254,10 +254,11 @@ pub fn main_fetch(
Response::network_error(NetworkError::Internal("Non-http scheme".into()))
} else if request.use_cors_preflight ||
(request.unsafe_request &&
(!is_cors_safelisted_method(&request.method) ||
request.headers.iter().any(|(name, value)| {
!is_cors_safelisted_request_header(&name, &value)
}))) {
(!is_cors_safelisted_method(&request.method) || request
.headers
.iter()
.any(|(name, value)| !is_cors_safelisted_request_header(&name, &value))))
{
// Substep 1.
request.response_tainting = ResponseTainting::CorsTainting;
// Substep 2.
@ -372,11 +373,10 @@ pub fn main_fetch(
// in the previous step.
let not_network_error = !response_is_network_error && !internal_response.is_network_error();
if not_network_error &&
(is_null_body_status(&internal_response.status) ||
match request.method {
Method::HEAD | Method::CONNECT => true,
_ => false,
}) {
(is_null_body_status(&internal_response.status) || match request.method {
Method::HEAD | Method::CONNECT => true,
_ => false,
}) {
// when Fetch is used only asynchronously, we will need to make sure
// that nothing tries to write to the body at this point
let mut body = internal_response.body.lock().unwrap();
@ -791,13 +791,12 @@ fn should_be_blocked_due_to_mime_type(
};
// Step 2-3
destination.is_script_like() &&
match mime_type.type_() {
mime::AUDIO | mime::VIDEO | mime::IMAGE => true,
mime::TEXT if mime_type.subtype() == mime::CSV => true,
// Step 4
_ => false,
}
destination.is_script_like() && match mime_type.type_() {
mime::AUDIO | mime::VIDEO | mime::IMAGE => true,
mime::TEXT if mime_type.subtype() == mime::CSV => true,
// Step 4
_ => false,
}
}
/// <https://fetch.spec.whatwg.org/#block-bad-port>

View file

@ -506,12 +506,10 @@ pub fn http_fetch(
}
// Substep 2
if response.is_none() &&
request.is_subresource_request() &&
match request.origin {
Origin::Origin(ref origin) => *origin == request.url().origin(),
_ => false,
} {
if response.is_none() && request.is_subresource_request() && match request.origin {
Origin::Origin(ref origin) => *origin == request.url().origin(),
_ => false,
} {
// TODO (handle foreign fetch unimplemented)
}
@ -1044,11 +1042,10 @@ fn http_network_or_cache_fetch(
}
}
// Substep 4
if revalidating_flag &&
forward_response
.status
.as_ref()
.map_or(false, |s| s.0 == StatusCode::NOT_MODIFIED)
if revalidating_flag && forward_response
.status
.as_ref()
.map_or(false, |s| s.0 == StatusCode::NOT_MODIFIED)
{
if let Ok(mut http_cache) = context.state.http_cache.write() {
response = http_cache.refresh(&http_request, forward_response.clone(), done_chan);
@ -1384,11 +1381,10 @@ fn cors_preflight_fetch(
let response = http_network_or_cache_fetch(&mut preflight, false, false, &mut None, context);
// Step 6
if cors_check(&request, &response).is_ok() &&
response
.status
.as_ref()
.map_or(false, |(status, _)| status.is_success())
if cors_check(&request, &response).is_ok() && response
.status
.as_ref()
.map_or(false, |(status, _)| status.is_success())
{
// Substep 1, 2
let mut methods = if response

View file

@ -404,10 +404,9 @@ impl Mp4Matcher {
}
let mp4 = [0x6D, 0x70, 0x34];
data[8..].starts_with(&mp4) ||
data[16..box_size]
.chunks(4)
.any(|chunk| chunk.starts_with(&mp4))
data[8..].starts_with(&mp4) || data[16..box_size]
.chunks(4)
.any(|chunk| chunk.starts_with(&mp4))
}
}
impl MIMEChecker for Mp4Matcher {

View file

@ -221,19 +221,25 @@ fn test_cors_preflight_fetch() {
let handler = move |request: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
if request.method() == Method::OPTIONS && state.clone().fetch_add(1, Ordering::SeqCst) == 0
{
assert!(request
.headers()
.contains_key(header::ACCESS_CONTROL_REQUEST_METHOD));
assert!(!request
.headers()
.contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS));
assert!(!request
.headers()
.get(header::REFERER)
.unwrap()
.to_str()
.unwrap()
.contains("a.html"));
assert!(
request
.headers()
.contains_key(header::ACCESS_CONTROL_REQUEST_METHOD)
);
assert!(
!request
.headers()
.contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS)
);
assert!(
!request
.headers()
.get(header::REFERER)
.unwrap()
.to_str()
.unwrap()
.contains("a.html")
);
response
.headers_mut()
.typed_insert(AccessControlAllowOrigin::ANY);
@ -279,12 +285,16 @@ fn test_cors_preflight_cache_fetch() {
let handler = move |request: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
if request.method() == Method::OPTIONS && state.clone().fetch_add(1, Ordering::SeqCst) == 0
{
assert!(request
.headers()
.contains_key(header::ACCESS_CONTROL_REQUEST_METHOD));
assert!(!request
.headers()
.contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS));
assert!(
request
.headers()
.contains_key(header::ACCESS_CONTROL_REQUEST_METHOD)
);
assert!(
!request
.headers()
.contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS)
);
response
.headers_mut()
.typed_insert(AccessControlAllowOrigin::ANY);
@ -344,12 +354,16 @@ fn test_cors_preflight_fetch_network_error() {
let handler = move |request: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
if request.method() == Method::OPTIONS && state.clone().fetch_add(1, Ordering::SeqCst) == 0
{
assert!(request
.headers()
.contains_key(header::ACCESS_CONTROL_REQUEST_METHOD));
assert!(!request
.headers()
.contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS));
assert!(
request
.headers()
.contains_key(header::ACCESS_CONTROL_REQUEST_METHOD)
);
assert!(
!request
.headers()
.contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS)
);
response
.headers_mut()
.typed_insert(AccessControlAllowOrigin::ANY);
@ -408,9 +422,11 @@ fn test_fetch_response_is_basic_filtered() {
let headers = fetch_response.headers;
assert!(!headers.contains_key(header::SET_COOKIE));
assert!(headers
.get(HeaderName::from_static("set-cookie2"))
.is_none());
assert!(
headers
.get(HeaderName::from_static("set-cookie2"))
.is_none()
);
}
#[test]
@ -480,9 +496,11 @@ fn test_fetch_response_is_cors_filtered() {
assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN));
assert!(!headers.contains_key(header::SET_COOKIE));
assert!(headers
.get(HeaderName::from_static("set-cookie2"))
.is_none());
assert!(
headers
.get(HeaderName::from_static("set-cookie2"))
.is_none()
);
}
#[test]

View file

@ -103,12 +103,14 @@ fn test_push_entry_with_0_max_age_evicts_entry_from_list() {
let mut entries_map = HashMap::new();
entries_map.insert(
"mozilla.org".to_owned(),
vec![HstsEntry::new(
"mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
Some(500000u64),
)
.unwrap()],
vec![
HstsEntry::new(
"mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
Some(500000u64),
)
.unwrap(),
],
);
let mut list = HstsList {
entries_map: entries_map,
@ -179,12 +181,14 @@ fn test_push_entry_to_hsts_list_should_not_create_duplicate_entry() {
let mut entries_map = HashMap::new();
entries_map.insert(
"mozilla.org".to_owned(),
vec![HstsEntry::new(
"mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
None,
)
.unwrap()],
vec![
HstsEntry::new(
"mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
None,
)
.unwrap(),
],
);
let mut list = HstsList {
entries_map: entries_map,
@ -283,12 +287,14 @@ fn test_hsts_list_with_exact_domain_entry_is_is_host_secure() {
let mut entries_map = HashMap::new();
entries_map.insert(
"mozilla.org".to_owned(),
vec![HstsEntry::new(
"mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
None,
)
.unwrap()],
vec![
HstsEntry::new(
"mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
None,
)
.unwrap(),
],
);
let hsts_list = HstsList {
@ -317,12 +323,14 @@ fn test_hsts_list_with_subdomain_when_include_subdomains_is_false_is_not_is_host
let mut entries_map = HashMap::new();
entries_map.insert(
"mozilla.org".to_owned(),
vec![HstsEntry::new(
"mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
None,
)
.unwrap()],
vec![
HstsEntry::new(
"mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
None,
)
.unwrap(),
],
);
let hsts_list = HstsList {
entries_map: entries_map,

View file

@ -142,13 +142,15 @@ fn test_check_default_headers_loaded_in_every_request() {
..RequestInit::default()
});
let response = fetch(&mut request, None);
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
// Testing for method.POST
let mut post_headers = headers.clone();
@ -170,13 +172,15 @@ fn test_check_default_headers_loaded_in_every_request() {
..RequestInit::default()
});
let response = fetch(&mut request, None);
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
let _ = server.close();
}
@ -202,13 +206,15 @@ fn test_load_when_request_is_not_get_or_head_and_there_is_no_body_content_length
..RequestInit::default()
});
let response = fetch(&mut request, None);
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
let _ = server.close();
}
@ -237,13 +243,15 @@ fn test_request_and_response_data_with_network_messages() {
});
let (devtools_chan, devtools_port) = channel();
let response = fetch(&mut request, Some(devtools_chan));
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
let _ = server.close();
@ -336,13 +344,15 @@ fn test_request_and_response_message_from_devtool_without_pipeline_id() {
});
let (devtools_chan, devtools_port) = channel();
let response = fetch(&mut request, Some(devtools_chan));
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
let _ = server.close();
@ -580,13 +590,15 @@ fn test_load_doesnt_add_host_to_sts_list_when_url_is_http_even_if_sts_headers_ar
let _ = server.close();
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
assert_eq!(
context
.state
@ -627,13 +639,15 @@ fn test_load_sets_cookies_in_the_resource_manager_when_it_get_set_cookie_header_
let _ = server.close();
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
assert_cookie_for_domain(
&context.state.cookie_jar,
@ -680,13 +694,15 @@ fn test_load_sets_requests_cookies_header_for_url_by_getting_cookies_from_the_re
let _ = server.close();
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
}
#[test]
@ -727,13 +743,15 @@ fn test_load_sends_cookie_if_nonhttp() {
let _ = server.close();
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
}
#[test]
@ -765,13 +783,15 @@ fn test_cookie_set_with_httponly_should_not_be_available_using_getcookiesforurl(
let _ = server.close();
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
assert_cookie_for_domain(
&context.state.cookie_jar,
@ -779,9 +799,11 @@ fn test_cookie_set_with_httponly_should_not_be_available_using_getcookiesforurl(
Some("mozillaIs=theBest"),
);
let mut cookie_jar = context.state.cookie_jar.write().unwrap();
assert!(cookie_jar
.cookies_for_url(&url, CookieSource::NonHTTP)
.is_none());
assert!(
cookie_jar
.cookies_for_url(&url, CookieSource::NonHTTP)
.is_none()
);
}
#[test]
@ -813,13 +835,15 @@ fn test_when_cookie_received_marked_secure_is_ignored_for_http() {
let _ = server.close();
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
assert_cookie_for_domain(&context.state.cookie_jar, url.as_str(), None);
}
@ -850,13 +874,15 @@ fn test_load_sets_content_length_to_length_of_request_body() {
let _ = server.close();
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
}
#[test]
@ -890,13 +916,15 @@ fn test_load_uses_explicit_accept_from_headers_in_load_data() {
let _ = server.close();
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
}
#[test]
@ -927,13 +955,15 @@ fn test_load_sets_default_accept_to_html_xhtml_xml_and_then_anything_else() {
let _ = server.close();
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
}
#[test]
@ -967,13 +997,15 @@ fn test_load_uses_explicit_accept_encoding_from_load_data_headers() {
let _ = server.close();
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
}
#[test]
@ -1004,13 +1036,15 @@ fn test_load_sets_default_accept_encoding_to_gzip_and_deflate() {
let _ = server.close();
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
}
#[test]
@ -1338,13 +1372,15 @@ fn test_if_auth_creds_not_in_url_but_in_cache_it_sets_it() {
let _ = server.close();
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
}
#[test]
@ -1401,13 +1437,15 @@ fn test_origin_set() {
..RequestInit::default()
});
let response = fetch(&mut request, None);
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
let origin_url = ServoUrl::parse("http://example.com").unwrap();
// XXX: Not sure about the Some(80) here. origin_url.origin() returns 80 for the port but origin_url returns None.
@ -1429,13 +1467,15 @@ fn test_origin_set() {
*origin_header_clone.lock().unwrap() = Some(origin.clone());
let response = fetch(&mut request, None);
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
// Test Origin header is not set on method Head
let mut request = Request::from_init(RequestInit {
@ -1448,13 +1488,15 @@ fn test_origin_set() {
*origin_header_clone.lock().unwrap() = None;
let response = fetch(&mut request, None);
assert!(response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success());
assert!(
response
.internal_response
.unwrap()
.status
.unwrap()
.0
.is_success()
);
let _ = server.close();
}

View file

@ -21,7 +21,10 @@ pub fn get_rect(pixels: &[u8], size: Size2D<u32>, rect: Rect<u32>) -> Cow<[u8]>
return Cow::Borrowed(&pixels[start..start + area * 4]);
}
let mut data = Vec::with_capacity(area * 4);
for row in pixels[first_row_start..].chunks(row_length).take(rect.size.height as usize) {
for row in pixels[first_row_start..]
.chunks(row_length)
.take(rect.size.height as usize)
{
data.extend_from_slice(&row[first_column_start..][..rect.size.width as usize * 4]);
}
data.into()

View file

@ -43,7 +43,8 @@ impl Profiler {
if chan.send(ProfilerMsg::Print).is_err() {
break;
}
}).expect("Thread spawning failed");
})
.expect("Thread spawning failed");
}
// Always spawn the memory profiler. If there is no timer thread it won't receive regular
@ -53,7 +54,8 @@ impl Profiler {
.spawn(move || {
let mut mem_profiler = Profiler::new(port);
mem_profiler.start();
}).expect("Thread spawning failed");
})
.expect("Thread spawning failed");
let mem_profiler_chan = ProfilerChan(chan);
@ -623,7 +625,8 @@ mod system_reporter {
let seg_re = Regex::new(
r"^[:xdigit:]+-[:xdigit:]+ (....) [:xdigit:]+ [:xdigit:]+:[:xdigit:]+ \d+ +(.*)",
).unwrap();
)
.unwrap();
let rss_re = Regex::new(r"^Rss: +(\d+) kB").unwrap();
// We record each segment's resident size.

View file

@ -184,7 +184,8 @@ impl Profiler {
let trace = file_path.as_ref().and_then(|p| TraceDump::new(p).ok());
let mut profiler = Profiler::new(port, trace, Some(outputoption));
profiler.start();
}).expect("Thread spawning failed");
})
.expect("Thread spawning failed");
// decide if we need to spawn the timer thread
match option {
&OutputOptions::FileName(_) | &OutputOptions::DB(_, _, _, _) => {
@ -200,7 +201,8 @@ impl Profiler {
if chan.send(ProfilerMsg::Print).is_err() {
break;
}
}).expect("Thread spawning failed");
})
.expect("Thread spawning failed");
},
}
},
@ -214,7 +216,8 @@ impl Profiler {
let trace = file_path.as_ref().and_then(|p| TraceDump::new(p).ok());
let mut profiler = Profiler::new(port, trace, None);
profiler.start();
}).expect("Thread spawning failed");
})
.expect("Thread spawning failed");
} else {
// No-op to handle messages when the time profiler is not printing:
thread::Builder::new()
@ -228,7 +231,8 @@ impl Profiler {
},
_ => {},
}
}).expect("Thread spawning failed");
})
.expect("Thread spawning failed");
}
},
}
@ -281,7 +285,8 @@ impl Profiler {
start_time = end_time;
start_energy = end_energy;
}
}).expect("Thread spawning failed");
})
.expect("Thread spawning failed");
}
profiler_chan
@ -323,9 +328,11 @@ impl Profiler {
let ms = (t.1 - t.0) as f64 / 1000000f64;
self.find_or_insert(k, ms);
},
ProfilerMsg::Print => if let Some(ProfilerMsg::Time(..)) = self.last_msg {
// only print if more data has arrived since the last printout
self.print_buckets();
ProfilerMsg::Print => {
if let Some(ProfilerMsg::Time(..)) = self.last_msg {
// only print if more data has arrived since the last printout
self.print_buckets();
}
},
ProfilerMsg::Get(k, sender) => {
let vec_option = self.buckets.get(&k);
@ -381,7 +388,8 @@ impl Profiler {
file,
"_category_\t_incremental?_\t_iframe?_\t_url_\t_mean (ms)_\t\
_median (ms)_\t_min (ms)_\t_max (ms)_\t_events_\n"
).unwrap();
)
.unwrap();
for (&(ref category, ref meta), ref mut data) in &mut self.buckets {
data.sort_by(|a, b| a.partial_cmp(b).expect("No NaN values in profiles"));
let data_len = data.len();
@ -397,7 +405,8 @@ impl Profiler {
min,
max,
data_len
).unwrap();
)
.unwrap();
}
}
},
@ -417,7 +426,8 @@ impl Profiler {
" _min (ms)_",
" _max (ms)_",
" _events_"
).unwrap();
)
.unwrap();
for (&(ref category, ref meta), ref mut data) in &mut self.buckets {
data.sort_by(|a, b| a.partial_cmp(b).expect("No NaN values in profiles"));
let data_len = data.len();
@ -433,7 +443,8 @@ impl Profiler {
min,
max,
data_len
).unwrap();
)
.unwrap();
}
}
writeln!(&mut lock, "").unwrap();
@ -473,8 +484,9 @@ impl Profiler {
measurement.add_tag("host", meta.url.as_str());
};
tokio::run(client.write_one(measurement, None)
.map_err(|e| warn!("Could not write measurement to profiler db: {:?}", e)));
tokio::run(client.write_one(measurement, None).map_err(|e| {
warn!("Could not write measurement to profiler db: {:?}", e)
}));
}
}
},

View file

@ -54,14 +54,12 @@ where
Ok((ipc_sender, profiled_ipc_receiver))
}
pub struct IpcBytesReceiver
{
pub struct IpcBytesReceiver {
ipc_bytes_receiver: ipc::IpcBytesReceiver,
time_profile_chan: ProfilerChan,
}
impl IpcBytesReceiver
{
impl IpcBytesReceiver {
pub fn recv(&self) -> Result<Vec<u8>, bincode::Error> {
time::profile(
ProfilerCategory::IpcBytesReceiver,
@ -74,8 +72,7 @@ impl IpcBytesReceiver
pub fn bytes_channel(
time_profile_chan: ProfilerChan,
) -> Result<(ipc::IpcBytesSender, IpcBytesReceiver), Error>
{
) -> Result<(ipc::IpcBytesSender, IpcBytesReceiver), Error> {
let (ipc_bytes_sender, ipc_bytes_receiver) = ipc::bytes_channel()?;
let profiled_ipc_bytes_receiver = IpcBytesReceiver {
ipc_bytes_receiver,

View file

@ -174,7 +174,8 @@ impl Reporter {
self.0
.send(ReporterRequest {
reports_channel: reports_chan,
}).unwrap()
})
.unwrap()
}
}

View file

@ -60,7 +60,8 @@ fn trylock_works() {
thread::spawn(move || {
let lock = m2.try_lock();
assert!(lock.is_err());
}).join()
})
.join()
.unwrap();
let _lock3 = m.try_lock().unwrap();
}
@ -84,7 +85,8 @@ fn poison_works() {
let _answer = Answer(lock2);
println!("Intentionally panicking.");
panic!("What the answer to my lifetimes dilemma is?");
}).join();
})
.join();
assert!(result.is_err());
let r = m.lock().err().unwrap().into_inner();
assert_eq!(*r.borrow(), 42);

View file

@ -175,8 +175,9 @@ fn run_form_data_algorithm(
} else {
""
};
let mime: Mime = mime_str.parse().map_err(
|_| Error::Type("Inappropriate MIME-type for Body".to_string()))?;
let mime: Mime = mime_str
.parse()
.map_err(|_| Error::Type("Inappropriate MIME-type for Body".to_string()))?;
// TODO
// ... Parser for Mime(TopLevel::Multipart, SubLevel::FormData, _)

View file

@ -69,7 +69,8 @@ fn main() {
write!(
&mut phf,
"pub static MAP: phf::Map<&'static [u8], unsafe fn(*mut JSContext, HandleObject)> = "
).unwrap();
)
.unwrap();
map.build(&mut phf).unwrap();
write!(&mut phf, ";\n").unwrap();
}

View file

@ -172,7 +172,8 @@ pub fn handle_get_layout(
paddingLeft: String::from(computed_style.PaddingLeft()),
width: width,
height: height,
})).unwrap();
}))
.unwrap();
}
fn determine_auto_margins(window: &Window, node: &Node) -> AutoMargins {

View file

@ -153,7 +153,8 @@ impl DocumentLoader {
.send(CoreResourceMsg::Fetch(
request,
FetchChannels::ResponseMsg(fetch_target, Some(cancel_receiver)),
)).unwrap();
))
.unwrap();
}
/// Mark an in-progress network request complete.

View file

@ -37,17 +37,20 @@ impl AnalyserNode {
context: &BaseAudioContext,
options: &AnalyserOptions,
) -> Fallible<(AnalyserNode, IpcReceiver<Block>)> {
let node_options = options.parent
.unwrap_or(2, ChannelCountMode::Max,
ChannelInterpretation::Speakers);
let node_options =
options
.parent
.unwrap_or(2, ChannelCountMode::Max, ChannelInterpretation::Speakers);
if options.fftSize > 32768 || options.fftSize < 32 ||
(options.fftSize & (options.fftSize - 1) != 0) {
return Err(Error::IndexSize)
if options.fftSize > 32768 ||
options.fftSize < 32 ||
(options.fftSize & (options.fftSize - 1) != 0)
{
return Err(Error::IndexSize);
}
if *options.maxDecibels <= *options.minDecibels {
return Err(Error::IndexSize)
return Err(Error::IndexSize);
}
if *options.smoothingTimeConstant < 0. || *options.smoothingTimeConstant > 1. {
@ -67,14 +70,19 @@ impl AnalyserNode {
1, // outputs
)?;
let engine = AnalysisEngine::new(options.fftSize as usize,
*options.smoothingTimeConstant,
*options.minDecibels, *options.maxDecibels);
Ok((AnalyserNode {
node,
engine: DomRefCell::new(engine)
}, rcv))
let engine = AnalysisEngine::new(
options.fftSize as usize,
*options.smoothingTimeConstant,
*options.minDecibels,
*options.maxDecibels,
);
Ok((
AnalyserNode {
node,
engine: DomRefCell::new(engine),
},
rcv,
))
}
#[allow(unrooted_must_root)]
@ -89,13 +97,19 @@ impl AnalyserNode {
let canceller = window.task_canceller(TaskSourceName::DOMManipulation);
let this = Trusted::new(&*object);
ROUTER.add_route(recv.to_opaque(), Box::new(move |block| {
let this = this.clone();
let _ = source.queue_with_canceller(task!(append_analysis_block: move || {
ROUTER.add_route(
recv.to_opaque(),
Box::new(move |block| {
let this = this.clone();
let _ = source.queue_with_canceller(
task!(append_analysis_block: move || {
let this = this.root();
this.push_block(block.to().unwrap())
}), &canceller);
}));
}),
&canceller,
);
}),
);
Ok(object)
}
@ -130,7 +144,6 @@ impl AnalyserNodeMethods for AnalyserNode {
// run whilst we're writing to it
let dest = unsafe { array.as_mut_slice() };
self.engine.borrow_mut().fill_byte_frequency_data(dest);
}
#[allow(unsafe_code)]
@ -140,7 +153,6 @@ impl AnalyserNodeMethods for AnalyserNode {
// run whilst we're writing to it
let dest = unsafe { array.as_mut_slice() };
self.engine.borrow().fill_time_domain_data(dest);
}
#[allow(unsafe_code)]
@ -150,14 +162,12 @@ impl AnalyserNodeMethods for AnalyserNode {
// run whilst we're writing to it
let dest = unsafe { array.as_mut_slice() };
self.engine.borrow().fill_byte_time_domain_data(dest);
}
/// https://webaudio.github.io/web-audio-api/#dom-analysernode-fftsize
fn SetFftSize(&self, value: u32) -> Fallible<()> {
if value > 32768 || value < 32 ||
(value & (value - 1) != 0) {
return Err(Error::IndexSize)
if value > 32768 || value < 32 || (value & (value - 1) != 0) {
return Err(Error::IndexSize);
}
self.engine.borrow_mut().set_fft_size(value as usize);
Ok(())
@ -181,7 +191,7 @@ impl AnalyserNodeMethods for AnalyserNode {
/// https://webaudio.github.io/web-audio-api/#dom-analysernode-mindecibels
fn SetMinDecibels(&self, value: Finite<f64>) -> Fallible<()> {
if *value >= self.engine.borrow().get_max_decibels() {
return Err(Error::IndexSize)
return Err(Error::IndexSize);
}
self.engine.borrow_mut().set_min_decibels(*value);
Ok(())
@ -195,7 +205,7 @@ impl AnalyserNodeMethods for AnalyserNode {
/// https://webaudio.github.io/web-audio-api/#dom-analysernode-maxdecibels
fn SetMaxDecibels(&self, value: Finite<f64>) -> Fallible<()> {
if *value <= self.engine.borrow().get_min_decibels() {
return Err(Error::IndexSize)
return Err(Error::IndexSize);
}
self.engine.borrow_mut().set_max_decibels(*value);
Ok(())
@ -209,10 +219,9 @@ impl AnalyserNodeMethods for AnalyserNode {
/// https://webaudio.github.io/web-audio-api/#dom-analysernode-smoothingtimeconstant
fn SetSmoothingTimeConstant(&self, value: Finite<f64>) -> Fallible<()> {
if *value < 0. || *value > 1. {
return Err(Error::IndexSize)
return Err(Error::IndexSize);
}
self.engine.borrow_mut().set_smoothing_constant(*value);
Ok(())
}
}

View file

@ -110,10 +110,8 @@ impl AudioBuffer {
// Initialize the underlying channels data with initial data provided by
// the user or silence otherwise.
fn set_initial_data(&self, initial_data: Option<&[Vec<f32>]>) {
let mut channels = ServoMediaAudioBuffer::new(
self.number_of_channels as u8,
self.length as usize,
);
let mut channels =
ServoMediaAudioBuffer::new(self.number_of_channels as u8, self.length as usize);
for channel in 0..self.number_of_channels {
channels.buffers[channel as usize] = match initial_data {
Some(data) => data[channel as usize].clone(),
@ -143,7 +141,8 @@ impl AudioBuffer {
cx,
CreateWith::Slice(&shared_channels.buffers[i]),
array.handle_mut(),
).is_err()
)
.is_err()
{
return false;
}
@ -159,10 +158,8 @@ impl AudioBuffer {
// https://webaudio.github.io/web-audio-api/#acquire-the-content
#[allow(unsafe_code)]
fn acquire_contents(&self) -> Option<ServoMediaAudioBuffer> {
let mut result = ServoMediaAudioBuffer::new(
self.number_of_channels as u8,
self.length as usize,
);
let mut result =
ServoMediaAudioBuffer::new(self.number_of_channels as u8, self.length as usize);
let cx = self.global().get_cx();
for (i, channel) in self.js_channels.borrow_mut().iter().enumerate() {
// Step 1.
@ -203,7 +200,7 @@ impl AudioBuffer {
*self.shared_channels.borrow_mut() = channels;
}
}
return self.shared_channels.borrow()
return self.shared_channels.borrow();
}
}
@ -324,7 +321,8 @@ impl AudioBufferMethods for AudioBuffer {
let js_channel_data = unsafe { js_channel.as_mut_slice() };
let (_, js_channel_data) = js_channel_data.split_at_mut(start_in_channel as usize);
unsafe {
js_channel_data[0..bytes_to_copy].copy_from_slice(&source.as_slice()[0..bytes_to_copy])
js_channel_data[0..bytes_to_copy]
.copy_from_slice(&source.as_slice()[0..bytes_to_copy])
};
} else {
return Err(Error::IndexSize);

View file

@ -348,7 +348,11 @@ impl BaseAudioContextMethods for BaseAudioContext {
/// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbiquadfilter
fn CreateBiquadFilter(&self) -> Fallible<DomRoot<BiquadFilterNode>> {
BiquadFilterNode::new(&self.global().as_window(), &self, &BiquadFilterOptions::empty())
BiquadFilterNode::new(
&self.global().as_window(),
&self,
&BiquadFilterOptions::empty(),
)
}
/// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createchannelmerger
@ -432,10 +436,12 @@ impl BaseAudioContextMethods for BaseAudioContext {
.lock()
.unwrap()
.resize(channel_count as usize, Vec::new());
}).progress(move |buffer, channel| {
})
.progress(move |buffer, channel| {
let mut decoded_audio = decoded_audio_.lock().unwrap();
decoded_audio[(channel - 1) as usize].extend_from_slice((*buffer).as_ref());
}).eos(move || {
})
.eos(move || {
let _ = task_source.queue_with_canceller(
task!(audio_decode_eos: move || {
let this = this.root();
@ -461,7 +467,8 @@ impl BaseAudioContextMethods for BaseAudioContext {
}),
&canceller,
);
}).error(move |error| {
})
.error(move |error| {
let _ = task_source_.queue_with_canceller(
task!(audio_decode_eos: move || {
let this = this_.root();
@ -478,7 +485,8 @@ impl BaseAudioContextMethods for BaseAudioContext {
}),
&canceller_,
);
}).build();
})
.build();
self.audio_context_impl
.decode_audio_data(audio_data, callbacks);
} else {

View file

@ -94,7 +94,8 @@ pub fn entry_global() -> DomRoot<GlobalScope> {
.rev()
.find(|entry| entry.kind == StackEntryKind::Entry)
.map(|entry| DomRoot::from_ref(&*entry.global))
}).unwrap()
})
.unwrap()
}
/// RAII struct that pushes and pops entries from the script settings stack.

View file

@ -457,7 +457,7 @@ unsafe_no_jsmanaged_fields!(AudioBuffer);
unsafe_no_jsmanaged_fields!(AudioContext<Backend>);
unsafe_no_jsmanaged_fields!(NodeId);
unsafe_no_jsmanaged_fields!(AnalysisEngine, DistanceModel, PanningModel, ParamType);
unsafe_no_jsmanaged_fields!(Player<Error=ServoMediaError>);
unsafe_no_jsmanaged_fields!(Player<Error = ServoMediaError>);
unsafe_no_jsmanaged_fields!(Mutex<MediaFrameRenderer>);
unsafe_no_jsmanaged_fields!(RenderApiSender);

View file

@ -178,7 +178,7 @@ pub fn get_array_index_from_id(_cx: *mut JSContext, id: HandleId) -> Option<u32>
if s > 'a' && s < 'z' {
return -1;
}
let i = 0;
let str = AtomToLinearString(JSID_TO_ATOM(id));
return if StringIsArray(str, &mut i) != 0 { i } else { -1 }

View file

@ -39,9 +39,10 @@ impl BiquadFilterNode {
context: &BaseAudioContext,
options: &BiquadFilterOptions,
) -> Fallible<BiquadFilterNode> {
let node_options = options.parent
.unwrap_or(2, ChannelCountMode::Max,
ChannelInterpretation::Speakers);
let node_options =
options
.parent
.unwrap_or(2, ChannelCountMode::Max, ChannelInterpretation::Speakers);
let filter = Cell::new(options.type_);
let options = options.into();
let node = AudioNode::new_inherited(
@ -57,9 +58,9 @@ impl BiquadFilterNode {
node.node_id(),
ParamType::Gain,
AutomationRate::A_rate,
options.gain, // default value
f32::MIN, // min value
f32::MAX, // max value
options.gain, // default value
f32::MIN, // min value
f32::MAX, // max value
);
let q = AudioParam::new(
window,
@ -67,9 +68,9 @@ impl BiquadFilterNode {
node.node_id(),
ParamType::Q,
AutomationRate::A_rate,
options.q, // default value
f32::MIN, // min value
f32::MAX, // max value
options.q, // default value
f32::MIN, // min value
f32::MAX, // max value
);
let frequency = AudioParam::new(
window,
@ -77,9 +78,9 @@ impl BiquadFilterNode {
node.node_id(),
ParamType::Frequency,
AutomationRate::A_rate,
options.frequency, // default value
f32::MIN, // min value
f32::MAX, // max value
options.frequency, // default value
f32::MIN, // min value
f32::MAX, // max value
);
let detune = AudioParam::new(
window,
@ -87,9 +88,9 @@ impl BiquadFilterNode {
node.node_id(),
ParamType::Detune,
AutomationRate::A_rate,
options.detune, // default value
f32::MIN, // min value
f32::MAX, // max value
options.detune, // default value
f32::MIN, // min value
f32::MAX, // max value
);
Ok(BiquadFilterNode {
node,
@ -108,7 +109,11 @@ impl BiquadFilterNode {
options: &BiquadFilterOptions,
) -> Fallible<DomRoot<BiquadFilterNode>> {
let node = BiquadFilterNode::new_inherited(window, context, options)?;
Ok(reflect_dom_object(Box::new(node), window, BiquadFilterNodeBinding::Wrap))
Ok(reflect_dom_object(
Box::new(node),
window,
BiquadFilterNodeBinding::Wrap,
))
}
pub fn Constructor(
@ -149,10 +154,9 @@ impl BiquadFilterNodeMethods for BiquadFilterNode {
// https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-type
fn SetType(&self, filter: BiquadFilterType) {
self.filter.set(filter);
self.node
.message(AudioNodeMessage::BiquadFilterNode(
BiquadFilterNodeMessage::SetFilterType(filter.into()),
));
self.node.message(AudioNodeMessage::BiquadFilterNode(
BiquadFilterNodeMessage::SetFilterType(filter.into()),
));
}
}
@ -163,7 +167,7 @@ impl<'a> From<&'a BiquadFilterOptions> for BiquadFilterNodeOptions {
q: *options.Q,
frequency: *options.frequency,
detune: *options.detune,
filter: options.type_.into()
filter: options.type_.into(),
}
}
}

View file

@ -334,7 +334,8 @@ where
single,
child_type,
sender,
)).unwrap();
))
.unwrap();
return p;
}
@ -694,7 +695,8 @@ impl PermissionAlgorithm for Bluetooth {
device_id.clone(),
BluetoothScanfilterSequence::new(scan_filters),
sender,
)).unwrap();
))
.unwrap();
match receiver.recv().unwrap() {
Ok(true) => (),

View file

@ -152,7 +152,8 @@ impl BluetoothDevice {
.send(BluetoothRequest::IsRepresentedDeviceNull(
self.Id().to_string(),
sender,
)).unwrap();
))
.unwrap();
receiver.recv().unwrap()
}
@ -242,7 +243,8 @@ impl BluetoothDevice {
.send(BluetoothRequest::GATTServerDisconnect(
String::from(self.Id()),
sender,
)).unwrap();
))
.unwrap();
receiver.recv().unwrap().map_err(Error::from)
}
}
@ -286,7 +288,8 @@ impl BluetoothDeviceMethods for BluetoothDevice {
.send(BluetoothRequest::WatchAdvertisements(
String::from(self.Id()),
sender,
)).unwrap();
))
.unwrap();
return p;
}

View file

@ -216,7 +216,8 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris
self.get_instance_id(),
vec,
sender,
)).unwrap();
))
.unwrap();
return p;
}
@ -253,7 +254,8 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris
self.get_instance_id(),
true,
sender,
)).unwrap();
))
.unwrap();
return p;
}
@ -272,7 +274,8 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris
self.get_instance_id(),
false,
sender,
)).unwrap();
))
.unwrap();
return p;
}

View file

@ -166,7 +166,8 @@ impl BluetoothRemoteGATTDescriptorMethods for BluetoothRemoteGATTDescriptor {
self.get_instance_id(),
vec,
sender,
)).unwrap();
))
.unwrap();
return p;
}
}

View file

@ -87,7 +87,8 @@ impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer {
.send(BluetoothRequest::GATTServerConnect(
String::from(self.Device().Id()),
sender,
)).unwrap();
))
.unwrap();
// Step 5: return promise.
return p;
}

View file

@ -266,7 +266,7 @@ impl CanvasRenderingContext2D {
CanvasImageSource::HTMLCanvasElement(canvas) => canvas.origin_is_clean(),
CanvasImageSource::HTMLImageElement(image) => {
image.same_origin(GlobalScope::entry().origin())
}
},
CanvasImageSource::CSSStyleValue(_) => true,
}
}
@ -403,8 +403,7 @@ impl CanvasRenderingContext2D {
dh: Option<f64>,
) -> ErrorResult {
debug!("Fetching image {}.", url);
let (mut image_data, image_size) =
self.fetch_image_data(url).ok_or(Error::InvalidState)?;
let (mut image_data, image_size) = self.fetch_image_data(url).ok_or(Error::InvalidState)?;
pixels::premultiply_inplace(&mut image_data);
let image_size = image_size.to_f64();
@ -558,7 +557,10 @@ impl CanvasRenderingContext2D {
// FIXME(nox): This is probably wrong when this is a context for an
// offscreen canvas.
let canvas_size = self.canvas.as_ref().map_or(Size2D::zero(), |c| c.get_size());
let canvas_size = self
.canvas
.as_ref()
.map_or(Size2D::zero(), |c| c.get_size());
assert!(Rect::from_size(canvas_size).contains_rect(&rect));
let (sender, receiver) = ipc::bytes_channel().unwrap();
@ -1144,7 +1146,10 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
let (origin, size) = adjust_size_sign(Point2D::new(sx, sy), Size2D::new(sw, sh));
// FIXME(nox): This is probably wrong when this is a context for an
// offscreen canvas.
let canvas_size = self.canvas.as_ref().map_or(Size2D::zero(), |c| c.get_size());
let canvas_size = self
.canvas
.as_ref()
.map_or(Size2D::zero(), |c| c.get_size());
let read_rect = match pixels::clip(origin, size, canvas_size) {
Some(rect) => rect,
None => {
@ -1153,12 +1158,25 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
},
};
ImageData::new(&self.global(), size.width, size.height, Some(self.get_rect(read_rect)))
ImageData::new(
&self.global(),
size.width,
size.height,
Some(self.get_rect(read_rect)),
)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata
fn PutImageData(&self, imagedata: &ImageData, dx: i32, dy: i32) {
self.PutImageData_(imagedata, dx, dy, 0, 0, imagedata.Width() as i32, imagedata.Height() as i32)
self.PutImageData_(
imagedata,
dx,
dy,
0,
0,
imagedata.Width() as i32,
imagedata.Height() as i32,
)
}
// https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata
@ -1176,7 +1194,6 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
// FIXME(nox): There are many arithmetic operations here that can
// overflow or underflow, this should probably be audited.
let imagedata_size = Size2D::new(imagedata.Width(), imagedata.Height());
if imagedata_size.area() == 0 {
return;
@ -1190,7 +1207,10 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
// FIXME(nox): This is probably wrong when this is a context for an
// offscreen canvas.
let canvas_size = self.canvas.as_ref().map_or(Size2D::zero(), |c| c.get_size());
let canvas_size = self
.canvas
.as_ref()
.map_or(Size2D::zero(), |c| c.get_size());
// Steps 3-6.
let (src_origin, src_size) = adjust_size_sign(
@ -1214,9 +1234,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
// Step 7.
let (sender, receiver) = ipc::bytes_channel().unwrap();
let pixels = unsafe {
&imagedata.get_rect(Rect::new(src_rect.origin, dst_rect.size))
};
let pixels = unsafe { &imagedata.get_rect(Rect::new(src_rect.origin, dst_rect.size)) };
self.send_canvas_2d_msg(Canvas2dMsg::PutImageData(dst_rect, receiver));
sender.send(pixels).unwrap();
self.mark_as_dirty();

View file

@ -157,7 +157,8 @@ impl CSSStyleOwner {
.style_stylesheet()
.contents
.url_data
.read()).clone(),
.read())
.clone(),
}
}
}

View file

@ -82,14 +82,13 @@ impl CSSSupportsRule {
None,
);
let enabled = {
let namespaces =
self
.cssconditionrule
.parent_stylesheet()
.style_stylesheet()
.contents
.namespaces
.read();
let namespaces = self
.cssconditionrule
.parent_stylesheet()
.style_stylesheet()
.contents
.namespaces
.read();
cond.eval(&context, &namespaces)
};
let mut guard = self.cssconditionrule.shared_lock().write();

View file

@ -97,7 +97,8 @@ impl CustomElementRegistry {
// Step 4-5
definition.local_name == *local_name &&
(definition.name == *local_name || Some(&definition.name) == is)
}).cloned()
})
.cloned()
}
pub fn lookup_definition_by_constructor(

View file

@ -318,7 +318,8 @@ impl DedicatedWorkerGlobalScope {
Box::new(SimpleWorkerErrorHandler::new(worker)),
pipeline_id,
TaskSourceName::DOMManipulation,
)).unwrap();
))
.unwrap();
return;
},
Ok((metadata, bytes)) => (metadata, bytes),
@ -391,7 +392,8 @@ impl DedicatedWorkerGlobalScope {
parent_sender,
CommonScriptMsg::CollectReports,
);
}).expect("Thread spawning failed");
})
.expect("Thread spawning failed");
}
pub fn script_chan(&self) -> Box<ScriptChan + Send> {
@ -495,7 +497,8 @@ impl DedicatedWorkerGlobalScope {
task,
Some(pipeline_id),
TaskSourceName::DOMManipulation,
)).unwrap();
))
.unwrap();
}
}
@ -526,7 +529,8 @@ impl DedicatedWorkerGlobalScopeMethods for DedicatedWorkerGlobalScope {
task,
Some(pipeline_id),
TaskSourceName::DOMManipulation,
)).unwrap();
))
.unwrap();
Ok(())
}

View file

@ -539,7 +539,8 @@ impl Document {
);
}),
self.window.upcast(),
).unwrap();
)
.unwrap();
}
} else {
self.window().suspend();
@ -1904,7 +1905,8 @@ impl Document {
}
}),
self.window.upcast(),
).unwrap();
)
.unwrap();
// Step 8.
let document = Trusted::new(self);
@ -1938,7 +1940,8 @@ impl Document {
);
}),
self.window.upcast(),
).unwrap();
)
.unwrap();
}
// Step 9.
@ -2780,14 +2783,16 @@ impl Document {
owner
.upcast::<Node>()
.is_before(sheet_in_doc.owner.upcast())
}).cloned();
})
.cloned();
self.window()
.layout_chan()
.send(Msg::AddStylesheet(
sheet.clone(),
insertion_point.as_ref().map(|s| s.sheet.clone()),
)).unwrap();
))
.unwrap();
let sheet = StyleSheetInDocument {
sheet,
@ -3621,7 +3626,8 @@ impl DocumentMethods for Document {
.child_elements()
.find(|node| {
node.namespace() == &ns!(svg) && node.local_name() == &local_name!("title")
}).map(DomRoot::upcast::<Node>)
})
.map(DomRoot::upcast::<Node>)
} else {
// Step 2.
root.upcast::<Node>()
@ -3726,7 +3732,8 @@ impl DocumentMethods for Document {
HTMLElementTypeId::HTMLFrameSetElement,
)) => true,
_ => false,
}).map(|node| DomRoot::downcast(node).unwrap())
})
.map(|node| DomRoot::downcast(node).unwrap())
})
}
@ -3947,16 +3954,18 @@ impl DocumentMethods for Document {
return Err(Error::Security);
}
let cookies = if let Some(cookie) = cookie_rs::Cookie::parse(cookie.to_string()).ok().map(Serde) {
vec![cookie]
} else {
vec![]
};
let cookies =
if let Some(cookie) = cookie_rs::Cookie::parse(cookie.to_string()).ok().map(Serde) {
vec![cookie]
} else {
vec![]
};
let _ = self.window
.upcast::<GlobalScope>()
.resource_threads()
.send(SetCookiesForUrl(self.url(), cookies, NonHTTP));
let _ = self
.window
.upcast::<GlobalScope>()
.resource_threads()
.send(SetCookiesForUrl(self.url(), cookies, NonHTTP));
Ok(())
}
@ -4158,7 +4167,8 @@ impl DocumentMethods for Document {
node::from_untrusted_node_address(js_runtime, untrusted_node_address)
};
DomRoot::downcast::<Element>(node)
}).collect();
})
.collect();
// Step 4
if let Some(root_element) = self.GetDocumentElement() {
@ -4172,7 +4182,11 @@ impl DocumentMethods for Document {
}
// https://html.spec.whatwg.org/multipage/#dom-document-open
fn Open(&self, _unused1: Option<DOMString>, _unused2: Option<DOMString>) -> Fallible<DomRoot<Document>> {
fn Open(
&self,
_unused1: Option<DOMString>,
_unused2: Option<DOMString>,
) -> Fallible<DomRoot<Document>> {
// Step 1
if !self.is_html_document() {
return Err(Error::InvalidState);
@ -4266,12 +4280,19 @@ impl DocumentMethods for Document {
}
// https://html.spec.whatwg.org/multipage/#dom-document-open-window
fn Open_(&self, url: DOMString, target: DOMString, features: DOMString) -> Fallible<DomRoot<WindowProxy>> {
fn Open_(
&self,
url: DOMString,
target: DOMString,
features: DOMString,
) -> Fallible<DomRoot<WindowProxy>> {
// WhatWG spec states this should always return a WindowProxy, but the spec for WindowProxy.open states
// it optionally returns a WindowProxy. Assume an error if window.open returns none.
// See https://github.com/whatwg/html/issues/4091
let context = self.browsing_context().ok_or(Error::InvalidAccess)?;
context.open(url, target, features).ok_or(Error::InvalidAccess)
context
.open(url, target, features)
.ok_or(Error::InvalidAccess)
}
// https://html.spec.whatwg.org/multipage/#dom-document-write
@ -4297,7 +4318,9 @@ impl DocumentMethods for Document {
// Either there is no parser, which means the parsing ended;
// or script nesting level is 0, which means the method was
// called from outside a parser-executed script.
if self.is_prompting_or_unloading() || self.ignore_destructive_writes_counter.get() > 0 {
if self.is_prompting_or_unloading() ||
self.ignore_destructive_writes_counter.get() > 0
{
// Step 4.
return Ok(());
}

View file

@ -295,7 +295,8 @@ impl DOMMatrixMethods for DOMMatrix {
// https://drafts.fxtf.org/geometry-1/#dom-dommatrix-multiplyself
fn MultiplySelf(&self, other: &DOMMatrixInit) -> Fallible<DomRoot<DOMMatrix>> {
// Steps 1-3.
self.upcast::<DOMMatrixReadOnly>().multiply_self(other)
self.upcast::<DOMMatrixReadOnly>()
.multiply_self(other)
// Step 4.
.and(Ok(DomRoot::from_ref(&self)))
}
@ -303,7 +304,8 @@ impl DOMMatrixMethods for DOMMatrix {
// https://drafts.fxtf.org/geometry-1/#dom-dommatrix-premultiplyself
fn PreMultiplySelf(&self, other: &DOMMatrixInit) -> Fallible<DomRoot<DOMMatrix>> {
// Steps 1-3.
self.upcast::<DOMMatrixReadOnly>().pre_multiply_self(other)
self.upcast::<DOMMatrixReadOnly>()
.pre_multiply_self(other)
// Step 4.
.and(Ok(DomRoot::from_ref(&self)))
}

View file

@ -456,7 +456,8 @@ pub unsafe fn get_attr_for_layout<'a>(
.find(|attr| {
let attr = attr.to_layout();
*name == attr.local_name_atom_forever() && (*attr.unsafe_get()).namespace() == namespace
}).map(|attr| attr.to_layout())
})
.map(|attr| attr.to_layout())
}
#[allow(unsafe_code)]
@ -491,7 +492,8 @@ impl RawLayoutElementHelpers for Element {
} else {
None
}
}).collect()
})
.collect()
}
}
@ -2014,7 +2016,8 @@ impl ElementMethods for Element {
rect.size.width.to_f64_px(),
rect.size.height.to_f64_px(),
)
}).collect()
})
.collect()
}
// https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect
@ -2766,9 +2769,7 @@ impl<'a> SelectorsElement for DomRoot<Element> {
#[allow(unsafe_code)]
fn opaque(&self) -> ::selectors::OpaqueElement {
::selectors::OpaqueElement::new(unsafe {
&*self.reflector().get_jsobject().get()
})
::selectors::OpaqueElement::new(unsafe { &*self.reflector().get_jsobject().get() })
}
fn parent_element(&self) -> Option<DomRoot<Element>> {
@ -3102,7 +3103,8 @@ impl Element {
})
// TODO: Check meta tags for a pragma-set default language
// TODO: Check HTTP Content-Language header
}).next()
})
.next()
.unwrap_or(String::new())
}

View file

@ -40,7 +40,6 @@ use std::str::{Chars, FromStr};
use std::sync::{Arc, Mutex};
use utf8;
const DEFAULT_RECONNECTION_TIME: u64 = 5000;
#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
@ -179,8 +178,10 @@ impl EventSourceContext {
self.data.push('\n');
},
"id" => mem::swap(&mut self.last_event_id, &mut self.value),
"retry" => if let Ok(time) = u64::from_str(&self.value) {
self.event_source.root().reconnection_time.set(time);
"retry" => {
if let Ok(time) = u64::from_str(&self.value) {
self.event_source.root().reconnection_time.set(time);
}
},
_ => (),
}
@ -339,13 +340,15 @@ impl FetchResponseListener for EventSourceContext {
match meta.content_type {
None => self.fail_the_connection(),
Some(ct) => {
if <ContentType as Into<Mime>>::into(ct.into_inner()) == mime::TEXT_EVENT_STREAM {
if <ContentType as Into<Mime>>::into(ct.into_inner()) ==
mime::TEXT_EVENT_STREAM
{
self.origin = meta.final_url.origin().ascii_serialization();
self.announce_the_connection();
} else {
self.fail_the_connection()
}
}
},
}
},
Err(_) => {
@ -503,7 +506,10 @@ impl EventSource {
};
// Step 10
// TODO(eijebong): Replace once typed headers allow it
request.headers.insert(header::ACCEPT, HeaderValue::from_static("text/event-stream"));
request.headers.insert(
header::ACCEPT,
HeaderValue::from_static("text/event-stream"),
);
// Step 11
request.cache_mode = CacheMode::NoStore;
// Step 12
@ -543,7 +549,8 @@ impl EventSource {
.send(CoreResourceMsg::Fetch(
request,
FetchChannels::ResponseMsg(action_sender, Some(cancel_receiver)),
)).unwrap();
))
.unwrap();
// Step 13
Ok(ev)
}
@ -614,8 +621,11 @@ impl EventSourceTimeoutCallback {
// Step 5.3
if !event_source.last_event_id.borrow().is_empty() {
//TODO(eijebong): Change this once typed header support custom values
request.headers.insert(HeaderName::from_static("last-event-id"),
HeaderValue::from_str(&String::from(event_source.last_event_id.borrow().clone())).unwrap());
request.headers.insert(
HeaderName::from_static("last-event-id"),
HeaderValue::from_str(&String::from(event_source.last_event_id.borrow().clone()))
.unwrap(),
);
}
// Step 5.4
global
@ -623,6 +633,7 @@ impl EventSourceTimeoutCallback {
.send(CoreResourceMsg::Fetch(
request,
FetchChannels::ResponseMsg(self.action_sender, None),
)).unwrap();
))
.unwrap();
}
}

View file

@ -302,7 +302,8 @@ impl EventListeners {
} else {
None
}
}).collect()
})
.collect()
}
fn has_listeners(&self) -> bool {

View file

@ -465,7 +465,8 @@ impl FileReader {
task_source,
canceller,
)
}).expect("Thread spawning failed");
})
.expect("Thread spawning failed");
Ok(())
}

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