diff options
252 files changed, 5976 insertions, 3776 deletions
diff --git a/components/allocator/lib.rs b/components/allocator/lib.rs index 59596ce8e8d..97b7ac20531 100644 --- a/components/allocator/lib.rs +++ b/components/allocator/lib.rs @@ -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 { diff --git a/components/bluetooth/lib.rs b/components/bluetooth/lib.rs index 300927d440f..79525820a37 100644 --- a/components/bluetooth/lib.rs +++ b/components/bluetooth/lib.rs @@ -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 diff --git a/components/bluetooth/test.rs b/components/bluetooth/test.rs index a879c66ce5e..e0eacc2d8e5 100644 --- a/components/bluetooth/test.rs +++ b/components/bluetooth/test.rs @@ -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( diff --git a/components/canvas/canvas_data.rs b/components/canvas/canvas_data.rs index 2b42aba9656..31da765f59f 100644 --- a/components/canvas/canvas_data.rs +++ b/components/canvas/canvas_data.rs @@ -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, + ) } } diff --git a/components/canvas/canvas_paint_thread.rs b/components/canvas/canvas_paint_thread.rs index 0eecd116348..7baef384ae9 100644 --- a/components/canvas/canvas_paint_thread.rs +++ b/components/canvas/canvas_paint_thread.rs @@ -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()), } } diff --git a/components/canvas/gl_context.rs b/components/canvas/gl_context.rs index 77cbc20e55b..916f381a286 100644 --- a/components/canvas/gl_context.rs +++ b/components/canvas/gl_context.rs @@ -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)); } } diff --git a/components/canvas/lib.rs b/components/canvas/lib.rs index 554f598403c..2e42b7e1902 100644 --- a/components/canvas/lib.rs +++ b/components/canvas/lib.rs @@ -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; diff --git a/components/canvas/webgl_thread.rs b/components/canvas/webgl_thread.rs index 96233d1c410..d6d6e98f28e 100644 --- a/components/canvas/webgl_thread.rs +++ b/components/canvas/webgl_thread.rs @@ -92,21 +92,21 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { ) -> WebGLSender<WebGLMsg> { let (sender, receiver) = webgl_channel::<WebGLMsg>().unwrap(); let result = sender.clone(); - thread::Builder::new().name("WebGLThread".to_owned()).spawn(move || { - let mut renderer = WebGLThread::new( - gl_factory, - webrender_api_sender, - webvr_compositor, - ); - let webgl_chan = WebGLChan(sender); - loop { - let msg = receiver.recv().unwrap(); - let exit = renderer.handle_msg(msg, &webgl_chan); - if exit { - return; + thread::Builder::new() + .name("WebGLThread".to_owned()) + .spawn(move || { + let mut renderer = + WebGLThread::new(gl_factory, webrender_api_sender, webvr_compositor); + let webgl_chan = WebGLChan(sender); + loop { + let msg = receiver.recv().unwrap(); + let exit = renderer.handle_msg(msg, &webgl_chan); + if exit { + return; + } } - } - }).expect("Thread spawning failed"); + }) + .expect("Thread spawning failed"); result } @@ -117,26 +117,32 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { match msg { WebGLMsg::CreateContext(version, size, attributes, result_sender) => { let result = self.create_webgl_context(version, size, attributes); - result_sender.send(result.map(|(id, limits, share_mode)| { - let data = Self::make_current_if_needed(id, &self.contexts, &mut self.bound_context_id) - .expect("WebGLContext not found"); - let glsl_version = Self::get_glsl_version(&data.ctx); - - // FIXME(nox): Should probably be done by offscreen_gl_context. - if (glsl_version.major, glsl_version.minor) < (3, 1) { - data.ctx.gl().enable(gl::POINT_SPRITE); - } - if !is_gles() { - data.ctx.gl().enable(gl::PROGRAM_POINT_SIZE); - } - - WebGLCreateContextResult { - sender: WebGLMsgSender::new(id, webgl_chan.clone()), - limits, - share_mode, - glsl_version, - } - })).unwrap(); + result_sender + .send(result.map(|(id, limits, share_mode)| { + let data = Self::make_current_if_needed( + id, + &self.contexts, + &mut self.bound_context_id, + ) + .expect("WebGLContext not found"); + let glsl_version = Self::get_glsl_version(&data.ctx); + + // FIXME(nox): Should probably be done by offscreen_gl_context. + if (glsl_version.major, glsl_version.minor) < (3, 1) { + data.ctx.gl().enable(gl::POINT_SPRITE); + } + if !is_gles() { + data.ctx.gl().enable(gl::PROGRAM_POINT_SIZE); + } + + WebGLCreateContextResult { + sender: WebGLMsgSender::new(id, webgl_chan.clone()), + limits, + share_mode, + glsl_version, + } + })) + .unwrap(); }, WebGLMsg::ResizeContext(ctx_id, size, sender) => { self.resize_webgl_context(ctx_id, size, sender); @@ -164,7 +170,7 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { }, WebGLMsg::Exit => { return true; - } + }, } false @@ -177,7 +183,11 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { command: WebGLCommand, backtrace: WebGLCommandBacktrace, ) { - let data = Self::make_current_if_needed_mut(context_id, &mut self.contexts, &mut self.bound_context_id); + let data = Self::make_current_if_needed_mut( + context_id, + &mut self.contexts, + &mut self.bound_context_id, + ); if let Some(data) = data { data.ctx.apply_command(command, backtrace, &mut data.state); } @@ -187,18 +197,24 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { fn handle_webvr_command(&mut self, context_id: WebGLContextId, command: WebVRCommand) { Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id); let texture = match command { - WebVRCommand::SubmitFrame(..) => { - self.cached_context_info.get(&context_id) - }, - _ => None + WebVRCommand::SubmitFrame(..) => self.cached_context_info.get(&context_id), + _ => None, }; - self.webvr_compositor.as_mut().unwrap().handle(command, texture.map(|t| (t.texture_id, t.size))); + self.webvr_compositor + .as_mut() + .unwrap() + .handle(command, texture.map(|t| (t.texture_id, t.size))); } /// Handles a lock external callback received from webrender::ExternalImageHandler - fn handle_lock(&mut self, context_id: WebGLContextId, sender: WebGLSender<(u32, Size2D<i32>, usize)>) { - let data = Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id) - .expect("WebGLContext not found in a WebGLMsg::Lock message"); + fn handle_lock( + &mut self, + context_id: WebGLContextId, + sender: WebGLSender<(u32, Size2D<i32>, usize)>, + ) { + let data = + Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id) + .expect("WebGLContext not found in a WebGLMsg::Lock message"); let info = self.cached_context_info.get_mut(&context_id).unwrap(); // Insert a OpenGL Fence sync object that sends a signal when all the WebGL commands are finished. // The related gl().wait_sync call is performed in the WR thread. See WebGLExternalImageApi for mor details. @@ -208,13 +224,16 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { // Without proper flushing, the sync object may never be signaled. data.ctx.gl().flush(); - sender.send((info.texture_id, info.size, gl_sync as usize)).unwrap(); + sender + .send((info.texture_id, info.size, gl_sync as usize)) + .unwrap(); } /// Handles an unlock external callback received from webrender::ExternalImageHandler fn handle_unlock(&mut self, context_id: WebGLContextId) { - let data = Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id) - .expect("WebGLContext not found in a WebGLMsg::Unlock message"); + let data = + Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id) + .expect("WebGLContext not found in a WebGLMsg::Unlock message"); let info = self.cached_context_info.get_mut(&context_id).unwrap(); if let Some(gl_sync) = info.gl_sync.take() { // Release the GLSync object. @@ -235,7 +254,8 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { // First try to create a shared context for the best performance. // Fallback to readback mode if the shared context creation fails. - let (ctx, share_mode) = self.gl_factory + let (ctx, share_mode) = self + .gl_factory .new_shared_context(version, size, attributes) .map(|r| (r, WebGLContextShareMode::SharedTexture)) .or_else(|err| { @@ -251,18 +271,24 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { let id = WebGLContextId(self.next_webgl_id); let (size, texture_id, limits) = ctx.get_info(); self.next_webgl_id += 1; - self.contexts.insert(id, GLContextData { - ctx, - state: Default::default(), - }); - self.cached_context_info.insert(id, WebGLContextInfo { - texture_id, - size, - alpha: attributes.alpha, - image_key: None, - share_mode, - gl_sync: None, - }); + self.contexts.insert( + id, + GLContextData { + ctx, + state: Default::default(), + }, + ); + self.cached_context_info.insert( + id, + WebGLContextInfo { + texture_id, + size, + alpha: attributes.alpha, + image_key: None, + share_mode, + gl_sync: None, + }, + ); Ok((id, limits, share_mode)) } @@ -277,8 +303,9 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { let data = Self::make_current_if_needed_mut( context_id, &mut self.contexts, - &mut self.bound_context_id - ).expect("Missing WebGL context!"); + &mut self.bound_context_id, + ) + .expect("Missing WebGL context!"); match data.ctx.resize(size) { Ok(_) => { let (real_size, texture_id, _) = data.ctx.get_info(); @@ -291,20 +318,22 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { // See `handle_update_wr_image`. match (info.image_key, info.share_mode) { (Some(image_key), WebGLContextShareMode::SharedTexture) => { - Self::update_wr_external_image(&self.webrender_api, - info.size, - info.alpha, - context_id, - image_key); + Self::update_wr_external_image( + &self.webrender_api, + info.size, + info.alpha, + context_id, + image_key, + ); }, - _ => {} + _ => {}, } sender.send(Ok(())).unwrap(); }, Err(msg) => { sender.send(Err(msg.into())).unwrap(); - } + }, } } @@ -333,7 +362,11 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { /// If SharedTexture is used the UpdateWebRenderImage message is sent only after a WebGLContext creation. /// If Readback is used UpdateWebRenderImage message is sent always on each layout iteration in order to /// submit the updated raw pixels. - fn handle_update_wr_image(&mut self, context_id: WebGLContextId, sender: WebGLSender<webrender_api::ImageKey>) { + fn handle_update_wr_image( + &mut self, + context_id: WebGLContextId, + sender: WebGLSender<webrender_api::ImageKey>, + ) { let info = self.cached_context_info.get_mut(&context_id).unwrap(); let webrender_api = &self.webrender_api; @@ -353,25 +386,29 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { Some(image_key) => { // ImageKey was already created, but WR Images must // be updated every frame in readback mode to send the new raw pixels. - Self::update_wr_readback_image(webrender_api, - info.size, - info.alpha, - image_key, - pixels); + Self::update_wr_readback_image( + webrender_api, + info.size, + info.alpha, + image_key, + pixels, + ); image_key }, None => { // Generate a new ImageKey for Readback mode. - let image_key = Self::create_wr_readback_image(webrender_api, - info.size, - info.alpha, - pixels); + let image_key = Self::create_wr_readback_image( + webrender_api, + info.size, + info.alpha, + pixels, + ); info.image_key = Some(image_key); image_key - } + }, } - } + }, }; // Send the ImageKey to the Layout thread. @@ -381,8 +418,12 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { fn handle_dom_to_texture(&mut self, command: DOMToTextureCommand) { match command { DOMToTextureCommand::Attach(context_id, texture_id, document_id, pipeline_id, size) => { - let data = Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id) - .expect("WebGLContext not found in a WebGL DOMToTextureCommand::Attach command"); + let data = Self::make_current_if_needed( + context_id, + &self.contexts, + &mut self.bound_context_id, + ) + .expect("WebGLContext not found in a WebGL DOMToTextureCommand::Attach command"); // Initialize the texture that WR will use for frame outputs. data.ctx.gl().tex_image_2d( gl::TEXTURE_2D, @@ -393,11 +434,17 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { 0, gl::RGBA, gl::UNSIGNED_BYTE, - None + None, + ); + self.dom_outputs.insert( + pipeline_id, + DOMToTextureData { + context_id, + texture_id, + document_id, + size, + }, ); - self.dom_outputs.insert(pipeline_id, DOMToTextureData { - context_id, texture_id, document_id, size - }); let mut txn = webrender_api::Transaction::new(); txn.enable_frame_output(pipeline_id, true); self.webrender_api.send_transaction(document_id, txn); @@ -406,12 +453,18 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { let contexts = &self.contexts; let bound_context_id = &mut self.bound_context_id; let result = self.dom_outputs.get(&pipeline_id).and_then(|dom_data| { - let data = Self::make_current_if_needed(dom_data.context_id, contexts, bound_context_id); + let data = Self::make_current_if_needed( + dom_data.context_id, + contexts, + bound_context_id, + ); data.and_then(|data| { // The next glWaitSync call is used to synchronize the two flows of // OpenGL commands (WR and WebGL) in order to avoid using semi-ready WR textures. // glWaitSync doesn't block WebGL CPU thread. - data.ctx.gl().wait_sync(gl_sync as gl::GLsync, 0, gl::TIMEOUT_IGNORED); + data.ctx + .gl() + .wait_sync(gl_sync as gl::GLsync, 0, gl::TIMEOUT_IGNORED); Some((dom_data.texture_id.get(), dom_data.size)) }) }); @@ -420,9 +473,12 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { sender.send(result).unwrap(); }, DOMToTextureCommand::Detach(texture_id) => { - if let Some((pipeline_id, document_id)) = self.dom_outputs.iter() - .find(|&(_, v)| v.texture_id == texture_id) - .map(|(k, v)| (*k, v.document_id)) { + if let Some((pipeline_id, document_id)) = self + .dom_outputs + .iter() + .find(|&(_, v)| v.texture_id == texture_id) + .map(|(k, v)| (*k, v.document_id)) + { let mut txn = webrender_api::Transaction::new(); txn.enable_frame_output(pipeline_id, false); self.webrender_api.send_transaction(document_id, txn); @@ -433,9 +489,11 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { } /// Gets a reference to a GLContextWrapper for a given WebGLContextId and makes it current if required. - fn make_current_if_needed<'a>(context_id: WebGLContextId, - contexts: &'a FnvHashMap<WebGLContextId, GLContextData>, - bound_id: &mut Option<WebGLContextId>) -> Option<&'a GLContextData> { + fn make_current_if_needed<'a>( + context_id: WebGLContextId, + contexts: &'a FnvHashMap<WebGLContextId, GLContextData>, + bound_id: &mut Option<WebGLContextId>, + ) -> Option<&'a GLContextData> { let data = contexts.get(&context_id); if let Some(data) = data { @@ -452,9 +510,8 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { fn make_current_if_needed_mut<'a>( context_id: WebGLContextId, contexts: &'a mut FnvHashMap<WebGLContextId, GLContextData>, - bound_id: &mut Option<WebGLContextId>) - -> Option<&'a mut GLContextData> - { + bound_id: &mut Option<WebGLContextId>, + ) -> Option<&'a mut GLContextData> { let data = contexts.get_mut(&context_id); if let Some(ref data) = data { @@ -468,10 +525,12 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { } /// Creates a `webrender_api::ImageKey` that uses shared textures. - fn create_wr_external_image(webrender_api: &webrender_api::RenderApi, - size: Size2D<i32>, - alpha: bool, - context_id: WebGLContextId) -> webrender_api::ImageKey { + fn create_wr_external_image( + webrender_api: &webrender_api::RenderApi, + size: Size2D<i32>, + alpha: bool, + context_id: WebGLContextId, + ) -> webrender_api::ImageKey { let descriptor = Self::image_descriptor(size, alpha); let data = Self::external_image_data(context_id); @@ -484,11 +543,13 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { } /// Updates a `webrender_api::ImageKey` that uses shared textures. - fn update_wr_external_image(webrender_api: &webrender_api::RenderApi, - size: Size2D<i32>, - alpha: bool, - context_id: WebGLContextId, - image_key: webrender_api::ImageKey) { + fn update_wr_external_image( + webrender_api: &webrender_api::RenderApi, + size: Size2D<i32>, + alpha: bool, + context_id: WebGLContextId, + image_key: webrender_api::ImageKey, + ) { let descriptor = Self::image_descriptor(size, alpha); let data = Self::external_image_data(context_id); @@ -498,10 +559,12 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { } /// Creates a `webrender_api::ImageKey` that uses raw pixels. - fn create_wr_readback_image(webrender_api: &webrender_api::RenderApi, - size: Size2D<i32>, - alpha: bool, - data: Vec<u8>) -> webrender_api::ImageKey { + fn create_wr_readback_image( + webrender_api: &webrender_api::RenderApi, + size: Size2D<i32>, + alpha: bool, + data: Vec<u8>, + ) -> webrender_api::ImageKey { let descriptor = Self::image_descriptor(size, alpha); let data = webrender_api::ImageData::new(data); @@ -514,11 +577,13 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { } /// Updates a `webrender_api::ImageKey` that uses raw pixels. - fn update_wr_readback_image(webrender_api: &webrender_api::RenderApi, - size: Size2D<i32>, - alpha: bool, - image_key: webrender_api::ImageKey, - data: Vec<u8>) { + fn update_wr_readback_image( + webrender_api: &webrender_api::RenderApi, + size: Size2D<i32>, + alpha: bool, + image_key: webrender_api::ImageKey, + data: Vec<u8>, + ) { let descriptor = Self::image_descriptor(size, alpha); let data = webrender_api::ImageData::new(data); @@ -556,18 +621,22 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { let width = size.width as usize; let height = size.height as usize; - let mut pixels = context.gl().read_pixels(0, 0, - size.width as gl::GLsizei, - size.height as gl::GLsizei, - gl::RGBA, gl::UNSIGNED_BYTE); + let mut pixels = context.gl().read_pixels( + 0, + 0, + size.width as gl::GLsizei, + size.height as gl::GLsizei, + gl::RGBA, + gl::UNSIGNED_BYTE, + ); // flip image vertically (texture is upside down) let orig_pixels = pixels.clone(); let stride = width * 4; for y in 0..height { let dst_start = y * stride; let src_start = (height - y - 1) * stride; - let src_slice = &orig_pixels[src_start .. src_start + stride]; - (&mut pixels[dst_start .. dst_start + stride]).clone_from_slice(&src_slice[..stride]); + let src_slice = &orig_pixels[src_start..src_start + stride]; + (&mut pixels[dst_start..dst_start + stride]).clone_from_slice(&src_slice[..stride]); } pixels::byte_swap_colors_inplace(&mut pixels); pixels @@ -578,13 +647,16 @@ impl<VR: WebVRRenderHandler + 'static> WebGLThread<VR> { let version = context.gl().get_string(gl::SHADING_LANGUAGE_VERSION); // Fomat used by SHADING_LANGUAGE_VERSION query : major.minor[.release] [vendor info] let mut values = version.split(&['.', ' '][..]); - let major = values.next().and_then(|v| v.parse::<u32>().ok()).unwrap_or(1); - let minor = values.next().and_then(|v| v.parse::<u32>().ok()).unwrap_or(20); - - WebGLSLVersion { - major, - minor, - } + let major = values + .next() + .and_then(|v| v.parse::<u32>().ok()) + .unwrap_or(1); + let minor = values + .next() + .and_then(|v| v.parse::<u32>().ok()) + .unwrap_or(20); + + WebGLSLVersion { major, minor } } } @@ -632,38 +704,30 @@ pub struct WebGLExternalImageHandler<T: WebGLExternalImageApi> { impl<T: WebGLExternalImageApi> WebGLExternalImageHandler<T> { pub fn new(handler: T) -> Self { - Self { - handler: handler - } + Self { handler: handler } } } impl<T: WebGLExternalImageApi> webrender::ExternalImageHandler for WebGLExternalImageHandler<T> { /// Lock the external image. Then, WR could start to read the image content. /// The WR client should not change the image content until the unlock() call. - fn lock(&mut self, - key: webrender_api::ExternalImageId, - _channel_index: u8, - _rendering: webrender_api::ImageRendering) -> webrender::ExternalImage { + fn lock( + &mut self, + key: webrender_api::ExternalImageId, + _channel_index: u8, + _rendering: webrender_api::ImageRendering, + ) -> webrender::ExternalImage { let ctx_id = WebGLContextId(key.0 as _); let (texture_id, size) = self.handler.lock(ctx_id); webrender::ExternalImage { - uv: webrender_api::TexelRect::new( - 0.0, - size.height as f32, - size.width as f32, - 0.0, - ), + uv: webrender_api::TexelRect::new(0.0, size.height as f32, size.width as f32, 0.0), source: webrender::ExternalImageSource::NativeTexture(texture_id), } - } /// Unlock the external image. The WR should not read the image content /// after this call. - fn unlock(&mut self, - key: webrender_api::ExternalImageId, - _channel_index: u8) { + fn unlock(&mut self, key: webrender_api::ExternalImageId, _channel_index: u8) { let ctx_id = WebGLContextId(key.0 as _); self.handler.unlock(ctx_id); } @@ -689,82 +753,109 @@ impl WebGLImpl { _backtrace: WebGLCommandBacktrace, ) { match command { - WebGLCommand::GetContextAttributes(ref sender) => - sender.send(*ctx.borrow_attributes()).unwrap(), - WebGLCommand::ActiveTexture(target) => - ctx.gl().active_texture(target), - WebGLCommand::AttachShader(program_id, shader_id) => - ctx.gl().attach_shader(program_id.get(), shader_id.get()), - WebGLCommand::DetachShader(program_id, shader_id) => - ctx.gl().detach_shader(program_id.get(), shader_id.get()), - WebGLCommand::BindAttribLocation(program_id, index, ref name) => { - ctx.gl().bind_attrib_location(program_id.get(), index, &to_name_in_compiled_shader(name)) - } - WebGLCommand::BlendColor(r, g, b, a) => - ctx.gl().blend_color(r, g, b, a), - WebGLCommand::BlendEquation(mode) => - ctx.gl().blend_equation(mode), - WebGLCommand::BlendEquationSeparate(mode_rgb, mode_alpha) => - ctx.gl().blend_equation_separate(mode_rgb, mode_alpha), - WebGLCommand::BlendFunc(src, dest) => - ctx.gl().blend_func(src, dest), - WebGLCommand::BlendFuncSeparate(src_rgb, dest_rgb, src_alpha, dest_alpha) => - ctx.gl().blend_func_separate(src_rgb, dest_rgb, src_alpha, dest_alpha), + WebGLCommand::GetContextAttributes(ref sender) => { + sender.send(*ctx.borrow_attributes()).unwrap() + }, + WebGLCommand::ActiveTexture(target) => ctx.gl().active_texture(target), + WebGLCommand::AttachShader(program_id, shader_id) => { + ctx.gl().attach_shader(program_id.get(), shader_id.get()) + }, + WebGLCommand::DetachShader(program_id, shader_id) => { + ctx.gl().detach_shader(program_id.get(), shader_id.get()) + }, + WebGLCommand::BindAttribLocation(program_id, index, ref name) => ctx + .gl() + .bind_attrib_location(program_id.get(), index, &to_name_in_compiled_shader(name)), + WebGLCommand::BlendColor(r, g, b, a) => ctx.gl().blend_color(r, g, b, a), + WebGLCommand::BlendEquation(mode) => ctx.gl().blend_equation(mode), + WebGLCommand::BlendEquationSeparate(mode_rgb, mode_alpha) => { + ctx.gl().blend_equation_separate(mode_rgb, mode_alpha) + }, + WebGLCommand::BlendFunc(src, dest) => ctx.gl().blend_func(src, dest), + WebGLCommand::BlendFuncSeparate(src_rgb, dest_rgb, src_alpha, dest_alpha) => ctx + .gl() + .blend_func_separate(src_rgb, dest_rgb, src_alpha, dest_alpha), WebGLCommand::BufferData(buffer_type, ref receiver, usage) => { gl::buffer_data(ctx.gl(), buffer_type, &receiver.recv().unwrap(), usage) }, WebGLCommand::BufferSubData(buffer_type, offset, ref receiver) => { gl::buffer_sub_data(ctx.gl(), buffer_type, offset, &receiver.recv().unwrap()) }, - WebGLCommand::Clear(mask) => - ctx.gl().clear(mask), + WebGLCommand::Clear(mask) => ctx.gl().clear(mask), WebGLCommand::ClearColor(r, g, b, a) => { state.clear_color = (r, g, b, a); ctx.gl().clear_color(r, g, b, a); - } + }, WebGLCommand::ClearDepth(depth) => { let value = depth.max(0.).min(1.) as f64; state.depth_clear_value = value; ctx.gl().clear_depth(value) - } + }, WebGLCommand::ClearStencil(stencil) => { state.stencil_clear_value = stencil; ctx.gl().clear_stencil(stencil); - } - WebGLCommand::ColorMask(r, g, b, a) => - ctx.gl().color_mask(r, g, b, a), - WebGLCommand::CopyTexImage2D(target, level, internal_format, x, y, width, height, border) => - ctx.gl().copy_tex_image_2d(target, level, internal_format, x, y, width, height, border), - WebGLCommand::CopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height) => - ctx.gl().copy_tex_sub_image_2d(target, level, xoffset, yoffset, x, y, width, height), - WebGLCommand::CullFace(mode) => - ctx.gl().cull_face(mode), - WebGLCommand::DepthFunc(func) => - ctx.gl().depth_func(func), + }, + WebGLCommand::ColorMask(r, g, b, a) => ctx.gl().color_mask(r, g, b, a), + WebGLCommand::CopyTexImage2D( + target, + level, + internal_format, + x, + y, + width, + height, + border, + ) => ctx.gl().copy_tex_image_2d( + target, + level, + internal_format, + x, + y, + width, + height, + border, + ), + WebGLCommand::CopyTexSubImage2D( + target, + level, + xoffset, + yoffset, + x, + y, + width, + height, + ) => ctx + .gl() + .copy_tex_sub_image_2d(target, level, xoffset, yoffset, x, y, width, height), + WebGLCommand::CullFace(mode) => ctx.gl().cull_face(mode), + WebGLCommand::DepthFunc(func) => ctx.gl().depth_func(func), WebGLCommand::DepthMask(flag) => { state.depth_write_mask = flag; ctx.gl().depth_mask(flag); - } - WebGLCommand::DepthRange(near, far) => { - ctx.gl().depth_range(near.max(0.).min(1.) as f64, far.max(0.).min(1.) as f64) - } + }, + WebGLCommand::DepthRange(near, far) => ctx + .gl() + .depth_range(near.max(0.).min(1.) as f64, far.max(0.).min(1.) as f64), WebGLCommand::Disable(cap) => { if cap == gl::SCISSOR_TEST { state.scissor_test_enabled = false; } ctx.gl().disable(cap); - } + }, WebGLCommand::Enable(cap) => { if cap == gl::SCISSOR_TEST { state.scissor_test_enabled = true; } ctx.gl().enable(cap); - } + }, WebGLCommand::FramebufferRenderbuffer(target, attachment, renderbuffertarget, rb) => { let attach = |attachment| { - ctx.gl().framebuffer_renderbuffer(target, attachment, - renderbuffertarget, - rb.map_or(0, WebGLRenderbufferId::get)) + ctx.gl().framebuffer_renderbuffer( + target, + attachment, + renderbuffertarget, + rb.map_or(0, WebGLRenderbufferId::get), + ) }; if attachment == gl::DEPTH_STENCIL_ATTACHMENT { attach(gl::DEPTH_ATTACHMENT); @@ -772,11 +863,16 @@ impl WebGLImpl { } else { attach(attachment); } - } + }, WebGLCommand::FramebufferTexture2D(target, attachment, textarget, texture, level) => { let attach = |attachment| { - ctx.gl().framebuffer_texture_2d(target, attachment, textarget, - texture.map_or(0, WebGLTextureId::get), level) + ctx.gl().framebuffer_texture_2d( + target, + attachment, + textarget, + texture.map_or(0, WebGLTextureId::get), + level, + ) }; if attachment == gl::DEPTH_STENCIL_ATTACHMENT { attach(gl::DEPTH_ATTACHMENT); @@ -784,21 +880,18 @@ impl WebGLImpl { } else { attach(attachment) } - } - WebGLCommand::FrontFace(mode) => - ctx.gl().front_face(mode), - WebGLCommand::DisableVertexAttribArray(attrib_id) => - ctx.gl().disable_vertex_attrib_array(attrib_id), - WebGLCommand::EnableVertexAttribArray(attrib_id) => - ctx.gl().enable_vertex_attrib_array(attrib_id), - WebGLCommand::Hint(name, val) => - ctx.gl().hint(name, val), - WebGLCommand::LineWidth(width) => - ctx.gl().line_width(width), - WebGLCommand::PixelStorei(name, val) => - ctx.gl().pixel_store_i(name, val), - WebGLCommand::PolygonOffset(factor, units) => - ctx.gl().polygon_offset(factor, units), + }, + WebGLCommand::FrontFace(mode) => ctx.gl().front_face(mode), + WebGLCommand::DisableVertexAttribArray(attrib_id) => { + ctx.gl().disable_vertex_attrib_array(attrib_id) + }, + WebGLCommand::EnableVertexAttribArray(attrib_id) => { + ctx.gl().enable_vertex_attrib_array(attrib_id) + }, + WebGLCommand::Hint(name, val) => ctx.gl().hint(name, val), + WebGLCommand::LineWidth(width) => ctx.gl().line_width(width), + WebGLCommand::PixelStorei(name, val) => ctx.gl().pixel_store_i(name, val), + WebGLCommand::PolygonOffset(factor, units) => ctx.gl().polygon_offset(factor, units), WebGLCommand::ReadPixels(rect, format, pixel_type, ref sender) => { let pixels = ctx.gl().read_pixels( rect.origin.x as i32, @@ -809,25 +902,25 @@ impl WebGLImpl { pixel_type, ); sender.send(&pixels).unwrap(); - } - WebGLCommand::RenderbufferStorage(target, format, width, height) => - ctx.gl().renderbuffer_storage(target, format, width, height), - WebGLCommand::SampleCoverage(value, invert) => - ctx.gl().sample_coverage(value, invert), + }, + WebGLCommand::RenderbufferStorage(target, format, width, height) => { + ctx.gl().renderbuffer_storage(target, format, width, height) + }, + WebGLCommand::SampleCoverage(value, invert) => ctx.gl().sample_coverage(value, invert), WebGLCommand::Scissor(x, y, width, height) => { // FIXME(nox): Kinda unfortunate that some u32 values could // end up as negative numbers here, but I don't even think // that can happen in the real world. ctx.gl().scissor(x, y, width as i32, height as i32); }, - WebGLCommand::StencilFunc(func, ref_, mask) => - ctx.gl().stencil_func(func, ref_, mask), - WebGLCommand::StencilFuncSeparate(face, func, ref_, mask) => - ctx.gl().stencil_func_separate(face, func, ref_, mask), + WebGLCommand::StencilFunc(func, ref_, mask) => ctx.gl().stencil_func(func, ref_, mask), + WebGLCommand::StencilFuncSeparate(face, func, ref_, mask) => { + ctx.gl().stencil_func_separate(face, func, ref_, mask) + }, WebGLCommand::StencilMask(mask) => { state.stencil_write_mask = (mask, mask); ctx.gl().stencil_mask(mask); - } + }, WebGLCommand::StencilMaskSeparate(face, mask) => { if face == gl::FRONT { state.stencil_write_mask.0 = mask; @@ -835,385 +928,418 @@ impl WebGLImpl { state.stencil_write_mask.1 = mask; } ctx.gl().stencil_mask_separate(face, mask); - } - WebGLCommand::StencilOp(fail, zfail, zpass) => - ctx.gl().stencil_op(fail, zfail, zpass), - WebGLCommand::StencilOpSeparate(face, fail, zfail, zpass) => - ctx.gl().stencil_op_separate(face, fail, zfail, zpass), - WebGLCommand::GetRenderbufferParameter(target, pname, ref chan) => - Self::get_renderbuffer_parameter(ctx.gl(), target, pname, chan), - WebGLCommand::GetFramebufferAttachmentParameter(target, attachment, pname, ref chan) => - Self::get_framebuffer_attachment_parameter(ctx.gl(), target, attachment, pname, chan), - WebGLCommand::GetShaderPrecisionFormat(shader_type, precision_type, ref chan) => - Self::shader_precision_format(ctx.gl(), shader_type, precision_type, chan), - WebGLCommand::GetExtensions(ref chan) => - Self::get_extensions(ctx.gl(), chan), - WebGLCommand::GetUniformLocation(program_id, ref name, ref chan) => - Self::uniform_location(ctx.gl(), program_id, &name, chan), - WebGLCommand::GetShaderInfoLog(shader_id, ref chan) => - Self::shader_info_log(ctx.gl(), shader_id, chan), - WebGLCommand::GetProgramInfoLog(program_id, ref chan) => - Self::program_info_log(ctx.gl(), program_id, chan), - WebGLCommand::CompileShader(shader_id, ref source) => - Self::compile_shader(ctx.gl(), shader_id, &source), - WebGLCommand::CreateBuffer(ref chan) => - Self::create_buffer(ctx.gl(), chan), - WebGLCommand::CreateFramebuffer(ref chan) => - Self::create_framebuffer(ctx.gl(), chan), - WebGLCommand::CreateRenderbuffer(ref chan) => - Self::create_renderbuffer(ctx.gl(), chan), - WebGLCommand::CreateTexture(ref chan) => - Self::create_texture(ctx.gl(), chan), - WebGLCommand::CreateProgram(ref chan) => - Self::create_program(ctx.gl(), chan), - WebGLCommand::CreateShader(shader_type, ref chan) => - Self::create_shader(ctx.gl(), shader_type, chan), - WebGLCommand::DeleteBuffer(id) => - ctx.gl().delete_buffers(&[id.get()]), - WebGLCommand::DeleteFramebuffer(id) => - ctx.gl().delete_framebuffers(&[id.get()]), - WebGLCommand::DeleteRenderbuffer(id) => - ctx.gl().delete_renderbuffers(&[id.get()]), - WebGLCommand::DeleteTexture(id) => - ctx.gl().delete_textures(&[id.get()]), - WebGLCommand::DeleteProgram(id) => - ctx.gl().delete_program(id.get()), - WebGLCommand::DeleteShader(id) => - ctx.gl().delete_shader(id.get()), - WebGLCommand::BindBuffer(target, id) => - ctx.gl().bind_buffer(target, id.map_or(0, WebGLBufferId::get)), - WebGLCommand::BindFramebuffer(target, request) => - Self::bind_framebuffer(ctx.gl(), target, request, ctx), - WebGLCommand::BindRenderbuffer(target, id) => - ctx.gl().bind_renderbuffer(target, id.map_or(0, WebGLRenderbufferId::get)), - WebGLCommand::BindTexture(target, id) => - ctx.gl().bind_texture(target, id.map_or(0, WebGLTextureId::get)), - WebGLCommand::Uniform1f(uniform_id, v) => - ctx.gl().uniform_1f(uniform_id, v), - WebGLCommand::Uniform1fv(uniform_id, ref v) => - ctx.gl().uniform_1fv(uniform_id, v), - WebGLCommand::Uniform1i(uniform_id, v) => - ctx.gl().uniform_1i(uniform_id, v), - WebGLCommand::Uniform1iv(uniform_id, ref v) => - ctx.gl().uniform_1iv(uniform_id, v), - WebGLCommand::Uniform2f(uniform_id, x, y) => - ctx.gl().uniform_2f(uniform_id, x, y), - WebGLCommand::Uniform2fv(uniform_id, ref v) => - ctx.gl().uniform_2fv(uniform_id, v), - WebGLCommand::Uniform2i(uniform_id, x, y) => - ctx.gl().uniform_2i(uniform_id, x, y), - WebGLCommand::Uniform2iv(uniform_id, ref v) => - ctx.gl().uniform_2iv(uniform_id, v), - WebGLCommand::Uniform3f(uniform_id, x, y, z) => - ctx.gl().uniform_3f(uniform_id, x, y, z), - WebGLCommand::Uniform3fv(uniform_id, ref v) => - ctx.gl().uniform_3fv(uniform_id, v), - WebGLCommand::Uniform3i(uniform_id, x, y, z) => - ctx.gl().uniform_3i(uniform_id, x, y, z), - WebGLCommand::Uniform3iv(uniform_id, ref v) => - ctx.gl().uniform_3iv(uniform_id, v), - WebGLCommand::Uniform4f(uniform_id, x, y, z, w) => - ctx.gl().uniform_4f(uniform_id, x, y, z, w), - WebGLCommand::Uniform4fv(uniform_id, ref v) => - ctx.gl().uniform_4fv(uniform_id, v), - WebGLCommand::Uniform4i(uniform_id, x, y, z, w) => - ctx.gl().uniform_4i(uniform_id, x, y, z, w), - WebGLCommand::Uniform4iv(uniform_id, ref v) => - ctx.gl().uniform_4iv(uniform_id, v), + }, + WebGLCommand::StencilOp(fail, zfail, zpass) => ctx.gl().stencil_op(fail, zfail, zpass), + WebGLCommand::StencilOpSeparate(face, fail, zfail, zpass) => { + ctx.gl().stencil_op_separate(face, fail, zfail, zpass) + }, + WebGLCommand::GetRenderbufferParameter(target, pname, ref chan) => { + Self::get_renderbuffer_parameter(ctx.gl(), target, pname, chan) + }, + WebGLCommand::GetFramebufferAttachmentParameter( + target, + attachment, + pname, + ref chan, + ) => Self::get_framebuffer_attachment_parameter( + ctx.gl(), + target, + attachment, + pname, + chan, + ), + WebGLCommand::GetShaderPrecisionFormat(shader_type, precision_type, ref chan) => { + Self::shader_precision_format(ctx.gl(), shader_type, precision_type, chan) + }, + WebGLCommand::GetExtensions(ref chan) => Self::get_extensions(ctx.gl(), chan), + WebGLCommand::GetUniformLocation(program_id, ref name, ref chan) => { + Self::uniform_location(ctx.gl(), program_id, &name, chan) + }, + WebGLCommand::GetShaderInfoLog(shader_id, ref chan) => { + Self::shader_info_log(ctx.gl(), shader_id, chan) + }, + WebGLCommand::GetProgramInfoLog(program_id, ref chan) => { + Self::program_info_log(ctx.gl(), program_id, chan) + }, + WebGLCommand::CompileShader(shader_id, ref source) => { + Self::compile_shader(ctx.gl(), shader_id, &source) + }, + WebGLCommand::CreateBuffer(ref chan) => Self::create_buffer(ctx.gl(), chan), + WebGLCommand::CreateFramebuffer(ref chan) => Self::create_framebuffer(ctx.gl(), chan), + WebGLCommand::CreateRenderbuffer(ref chan) => Self::create_renderbuffer(ctx.gl(), chan), + WebGLCommand::CreateTexture(ref chan) => Self::create_texture(ctx.gl(), chan), + WebGLCommand::CreateProgram(ref chan) => Self::create_program(ctx.gl(), chan), + WebGLCommand::CreateShader(shader_type, ref chan) => { + Self::create_shader(ctx.gl(), shader_type, chan) + }, + WebGLCommand::DeleteBuffer(id) => ctx.gl().delete_buffers(&[id.get()]), + WebGLCommand::DeleteFramebuffer(id) => ctx.gl().delete_framebuffers(&[id.get()]), + WebGLCommand::DeleteRenderbuffer(id) => ctx.gl().delete_renderbuffers(&[id.get()]), + WebGLCommand::DeleteTexture(id) => ctx.gl().delete_textures(&[id.get()]), + WebGLCommand::DeleteProgram(id) => ctx.gl().delete_program(id.get()), + WebGLCommand::DeleteShader(id) => ctx.gl().delete_shader(id.get()), + WebGLCommand::BindBuffer(target, id) => ctx + .gl() + .bind_buffer(target, id.map_or(0, WebGLBufferId::get)), + WebGLCommand::BindFramebuffer(target, request) => { + Self::bind_framebuffer(ctx.gl(), target, request, ctx) + }, + WebGLCommand::BindRenderbuffer(target, id) => ctx + .gl() + .bind_renderbuffer(target, id.map_or(0, WebGLRenderbufferId::get)), + WebGLCommand::BindTexture(target, id) => ctx + .gl() + .bind_texture(target, id.map_or(0, WebGLTextureId::get)), + WebGLCommand::Uniform1f(uniform_id, v) => ctx.gl().uniform_1f(uniform_id, v), + WebGLCommand::Uniform1fv(uniform_id, ref v) => ctx.gl().uniform_1fv(uniform_id, v), + WebGLCommand::Uniform1i(uniform_id, v) => ctx.gl().uniform_1i(uniform_id, v), + WebGLCommand::Uniform1iv(uniform_id, ref v) => ctx.gl().uniform_1iv(uniform_id, v), + WebGLCommand::Uniform2f(uniform_id, x, y) => ctx.gl().uniform_2f(uniform_id, x, y), + WebGLCommand::Uniform2fv(uniform_id, ref v) => ctx.gl().uniform_2fv(uniform_id, v), + WebGLCommand::Uniform2i(uniform_id, x, y) => ctx.gl().uniform_2i(uniform_id, x, y), + WebGLCommand::Uniform2iv(uniform_id, ref v) => ctx.gl().uniform_2iv(uniform_id, v), + WebGLCommand::Uniform3f(uniform_id, x, y, z) => { + ctx.gl().uniform_3f(uniform_id, x, y, z) + }, + WebGLCommand::Uniform3fv(uniform_id, ref v) => ctx.gl().uniform_3fv(uniform_id, v), + WebGLCommand::Uniform3i(uniform_id, x, y, z) => { + ctx.gl().uniform_3i(uniform_id, x, y, z) + }, + WebGLCommand::Uniform3iv(uniform_id, ref v) => ctx.gl().uniform_3iv(uniform_id, v), + WebGLCommand::Uniform4f(uniform_id, x, y, z, w) => { + ctx.gl().uniform_4f(uniform_id, x, y, z, w) + }, + WebGLCommand::Uniform4fv(uniform_id, ref v) => ctx.gl().uniform_4fv(uniform_id, v), + WebGLCommand::Uniform4i(uniform_id, x, y, z, w) => { + ctx.gl().uniform_4i(uniform_id, x, y, z, w) + }, + WebGLCommand::Uniform4iv(uniform_id, ref v) => ctx.gl().uniform_4iv(uniform_id, v), WebGLCommand::UniformMatrix2fv(uniform_id, ref v) => { ctx.gl().uniform_matrix_2fv(uniform_id, false, v) - } + }, WebGLCommand::UniformMatrix3fv(uniform_id, ref v) => { ctx.gl().uniform_matrix_3fv(uniform_id, false, v) - } + }, WebGLCommand::UniformMatrix4fv(uniform_id, ref v) => { ctx.gl().uniform_matrix_4fv(uniform_id, false, v) - } - WebGLCommand::ValidateProgram(program_id) => - ctx.gl().validate_program(program_id.get()), - WebGLCommand::VertexAttrib(attrib_id, x, y, z, w) => - ctx.gl().vertex_attrib_4f(attrib_id, x, y, z, w), - WebGLCommand::VertexAttribPointer2f(attrib_id, size, normalized, stride, offset) => - ctx.gl().vertex_attrib_pointer_f32(attrib_id, size, normalized, stride, offset), - WebGLCommand::VertexAttribPointer(attrib_id, size, data_type, normalized, stride, offset) => - ctx.gl().vertex_attrib_pointer(attrib_id, size, data_type, normalized, stride, offset), + }, + WebGLCommand::ValidateProgram(program_id) => { + ctx.gl().validate_program(program_id.get()) + }, + WebGLCommand::VertexAttrib(attrib_id, x, y, z, w) => { + ctx.gl().vertex_attrib_4f(attrib_id, x, y, z, w) + }, + WebGLCommand::VertexAttribPointer2f(attrib_id, size, normalized, stride, offset) => ctx + .gl() + .vertex_attrib_pointer_f32(attrib_id, size, normalized, stride, offset), + WebGLCommand::VertexAttribPointer( + attrib_id, + size, + data_type, + normalized, + stride, + offset, + ) => ctx + .gl() + .vertex_attrib_pointer(attrib_id, size, data_type, normalized, stride, offset), WebGLCommand::SetViewport(x, y, width, height) => { ctx.gl().viewport(x, y, width, height); - } - WebGLCommand::TexImage2D(target, level, internal, width, height, format, data_type, ref chan) => { - ctx.gl().tex_image_2d( - target, - level, - internal, - width, - height, - 0, - format, - data_type, - Some(&chan.recv().unwrap()), - ) - } - WebGLCommand::TexSubImage2D(target, level, xoffset, yoffset, x, y, width, height, ref chan) => { - ctx.gl().tex_sub_image_2d( - target, - level, - xoffset, - yoffset, - x, - y, - width, - height, - &chan.recv().unwrap(), - ) - } - WebGLCommand::DrawingBufferWidth(ref sender) => - sender.send(ctx.borrow_draw_buffer().unwrap().size().width).unwrap(), - WebGLCommand::DrawingBufferHeight(ref sender) => - sender.send(ctx.borrow_draw_buffer().unwrap().size().height).unwrap(), - WebGLCommand::Finish(ref sender) => - Self::finish(ctx.gl(), sender), - WebGLCommand::Flush => - ctx.gl().flush(), - WebGLCommand::GenerateMipmap(target) => - ctx.gl().generate_mipmap(target), - WebGLCommand::CreateVertexArray(ref chan) => - Self::create_vertex_array(ctx.gl(), chan), - WebGLCommand::DeleteVertexArray(id) => - ctx.gl().delete_vertex_arrays(&[id.get()]), - WebGLCommand::BindVertexArray(id) => - ctx.gl().bind_vertex_array(id.map_or(0, WebGLVertexArrayId::get)), + }, + WebGLCommand::TexImage2D( + target, + level, + internal, + width, + height, + format, + data_type, + ref chan, + ) => ctx.gl().tex_image_2d( + target, + level, + internal, + width, + height, + 0, + format, + data_type, + Some(&chan.recv().unwrap()), + ), + WebGLCommand::TexSubImage2D( + target, + level, + xoffset, + yoffset, + x, + y, + width, + height, + ref chan, + ) => ctx.gl().tex_sub_image_2d( + target, + level, + xoffset, + yoffset, + x, + y, + width, + height, + &chan.recv().unwrap(), + ), + WebGLCommand::DrawingBufferWidth(ref sender) => sender + .send(ctx.borrow_draw_buffer().unwrap().size().width) + .unwrap(), + WebGLCommand::DrawingBufferHeight(ref sender) => sender + .send(ctx.borrow_draw_buffer().unwrap().size().height) + .unwrap(), + WebGLCommand::Finish(ref sender) => Self::finish(ctx.gl(), sender), + WebGLCommand::Flush => ctx.gl().flush(), + WebGLCommand::GenerateMipmap(target) => ctx.gl().generate_mipmap(target), + WebGLCommand::CreateVertexArray(ref chan) => Self::create_vertex_array(ctx.gl(), chan), + WebGLCommand::DeleteVertexArray(id) => ctx.gl().delete_vertex_arrays(&[id.get()]), + WebGLCommand::BindVertexArray(id) => ctx + .gl() + .bind_vertex_array(id.map_or(0, WebGLVertexArrayId::get)), WebGLCommand::GetParameterBool(param, ref sender) => { let mut value = [0]; unsafe { ctx.gl().get_boolean_v(param as u32, &mut value); } sender.send(value[0] != 0).unwrap() - } + }, WebGLCommand::GetParameterBool4(param, ref sender) => { let mut value = [0; 4]; unsafe { ctx.gl().get_boolean_v(param as u32, &mut value); } - let value = [ - value[0] != 0, - value[1] != 0, - value[2] != 0, - value[3] != 0, - ]; + let value = [value[0] != 0, value[1] != 0, value[2] != 0, value[3] != 0]; sender.send(value).unwrap() - } + }, WebGLCommand::GetParameterInt(param, ref sender) => { let mut value = [0]; unsafe { ctx.gl().get_integer_v(param as u32, &mut value); } sender.send(value[0]).unwrap() - } + }, WebGLCommand::GetParameterInt2(param, ref sender) => { let mut value = [0; 2]; unsafe { ctx.gl().get_integer_v(param as u32, &mut value); } sender.send(value).unwrap() - } + }, WebGLCommand::GetParameterInt4(param, ref sender) => { let mut value = [0; 4]; unsafe { ctx.gl().get_integer_v(param as u32, &mut value); } sender.send(value).unwrap() - } + }, WebGLCommand::GetParameterFloat(param, ref sender) => { let mut value = [0.]; unsafe { ctx.gl().get_float_v(param as u32, &mut value); } sender.send(value[0]).unwrap() - } + }, WebGLCommand::GetParameterFloat2(param, ref sender) => { let mut value = [0.; 2]; unsafe { ctx.gl().get_float_v(param as u32, &mut value); } sender.send(value).unwrap() - } + }, WebGLCommand::GetParameterFloat4(param, ref sender) => { let mut value = [0.; 4]; unsafe { ctx.gl().get_float_v(param as u32, &mut value); } sender.send(value).unwrap() - } + }, WebGLCommand::GetProgramValidateStatus(program, ref sender) => { let mut value = [0]; unsafe { - ctx.gl().get_program_iv(program.get(), gl::VALIDATE_STATUS, &mut value); + ctx.gl() + .get_program_iv(program.get(), gl::VALIDATE_STATUS, &mut value); } sender.send(value[0] != 0).unwrap() - } + }, WebGLCommand::GetProgramActiveUniforms(program, ref sender) => { let mut value = [0]; unsafe { - ctx.gl().get_program_iv(program.get(), gl::ACTIVE_UNIFORMS, &mut value); + ctx.gl() + .get_program_iv(program.get(), gl::ACTIVE_UNIFORMS, &mut value); } sender.send(value[0]).unwrap() - } + }, WebGLCommand::GetCurrentVertexAttrib(index, ref sender) => { let mut value = [0.; 4]; unsafe { - ctx.gl().get_vertex_attrib_fv(index, gl::CURRENT_VERTEX_ATTRIB, &mut value); + ctx.gl() + .get_vertex_attrib_fv(index, gl::CURRENT_VERTEX_ATTRIB, &mut value); } sender.send(value).unwrap(); - } + }, WebGLCommand::GetTexParameterFloat(target, param, ref sender) => { - sender.send(ctx.gl().get_tex_parameter_fv(target, param as u32)).unwrap(); - } + sender + .send(ctx.gl().get_tex_parameter_fv(target, param as u32)) + .unwrap(); + }, WebGLCommand::GetTexParameterInt(target, param, ref sender) => { - sender.send(ctx.gl().get_tex_parameter_iv(target, param as u32)).unwrap(); - } + sender + .send(ctx.gl().get_tex_parameter_iv(target, param as u32)) + .unwrap(); + }, WebGLCommand::TexParameteri(target, param, value) => { ctx.gl().tex_parameter_i(target, param as u32, value) - } + }, WebGLCommand::TexParameterf(target, param, value) => { ctx.gl().tex_parameter_f(target, param as u32, value) - } + }, WebGLCommand::LinkProgram(program_id, ref sender) => { - return sender.send(Self::link_program(ctx.gl(), program_id)).unwrap(); - } + return sender + .send(Self::link_program(ctx.gl(), program_id)) + .unwrap(); + }, WebGLCommand::UseProgram(program_id) => { ctx.gl().use_program(program_id.map_or(0, |p| p.get())) - } + }, WebGLCommand::DrawArrays { mode, first, count } => { ctx.gl().draw_arrays(mode, first, count) - } - WebGLCommand::DrawArraysInstanced { mode, first, count, primcount } => { - ctx.gl().draw_arrays_instanced(mode, first, count, primcount) - } - WebGLCommand::DrawElements { mode, count, type_, offset } => { - ctx.gl().draw_elements(mode, count, type_, offset) - } - WebGLCommand::DrawElementsInstanced { mode, count, type_, offset, primcount } => { - ctx.gl().draw_elements_instanced(mode, count, type_, offset, primcount) - } + }, + WebGLCommand::DrawArraysInstanced { + mode, + first, + count, + primcount, + } => ctx + .gl() + .draw_arrays_instanced(mode, first, count, primcount), + WebGLCommand::DrawElements { + mode, + count, + type_, + offset, + } => ctx.gl().draw_elements(mode, count, type_, offset), + WebGLCommand::DrawElementsInstanced { + mode, + count, + type_, + offset, + primcount, + } => ctx + .gl() + .draw_elements_instanced(mode, count, type_, offset, primcount), WebGLCommand::VertexAttribDivisor { index, divisor } => { ctx.gl().vertex_attrib_divisor(index, divisor) - } + }, WebGLCommand::GetUniformBool(program_id, loc, ref sender) => { let mut value = [0]; unsafe { ctx.gl().get_uniform_iv(program_id.get(), loc, &mut value); } sender.send(value[0] != 0).unwrap(); - } + }, WebGLCommand::GetUniformBool2(program_id, loc, ref sender) => { let mut value = [0; 2]; unsafe { ctx.gl().get_uniform_iv(program_id.get(), loc, &mut value); } - let value = [ - value[0] != 0, - value[1] != 0, - ]; + let value = [value[0] != 0, value[1] != 0]; sender.send(value).unwrap(); - } + }, WebGLCommand::GetUniformBool3(program_id, loc, ref sender) => { let mut value = [0; 3]; unsafe { ctx.gl().get_uniform_iv(program_id.get(), loc, &mut value); } - let value = [ - value[0] != 0, - value[1] != 0, - value[2] != 0, - ]; + let value = [value[0] != 0, value[1] != 0, value[2] != 0]; sender.send(value).unwrap(); - } + }, WebGLCommand::GetUniformBool4(program_id, loc, ref sender) => { let mut value = [0; 4]; unsafe { ctx.gl().get_uniform_iv(program_id.get(), loc, &mut value); } - let value = [ - value[0] != 0, - value[1] != 0, - value[2] != 0, - value[3] != 0, - ]; + let value = [value[0] != 0, value[1] != 0, value[2] != 0, value[3] != 0]; sender.send(value).unwrap(); - } + }, WebGLCommand::GetUniformInt(program_id, loc, ref sender) => { let mut value = [0]; unsafe { ctx.gl().get_uniform_iv(program_id.get(), loc, &mut value); } sender.send(value[0]).unwrap(); - } + }, WebGLCommand::GetUniformInt2(program_id, loc, ref sender) => { let mut value = [0; 2]; unsafe { ctx.gl().get_uniform_iv(program_id.get(), loc, &mut value); } sender.send(value).unwrap(); - } + }, WebGLCommand::GetUniformInt3(program_id, loc, ref sender) => { let mut value = [0; 3]; unsafe { ctx.gl().get_uniform_iv(program_id.get(), loc, &mut value); } sender.send(value).unwrap(); - } + }, WebGLCommand::GetUniformInt4(program_id, loc, ref sender) => { let mut value = [0; 4]; unsafe { ctx.gl().get_uniform_iv(program_id.get(), loc, &mut value); } sender.send(value).unwrap(); - } + }, WebGLCommand::GetUniformFloat(program_id, loc, ref sender) => { let mut value = [0.]; unsafe { ctx.gl().get_uniform_fv(program_id.get(), loc, &mut value); } sender.send(value[0]).unwrap(); - } + }, WebGLCommand::GetUniformFloat2(program_id, loc, ref sender) => { let mut value = [0.; 2]; unsafe { ctx.gl().get_uniform_fv(program_id.get(), loc, &mut value); } sender.send(value).unwrap(); - } + }, WebGLCommand::GetUniformFloat3(program_id, loc, ref sender) => { let mut value = [0.; 3]; unsafe { ctx.gl().get_uniform_fv(program_id.get(), loc, &mut value); } sender.send(value).unwrap(); - } + }, WebGLCommand::GetUniformFloat4(program_id, loc, ref sender) => { let mut value = [0.; 4]; unsafe { ctx.gl().get_uniform_fv(program_id.get(), loc, &mut value); } sender.send(value).unwrap(); - } + }, WebGLCommand::GetUniformFloat9(program_id, loc, ref sender) => { let mut value = [0.; 9]; unsafe { ctx.gl().get_uniform_fv(program_id.get(), loc, &mut value); } sender.send(value).unwrap(); - } + }, WebGLCommand::GetUniformFloat16(program_id, loc, ref sender) => { let mut value = [0.; 16]; unsafe { ctx.gl().get_uniform_fv(program_id.get(), loc, &mut value); } sender.send(value).unwrap(); - } - WebGLCommand::InitializeFramebuffer { color, depth, stencil } => { - Self::initialize_framebuffer(ctx.gl(), state, color, depth, stencil) - } + }, + WebGLCommand::InitializeFramebuffer { + color, + depth, + stencil, + } => Self::initialize_framebuffer(ctx.gl(), state, color, depth, stencil), } // TODO: update test expectations in order to enable debug assertions @@ -1228,7 +1354,13 @@ impl WebGLImpl { } } } - assert_eq!(error, gl::NO_ERROR, "Unexpected WebGL error: 0x{:x} ({})", error, error); + assert_eq!( + error, + gl::NO_ERROR, + "Unexpected WebGL error: 0x{:x} ({})", + error, + error + ); } fn initialize_framebuffer( @@ -1242,7 +1374,11 @@ impl WebGLImpl { (color, gl::COLOR_BUFFER_BIT), (depth, gl::DEPTH_BUFFER_BIT), (stencil, gl::STENCIL_BUFFER_BIT), - ].iter().fold(0, |bits, &(enabled, bit)| bits | if enabled { bit } else { 0 }); + ] + .iter() + .fold(0, |bits, &(enabled, bit)| { + bits | if enabled { bit } else { 0 } + }); if state.scissor_test_enabled { gl.disable(gl::SCISSOR_TEST); @@ -1299,50 +1435,60 @@ impl WebGLImpl { linked: false, active_attribs: vec![].into(), active_uniforms: vec![].into(), - } + }; } let mut num_active_attribs = [0]; unsafe { - gl.get_program_iv(program.get(), gl::ACTIVE_ATTRIBUTES, &mut num_active_attribs); + gl.get_program_iv( + program.get(), + gl::ACTIVE_ATTRIBUTES, + &mut num_active_attribs, + ); } - let active_attribs = (0..num_active_attribs[0] as u32).map(|i| { - // FIXME(nox): This allocates strings sometimes for nothing - // and the gleam method keeps getting ACTIVE_ATTRIBUTE_MAX_LENGTH. - let (size, type_, name) = gl.get_active_attrib(program.get(), i); - let location = if name.starts_with("gl_") { - -1 - } else { - gl.get_attrib_location(program.get(), &name) - }; - ActiveAttribInfo { - name: from_name_in_compiled_shader(&name), - size, - type_, - location, - } - }).collect::<Vec<_>>().into(); + let active_attribs = (0..num_active_attribs[0] as u32) + .map(|i| { + // FIXME(nox): This allocates strings sometimes for nothing + // and the gleam method keeps getting ACTIVE_ATTRIBUTE_MAX_LENGTH. + let (size, type_, name) = gl.get_active_attrib(program.get(), i); + let location = if name.starts_with("gl_") { + -1 + } else { + gl.get_attrib_location(program.get(), &name) + }; + ActiveAttribInfo { + name: from_name_in_compiled_shader(&name), + size, + type_, + location, + } + }) + .collect::<Vec<_>>() + .into(); let mut num_active_uniforms = [0]; unsafe { gl.get_program_iv(program.get(), gl::ACTIVE_UNIFORMS, &mut num_active_uniforms); } - let active_uniforms = (0..num_active_uniforms[0] as u32).map(|i| { - // FIXME(nox): This allocates strings sometimes for nothing - // and the gleam method keeps getting ACTIVE_UNIFORM_MAX_LENGTH. - let (size, type_, mut name) = gl.get_active_uniform(program.get(), i); - let is_array = name.ends_with("[0]"); - if is_array { - // FIXME(nox): NLL - let len = name.len(); - name.truncate(len - 3); - } - ActiveUniformInfo { - base_name: from_name_in_compiled_shader(&name).into(), - size: if is_array { Some(size) } else { None }, - type_, - } - }).collect::<Vec<_>>().into(); + let active_uniforms = (0..num_active_uniforms[0] as u32) + .map(|i| { + // FIXME(nox): This allocates strings sometimes for nothing + // and the gleam method keeps getting ACTIVE_UNIFORM_MAX_LENGTH. + let (size, type_, mut name) = gl.get_active_uniform(program.get(), i); + let is_array = name.ends_with("[0]"); + if is_array { + // FIXME(nox): NLL + let len = name.len(); + name.truncate(len - 3); + } + ActiveUniformInfo { + base_name: from_name_in_compiled_shader(&name).into(), + size: if is_array { Some(size) } else { None }, + type_, + } + }) + .collect::<Vec<_>>() + .into(); ProgramLinkInfo { linked: true, @@ -1356,10 +1502,12 @@ impl WebGLImpl { chan.send(()).unwrap(); } - fn shader_precision_format(gl: &gl::Gl, - shader_type: u32, - precision_type: u32, - chan: &WebGLSender<(i32, i32, i32)>) { + fn shader_precision_format( + gl: &gl::Gl, + shader_type: u32, + precision_type: u32, + chan: &WebGLSender<(i32, i32, i32)>, + ) { let result = gl.get_shader_precision_format(shader_type, precision_type); chan.send(result).unwrap(); } @@ -1374,19 +1522,14 @@ impl WebGLImpl { target: u32, attachment: u32, pname: u32, - chan: &WebGLSender<i32> + chan: &WebGLSender<i32>, ) { let parameter = gl.get_framebuffer_attachment_parameter_iv(target, attachment, pname); chan.send(parameter).unwrap(); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 - fn get_renderbuffer_parameter( - gl: &gl::Gl, - target: u32, - pname: u32, - chan: &WebGLSender<i32> - ) { + fn get_renderbuffer_parameter(gl: &gl::Gl, target: u32, pname: u32, chan: &WebGLSender<i32>) { let parameter = gl.get_renderbuffer_parameter_iv(target, pname); chan.send(parameter).unwrap(); } @@ -1402,7 +1545,6 @@ impl WebGLImpl { chan.send(location).unwrap(); } - fn shader_info_log(gl: &gl::Gl, shader_id: WebGLShaderId, chan: &WebGLSender<String>) { let log = gl.get_shader_info_log(shader_id.get()); chan.send(log).unwrap(); @@ -1491,20 +1633,22 @@ impl WebGLImpl { } #[inline] - fn bind_framebuffer<Native: NativeGLContextMethods>(gl: &gl::Gl, - target: u32, - request: WebGLFramebufferBindingRequest, - ctx: &GLContext<Native>) { + fn bind_framebuffer<Native: NativeGLContextMethods>( + gl: &gl::Gl, + target: u32, + request: WebGLFramebufferBindingRequest, + ctx: &GLContext<Native>, + ) { let id = match request { WebGLFramebufferBindingRequest::Explicit(id) => id.get(), - WebGLFramebufferBindingRequest::Default => - ctx.borrow_draw_buffer().unwrap().get_framebuffer(), + WebGLFramebufferBindingRequest::Default => { + ctx.borrow_draw_buffer().unwrap().get_framebuffer() + }, }; gl.bind_framebuffer(target, id); } - #[inline] fn compile_shader(gl: &gl::Gl, shader_id: WebGLShaderId, source: &str) { gl.shader_source(shader_id.get(), &[source.as_bytes()]); diff --git a/components/canvas_traits/canvas.rs b/components/canvas_traits/canvas.rs index fad9679e483..4acdde707b3 100644 --- a/components/canvas_traits/canvas.rs +++ b/components/canvas_traits/canvas.rs @@ -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", } } diff --git a/components/canvas_traits/lib.rs b/components/canvas_traits/lib.rs index b2147d880e6..2c386b944ef 100644 --- a/components/canvas_traits/lib.rs +++ b/components/canvas_traits/lib.rs @@ -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; diff --git a/components/canvas_traits/webgl.rs b/components/canvas_traits/webgl.rs index bf66792832f..ac9bbb40315 100644 --- a/components/canvas_traits/webgl.rs +++ b/components/canvas_traits/webgl.rs @@ -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. diff --git a/components/channel/lib.rs b/components/channel/lib.rs index 87950fbe22a..df1c49a64c8 100644 --- a/components/channel/lib.rs +++ b/components/channel/lib.rs @@ -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, diff --git a/components/compositing/build.rs b/components/compositing/build.rs index 8a13f9632d7..54532276222 100644 --- a/components/compositing/build.rs +++ b/components/compositing/build.rs @@ -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(); diff --git a/components/compositing/compositor.rs b/components/compositing/compositor.rs index 175fbaf5ed8..c58fa02cd50 100644 --- a/components/compositing/compositor.rs +++ b/components/compositing/compositor.rs @@ -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); diff --git a/components/config/opts.rs b/components/config/opts.rs index 1c0ca14e6b0..47112e15bee 100644 --- a/components/config/opts.rs +++ b/components/config/opts.rs @@ -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") diff --git a/components/config/prefs.rs b/components/config/prefs.rs index 85b86adadd5..9a97bbdca04 100644 --- a/components/config/prefs.rs +++ b/components/config/prefs.rs @@ -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"); } } diff --git a/components/constellation/constellation.rs b/components/constellation/constellation.rs index 32aaa3a1106..4aef61c6cca 100644 --- a/components/constellation/constellation.rs +++ b/components/constellation/constellation.rs @@ -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 diff --git a/components/constellation/network_listener.rs b/components/constellation/network_listener.rs index 457a2021ced..71a8e66cb62 100644 --- a/components/constellation/network_listener.rs +++ b/components/constellation/network_listener.rs @@ -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), }); diff --git a/components/constellation/pipeline.rs b/components/constellation/pipeline.rs index 4a826189d53..118403451d6 100644 --- a/components/constellation/pipeline.rs +++ b/components/constellation/pipeline.rs @@ -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 { diff --git a/components/debugger/lib.rs b/components/debugger/lib.rs index 938e16906e3..c6ba6147826 100644 --- a/components/debugger/lib.rs +++ b/components/debugger/lib.rs @@ -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) } diff --git a/components/devtools/actors/console.rs b/components/devtools/actors/console.rs index 0f3b0e10ed2..1c7230c95a1 100644 --- a/components/devtools/actors/console.rs +++ b/components/devtools/actors/console.rs @@ -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(|_| ())? { diff --git a/components/devtools/actors/device.rs b/components/devtools/actors/device.rs index d35c2f5b845..27823db2ce5 100644 --- a/components/devtools/actors/device.rs +++ b/components/devtools/actors/device.rs @@ -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(), ), }], } } } - - diff --git a/components/devtools/actors/inspector.rs b/components/devtools/actors/inspector.rs index 4177d838571..a88651efd26 100644 --- a/components/devtools/actors/inspector.rs +++ b/components/devtools/actors/inspector.rs @@ -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, diff --git a/components/devtools/actors/network_event.rs b/components/devtools/actors/network_event.rs index beb7d3e50ba..02d77d33e90 100644 --- a/components/devtools/actors/network_event.rs +++ b/components/devtools/actors/network_event.rs @@ -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, diff --git a/components/devtools/actors/performance.rs b/components/devtools/actors/performance.rs index d9be7f04cb3..c68b04f93aa 100644 --- a/components/devtools/actors/performance.rs +++ b/components/devtools/actors/performance.rs @@ -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(), ), }], diff --git a/components/devtools/actors/stylesheets.rs b/components/devtools/actors/stylesheets.rs index e3038bc0b63..e4f1858f31b 100644 --- a/components/devtools/actors/stylesheets.rs +++ b/components/devtools/actors/stylesheets.rs @@ -30,4 +30,3 @@ impl StyleSheetsActor { StyleSheetsActor { name: name } } } - diff --git a/components/devtools/actors/timeline.rs b/components/devtools/actors/timeline.rs index 45c662988b5..d318321e27e 100644 --- a/components/devtools/actors/timeline.rs +++ b/components/devtools/actors/timeline.rs @@ -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()); diff --git a/components/devtools/lib.rs b/components/devtools/lib.rs index ef147ca953d..07c9cc2d825 100644 --- a/components/devtools/lib.rs +++ b/components/devtools/lib.rs @@ -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 { diff --git a/components/dom_struct/lib.rs b/components/dom_struct/lib.rs index 9c971665eed..bd3a9765e29 100644 --- a/components/dom_struct/lib.rs +++ b/components/dom_struct/lib.rs @@ -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"); } diff --git a/components/domobject_derive/lib.rs b/components/domobject_derive/lib.rs index 9bd2e4bf1a4..05308e53c65 100644 --- a/components/domobject_derive/lib.rs +++ b/components/domobject_derive/lib.rs @@ -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(); diff --git a/components/gfx/font.rs b/components/gfx/font.rs index 18a8ed21e11..086f8a253f5 100644 --- a/components/gfx/font.rs +++ b/components/gfx/font.rs @@ -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) } } diff --git a/components/gfx/font_cache_thread.rs b/components/gfx/font_cache_thread.rs index 94b2138d68f..669544004bb 100644 --- a/components/gfx/font_cache_thread.rs +++ b/components/gfx/font_cache_thread.rs @@ -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(); diff --git a/components/gfx/font_context.rs b/components/gfx/font_context.rs index e2f332e028c..655f165c38f 100644 --- a/components/gfx/font_context.rs +++ b/components/gfx/font_context.rs @@ -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 diff --git a/components/gfx/platform/freetype/android/font_list.rs b/components/gfx/platform/freetype/android/font_list.rs index ef4a0612f24..c156b630db0 100644 --- a/components/gfx/platform/freetype/android/font_list.rs +++ b/components/gfx/platform/freetype/android/font_list.rs @@ -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 { diff --git a/components/gfx/platform/freetype/font.rs b/components/gfx/platform/freetype/font.rs index 4ce38aa96d5..e0b34ae9be1 100644 --- a/components/gfx/platform/freetype/font.rs +++ b/components/gfx/platform/freetype/font.rs @@ -216,7 +216,8 @@ impl FontHandleMethods for FontHandle { } } else { FontStretchKeyword::Normal - }.compute(); + } + .compute(); FontStretch(NonNegative(percentage)) } diff --git a/components/gfx/platform/freetype/font_template.rs b/components/gfx/platform/freetype/font_template.rs index 674739b69ce..136f30f7337 100644 --- a/components/gfx/platform/freetype/font_template.rs +++ b/components/gfx/platform/freetype/font_template.rs @@ -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() } } diff --git a/components/gfx/platform/macos/font.rs b/components/gfx/platform/macos/font.rs index b9570da0760..9e6379db20f 100644 --- a/components/gfx/platform/macos/font.rs +++ b/components/gfx/platform/macos/font.rs @@ -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) }; diff --git a/components/gfx/platform/macos/font_template.rs b/components/gfx/platform/macos/font_template.rs index 85d134f45a2..9452266ba93 100644 --- a/components/gfx/platform/macos/font_template.rs +++ b/components/gfx/platform/macos/font_template.rs @@ -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!"); diff --git a/components/gfx/platform/windows/font.rs b/components/gfx/platform/windows/font.rs index a85c8383f5f..b0dd1273cf7 100644 --- a/components/gfx/platform/windows/font.rs +++ b/components/gfx/platform/windows/font.rs @@ -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 { diff --git a/components/gfx/platform/windows/font_template.rs b/components/gfx/platform/windows/font_template.rs index 49deeee736f..5a0cd14221d 100644 --- a/components/gfx/platform/windows/font_template.rs +++ b/components/gfx/platform/windows/font_template.rs @@ -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() } } diff --git a/components/gfx/tests/font_context.rs b/components/gfx/tests/font_context.rs index 8608f38329e..ba9e7afbdb0 100644 --- a/components/gfx/tests/font_context.rs +++ b/components/gfx/tests/font_context.rs @@ -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())) } diff --git a/components/gfx/tests/font_template.rs b/components/gfx/tests/font_template.rs index a6caea2f375..6e7fa8aea5a 100644 --- a/components/gfx/tests/font_template.rs +++ b/components/gfx/tests/font_template.rs @@ -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(); diff --git a/components/gfx/text/glyph.rs b/components/gfx/text/glyph.rs index 8e4c56e309b..5e37f3eb94c 100644 --- a/components/gfx/text/glyph.rs +++ b/components/gfx/text/glyph.rs @@ -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 diff --git a/components/gfx/text/text_run.rs b/components/gfx/text/text_run.rs index 7a6e6623b9c..e4871615fa0 100644 --- a/components/gfx/text/text_run.rs +++ b/components/gfx/text/text_run.rs @@ -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 diff --git a/components/layout/animation.rs b/components/layout/animation.rs index c9c83744361..9ce47e16d5a 100644 --- a/components/layout/animation.rs +++ b/components/layout/animation.rs @@ -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 diff --git a/components/layout/block.rs b/components/layout/block.rs index 76fb026ae0b..99ca7ada523 100644 --- a/components/layout/block.rs +++ b/components/layout/block.rs @@ -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()), ); } diff --git a/components/layout/construct.rs b/components/layout/construct.rs index b06e80bdd61..bfa6e878943 100644 --- a/components/layout/construct.rs +++ b/components/layout/construct.rs @@ -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))) diff --git a/components/layout/display_list/items.rs b/components/layout/display_list/items.rs index 13de1360737..0a85e0a290a 100644 --- a/components/layout/display_list/items.rs +++ b/components/layout/display_list/items.rs @@ -590,7 +590,8 @@ impl ClippingRegion { rect: complex.rect.translate(delta), radii: complex.radii, mode: complex.mode, - }).collect(), + }) + .collect(), } } diff --git a/components/layout/flex.rs b/components/layout/flex.rs index 3ccbb59a4b4..d8f0f167198 100644 --- a/components/layout/flex.rs +++ b/components/layout/flex.rs @@ -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); diff --git a/components/layout/fragment.rs b/components/layout/fragment.rs index 7774a4a9014..cb781484e63 100644 --- a/components/layout/fragment.rs +++ b/components/layout/fragment.rs @@ -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, diff --git a/components/layout/inline.rs b/components/layout/inline.rs index 8093f3c9eeb..7f52c817dd1 100644 --- a/components/layout/inline.rs +++ b/components/layout/inline.rs @@ -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()), ) } } diff --git a/components/layout/list_item.rs b/components/layout/list_item.rs index 002651918f3..08473cb89ef 100644 --- a/components/layout/list_item.rs +++ b/components/layout/list_item.rs @@ -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()), ); } } diff --git a/components/layout/model.rs b/components/layout/model.rs index c33c21a49b9..0c10159f480 100644 --- a/components/layout/model.rs +++ b/components/layout/model.rs @@ -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. diff --git a/components/layout/multicol.rs b/components/layout/multicol.rs index 4344ffa531b..79f25482d9e 100644 --- a/components/layout/multicol.rs +++ b/components/layout/multicol.rs @@ -164,7 +164,8 @@ impl Flow for MulticolFlow { LogicalSize::from_physical( self.block_flow.base.writing_mode, ctx.shared_context().viewport_size(), - ).block + ) + .block } }, }); diff --git a/components/layout/query.rs b/components/layout/query.rs index eb94e9c0449..95623c7a98b 100644 --- a/components/layout/query.rs +++ b/components/layout/query.rs @@ -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 { diff --git a/components/layout/table_cell.rs b/components/layout/table_cell.rs index e94ecba71dd..51442f2f832 100644 --- a/components/layout/table_cell.rs +++ b/components/layout/table_cell.rs @@ -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 diff --git a/components/layout/table_wrapper.rs b/components/layout/table_wrapper.rs index 0d1596d9c85..cb4a033298c 100644 --- a/components/layout/table_wrapper.rs +++ b/components/layout/table_wrapper.rs @@ -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 diff --git a/components/layout_thread/dom_wrapper.rs b/components/layout_thread/dom_wrapper.rs index bd760204884..4eac43a6a32 100644 --- a/components/layout_thread/dom_wrapper.rs +++ b/components/layout_thread/dom_wrapper.rs @@ -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> { diff --git a/components/layout_thread/lib.rs b/components/layout_thread/lib.rs index ad0e7cac3ef..ca5bd40a313 100644 --- a/components/layout_thread/lib.rs +++ b/components/layout_thread/lib.rs @@ -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() { diff --git a/components/malloc_size_of_derive/lib.rs b/components/malloc_size_of_derive/lib.rs index 59446131508..dc0d34af88f 100644 --- a/components/malloc_size_of_derive/lib.rs +++ b/components/malloc_size_of_derive/lib.rs @@ -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(); diff --git a/components/net/cookie_storage.rs b/components/net/cookie_storage.rs index 8959b6d97ac..274af9068a5 100644 --- a/components/net/cookie_storage.rs +++ b/components/net/cookie_storage.rs @@ -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)); } diff --git a/components/net/fetch/methods.rs b/components/net/fetch/methods.rs index 0e744e0de26..a0ca76ff802 100644 --- a/components/net/fetch/methods.rs +++ b/components/net/fetch/methods.rs @@ -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> diff --git a/components/net/http_loader.rs b/components/net/http_loader.rs index 10fccc3561b..2ca55d4ffa0 100644 --- a/components/net/http_loader.rs +++ b/components/net/http_loader.rs @@ -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 diff --git a/components/net/mime_classifier.rs b/components/net/mime_classifier.rs index 7dd5b61bc97..e6716789033 100644 --- a/components/net/mime_classifier.rs +++ b/components/net/mime_classifier.rs @@ -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 { diff --git a/components/net/tests/fetch.rs b/components/net/tests/fetch.rs index aba99c2fdd4..a11d068e9ce 100644 --- a/components/net/tests/fetch.rs +++ b/components/net/tests/fetch.rs @@ -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] diff --git a/components/net/tests/hsts.rs b/components/net/tests/hsts.rs index a16c104f061..1903aec1af4 100644 --- a/components/net/tests/hsts.rs +++ b/components/net/tests/hsts.rs @@ -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, diff --git a/components/net/tests/http_loader.rs b/components/net/tests/http_loader.rs index 545716789fe..ee2c12b9981 100644 --- a/components/net/tests/http_loader.rs +++ b/components/net/tests/http_loader.rs @@ -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(); } diff --git a/components/pixels/lib.rs b/components/pixels/lib.rs index de29e5fa2ee..806b854fda2 100644 --- a/components/pixels/lib.rs +++ b/components/pixels/lib.rs @@ -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() diff --git a/components/profile/mem.rs b/components/profile/mem.rs index 83756722e61..14c99654086 100644 --- a/components/profile/mem.rs +++ b/components/profile/mem.rs @@ -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. diff --git a/components/profile/time.rs b/components/profile/time.rs index 2738e21c198..75ce0f85fba 100644 --- a/components/profile/time.rs +++ b/components/profile/time.rs @@ -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) + })); } } }, diff --git a/components/profile_traits/ipc.rs b/components/profile_traits/ipc.rs index 1aec4162522..abe03201f0d 100644 --- a/components/profile_traits/ipc.rs +++ b/components/profile_traits/ipc.rs @@ -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, diff --git a/components/profile_traits/mem.rs b/components/profile_traits/mem.rs index 29776e6bc3b..69279c62f71 100644 --- a/components/profile_traits/mem.rs +++ b/components/profile_traits/mem.rs @@ -174,7 +174,8 @@ impl Reporter { self.0 .send(ReporterRequest { reports_channel: reports_chan, - }).unwrap() + }) + .unwrap() } } diff --git a/components/remutex/tests/smoke.rs b/components/remutex/tests/smoke.rs index 31ac9d48402..743bdfec167 100644 --- a/components/remutex/tests/smoke.rs +++ b/components/remutex/tests/smoke.rs @@ -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); diff --git a/components/script/body.rs b/components/script/body.rs index 7929dba14bb..60ab96fd1b0 100644 --- a/components/script/body.rs +++ b/components/script/body.rs @@ -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, _) diff --git a/components/script/build.rs b/components/script/build.rs index 6bce87d65b5..0abb25ef24a 100644 --- a/components/script/build.rs +++ b/components/script/build.rs @@ -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(); } diff --git a/components/script/devtools.rs b/components/script/devtools.rs index d0409cf5fbc..feb90a1982f 100644 --- a/components/script/devtools.rs +++ b/components/script/devtools.rs @@ -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 { diff --git a/components/script/document_loader.rs b/components/script/document_loader.rs index f2ef4251fed..efde3f33a3f 100644 --- a/components/script/document_loader.rs +++ b/components/script/document_loader.rs @@ -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. diff --git a/components/script/dom/analysernode.rs b/components/script/dom/analysernode.rs index 88cee14c3a1..b4c172f9865 100644 --- a/components/script/dom/analysernode.rs +++ b/components/script/dom/analysernode.rs @@ -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); - - if options.fftSize > 32768 || options.fftSize < 32 || - (options.fftSize & (options.fftSize - 1) != 0) { - return Err(Error::IndexSize) + 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.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(()) } } - diff --git a/components/script/dom/audiobuffer.rs b/components/script/dom/audiobuffer.rs index 2ebdfee5377..92c53da3e9d 100644 --- a/components/script/dom/audiobuffer.rs +++ b/components/script/dom/audiobuffer.rs @@ -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); diff --git a/components/script/dom/baseaudiocontext.rs b/components/script/dom/baseaudiocontext.rs index 95ad60314ee..5958eb14b14 100644 --- a/components/script/dom/baseaudiocontext.rs +++ b/components/script/dom/baseaudiocontext.rs @@ -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 { diff --git a/components/script/dom/bindings/settings_stack.rs b/components/script/dom/bindings/settings_stack.rs index da26bff3db7..aee67a3da97 100644 --- a/components/script/dom/bindings/settings_stack.rs +++ b/components/script/dom/bindings/settings_stack.rs @@ -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. diff --git a/components/script/dom/bindings/trace.rs b/components/script/dom/bindings/trace.rs index 669f9481fb5..d067fb1a9f7 100644 --- a/components/script/dom/bindings/trace.rs +++ b/components/script/dom/bindings/trace.rs @@ -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); diff --git a/components/script/dom/bindings/utils.rs b/components/script/dom/bindings/utils.rs index 8579103afd5..9ad2122430f 100644 --- a/components/script/dom/bindings/utils.rs +++ b/components/script/dom/bindings/utils.rs @@ -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 } diff --git a/components/script/dom/biquadfilternode.rs b/components/script/dom/biquadfilternode.rs index ca74d42f2c6..079c2c97395 100644 --- a/components/script/dom/biquadfilternode.rs +++ b/components/script/dom/biquadfilternode.rs @@ -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(), } } } diff --git a/components/script/dom/bluetooth.rs b/components/script/dom/bluetooth.rs index b59c4bf49cd..c5985ac0964 100644 --- a/components/script/dom/bluetooth.rs +++ b/components/script/dom/bluetooth.rs @@ -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) => (), diff --git a/components/script/dom/bluetoothdevice.rs b/components/script/dom/bluetoothdevice.rs index 9455f3bb460..0cd5320ef08 100644 --- a/components/script/dom/bluetoothdevice.rs +++ b/components/script/dom/bluetoothdevice.rs @@ -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; } diff --git a/components/script/dom/bluetoothremotegattcharacteristic.rs b/components/script/dom/bluetoothremotegattcharacteristic.rs index dbeddd1ab5b..847ad88fe7f 100644 --- a/components/script/dom/bluetoothremotegattcharacteristic.rs +++ b/components/script/dom/bluetoothremotegattcharacteristic.rs @@ -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; } diff --git a/components/script/dom/bluetoothremotegattdescriptor.rs b/components/script/dom/bluetoothremotegattdescriptor.rs index 876f297f656..7ed43e9f336 100644 --- a/components/script/dom/bluetoothremotegattdescriptor.rs +++ b/components/script/dom/bluetoothremotegattdescriptor.rs @@ -166,7 +166,8 @@ impl BluetoothRemoteGATTDescriptorMethods for BluetoothRemoteGATTDescriptor { self.get_instance_id(), vec, sender, - )).unwrap(); + )) + .unwrap(); return p; } } diff --git a/components/script/dom/bluetoothremotegattserver.rs b/components/script/dom/bluetoothremotegattserver.rs index 64b4a9032a7..29ed938937b 100644 --- a/components/script/dom/bluetoothremotegattserver.rs +++ b/components/script/dom/bluetoothremotegattserver.rs @@ -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; } diff --git a/components/script/dom/canvasrenderingcontext2d.rs b/components/script/dom/canvasrenderingcontext2d.rs index 817250408d2..5ebc2eb98e1 100644 --- a/components/script/dom/canvasrenderingcontext2d.rs +++ b/components/script/dom/canvasrenderingcontext2d.rs @@ -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(); diff --git a/components/script/dom/cssstyledeclaration.rs b/components/script/dom/cssstyledeclaration.rs index 455bcbdd08f..1fc7f5b6961 100644 --- a/components/script/dom/cssstyledeclaration.rs +++ b/components/script/dom/cssstyledeclaration.rs @@ -157,7 +157,8 @@ impl CSSStyleOwner { .style_stylesheet() .contents .url_data - .read()).clone(), + .read()) + .clone(), } } } diff --git a/components/script/dom/csssupportsrule.rs b/components/script/dom/csssupportsrule.rs index 17005ce0aec..4c122595bb5 100644 --- a/components/script/dom/csssupportsrule.rs +++ b/components/script/dom/csssupportsrule.rs @@ -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(); diff --git a/components/script/dom/customelementregistry.rs b/components/script/dom/customelementregistry.rs index 8a38a98dc49..1fdf1cfc4a1 100644 --- a/components/script/dom/customelementregistry.rs +++ b/components/script/dom/customelementregistry.rs @@ -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( diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index f880d09f11d..f6fad393fc3 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -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(()) } diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index 9ce096e2e65..dbbd1d1c89e 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -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(()); } diff --git a/components/script/dom/dommatrix.rs b/components/script/dom/dommatrix.rs index 2baf094e869..12fcdc5781d 100644 --- a/components/script/dom/dommatrix.rs +++ b/components/script/dom/dommatrix.rs @@ -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))) } diff --git a/components/script/dom/element.rs b/components/script/dom/element.rs index 2600f0cc575..33654ea5149 100644 --- a/components/script/dom/element.rs +++ b/components/script/dom/element.rs @@ -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()) } diff --git a/components/script/dom/eventsource.rs b/components/script/dom/eventsource.rs index cd2136c72fa..a34042263ce 100644 --- a/components/script/dom/eventsource.rs +++ b/components/script/dom/eventsource.rs @@ -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(); } } diff --git a/components/script/dom/eventtarget.rs b/components/script/dom/eventtarget.rs index 1b03a2ac8ff..81e8a350490 100644 --- a/components/script/dom/eventtarget.rs +++ b/components/script/dom/eventtarget.rs @@ -302,7 +302,8 @@ impl EventListeners { } else { None } - }).collect() + }) + .collect() } fn has_listeners(&self) -> bool { diff --git a/components/script/dom/filereader.rs b/components/script/dom/filereader.rs index 885ff56901d..000616d5ced 100644 --- a/components/script/dom/filereader.rs +++ b/components/script/dom/filereader.rs @@ -465,7 +465,8 @@ impl FileReader { task_source, canceller, ) - }).expect("Thread spawning failed"); + }) + .expect("Thread spawning failed"); Ok(()) } diff --git a/components/script/dom/filereadersync.rs b/components/script/dom/filereadersync.rs index dab475c86ef..3b9608863ce 100644 --- a/components/script/dom/filereadersync.rs +++ b/components/script/dom/filereadersync.rs @@ -100,7 +100,8 @@ impl FileReaderSyncMethods for FileReaderSync { cx, CreateWith::Slice(&blob_contents), array_buffer.handle_mut() - ).is_ok() + ) + .is_ok() ); Ok(NonNull::new_unchecked(array_buffer.get())) diff --git a/components/script/dom/formdata.rs b/components/script/dom/formdata.rs index 0bb77306bce..ca3f83cbb91 100644 --- a/components/script/dom/formdata.rs +++ b/components/script/dom/formdata.rs @@ -135,7 +135,8 @@ impl FormDataMethods for FormData { FormDatumValue::File(ref b) => { FileOrUSVString::File(DomRoot::from_ref(&*b)) }, - }).collect() + }) + .collect() }) } diff --git a/components/script/dom/gainnode.rs b/components/script/dom/gainnode.rs index 5d8639b2ba8..c3e39e5bcfe 100644 --- a/components/script/dom/gainnode.rs +++ b/components/script/dom/gainnode.rs @@ -48,9 +48,9 @@ impl GainNode { 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 ); Ok(GainNode { node, diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 9e06a707fa3..4c40d11a044 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -252,13 +252,18 @@ impl GlobalScope { } pub fn add_uncaught_rejection(&self, rejection: HandleObject) { - self.uncaught_rejections.borrow_mut().push(Heap::boxed(rejection.get())); + self.uncaught_rejections + .borrow_mut() + .push(Heap::boxed(rejection.get())); } pub fn remove_uncaught_rejection(&self, rejection: HandleObject) { let mut uncaught_rejections = self.uncaught_rejections.borrow_mut(); - if let Some(index) = uncaught_rejections.iter().position(|promise| *promise == Heap::boxed(rejection.get())) { + if let Some(index) = uncaught_rejections + .iter() + .position(|promise| *promise == Heap::boxed(rejection.get())) + { uncaught_rejections.remove(index); } } @@ -268,13 +273,18 @@ impl GlobalScope { } pub fn add_consumed_rejection(&self, rejection: HandleObject) { - self.consumed_rejections.borrow_mut().push(Heap::boxed(rejection.get())); + self.consumed_rejections + .borrow_mut() + .push(Heap::boxed(rejection.get())); } pub fn remove_consumed_rejection(&self, rejection: HandleObject) { let mut consumed_rejections = self.consumed_rejections.borrow_mut(); - if let Some(index) = consumed_rejections.iter().position(|promise| *promise == Heap::boxed(rejection.get())) { + if let Some(index) = consumed_rejections + .iter() + .position(|promise| *promise == Heap::boxed(rejection.get())) + { consumed_rejections.remove(index); } } @@ -639,11 +649,10 @@ impl GlobalScope { /// Perform a microtask checkpoint. pub fn perform_a_microtask_checkpoint(&self) { - self.microtask_queue - .checkpoint( - |_| Some(DomRoot::from_ref(self)), - vec![DomRoot::from_ref(self)] - ); + self.microtask_queue.checkpoint( + |_| Some(DomRoot::from_ref(self)), + vec![DomRoot::from_ref(self)], + ); } /// Enqueue a microtask for subsequent execution. diff --git a/components/script/dom/headers.rs b/components/script/dom/headers.rs index 5ce4e84e49e..cebc78ba0e0 100644 --- a/components/script/dom/headers.rs +++ b/components/script/dom/headers.rs @@ -87,14 +87,19 @@ impl HeadersMethods for Headers { } // Step 7 let mut combined_value: Vec<u8> = vec![]; - if let Some(v) = self.header_list.borrow().get(HeaderName::from_str(&valid_name).unwrap()) { + if let Some(v) = self + .header_list + .borrow() + .get(HeaderName::from_str(&valid_name).unwrap()) + { combined_value = v.as_bytes().to_vec(); combined_value.push(b','); } combined_value.extend(valid_value.iter().cloned()); - self.header_list - .borrow_mut() - .insert(HeaderName::from_str(&valid_name).unwrap(), HeaderValue::from_bytes(&combined_value).unwrap()); + self.header_list.borrow_mut().insert( + HeaderName::from_str(&valid_name).unwrap(), + HeaderValue::from_bytes(&combined_value).unwrap(), + ); Ok(()) } @@ -129,9 +134,11 @@ impl HeadersMethods for Headers { fn Get(&self, name: ByteString) -> Fallible<Option<ByteString>> { // Step 1 let valid_name = validate_name(name)?; - Ok(self.header_list.borrow().get(HeaderName::from_str(&valid_name).unwrap()).map(|v| { - ByteString::new(v.as_bytes().to_vec()) - })) + Ok(self + .header_list + .borrow() + .get(HeaderName::from_str(&valid_name).unwrap()) + .map(|v| ByteString::new(v.as_bytes().to_vec()))) } // https://fetch.spec.whatwg.org/#dom-headers-has @@ -169,9 +176,10 @@ impl HeadersMethods for Headers { } // Step 7 // https://fetch.spec.whatwg.org/#concept-header-list-set - self.header_list - .borrow_mut() - .insert(HeaderName::from_str(&valid_name).unwrap(), HeaderValue::from_bytes(&valid_value).unwrap()); + self.header_list.borrow_mut().insert( + HeaderName::from_str(&valid_name).unwrap(), + HeaderValue::from_bytes(&valid_value).unwrap(), + ); Ok(()) } } @@ -185,7 +193,7 @@ impl Headers { for (name, value) in h.header_list.borrow().iter() { self.Append( ByteString::new(Vec::from(name.as_str())), - ByteString::new(Vec::from(value.to_str().unwrap().as_bytes())) + ByteString::new(Vec::from(value.to_str().unwrap().as_bytes())), )?; } Ok(()) @@ -251,7 +259,10 @@ impl Headers { // https://fetch.spec.whatwg.org/#concept-header-extract-mime-type pub fn extract_mime_type(&self) -> Vec<u8> { - self.header_list.borrow().get(header::CONTENT_TYPE).map_or(vec![], |v| v.as_bytes().to_owned()) + self.header_list + .borrow() + .get(header::CONTENT_TYPE) + .map_or(vec![], |v| v.as_bytes().to_owned()) } pub fn sort_header_list(&self) -> Vec<(String, String)> { @@ -299,14 +310,12 @@ fn is_cors_safelisted_request_content_type(value: &[u8]) -> bool { let value_mime_result: Result<Mime, _> = value_string.parse(); match value_mime_result { Err(_) => false, - Ok(value_mime) => { - match (value_mime.type_(), value_mime.subtype()) { - (mime::APPLICATION, mime::WWW_FORM_URLENCODED) | - (mime::MULTIPART, mime::FORM_DATA) | - (mime::TEXT, mime::PLAIN) => true, - _ => false, - } - } + Ok(value_mime) => match (value_mime.type_(), value_mime.subtype()) { + (mime::APPLICATION, mime::WWW_FORM_URLENCODED) | + (mime::MULTIPART, mime::FORM_DATA) | + (mime::TEXT, mime::PLAIN) => true, + _ => false, + }, } } diff --git a/components/script/dom/htmlbuttonelement.rs b/components/script/dom/htmlbuttonelement.rs index c7e28a672c1..e75da65e618 100755 --- a/components/script/dom/htmlbuttonelement.rs +++ b/components/script/dom/htmlbuttonelement.rs @@ -29,7 +29,7 @@ use std::cell::Cell; use std::default::Default; use style::element_state::ElementState; -#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq )] +#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)] enum ButtonType { Submit, Reset, diff --git a/components/script/dom/htmlcanvaselement.rs b/components/script/dom/htmlcanvaselement.rs index af5029a9015..db9b5e8eda5 100644 --- a/components/script/dom/htmlcanvaselement.rs +++ b/components/script/dom/htmlcanvaselement.rs @@ -302,7 +302,7 @@ impl HTMLCanvasElement { // TODO: add a method in WebGL2RenderingContext to get the pixels. return None; }, - None => vec![0; size.height as usize * size.width as usize * 4] + None => vec![0; size.height as usize * size.width as usize * 4], }; Some((data, size)) diff --git a/components/script/dom/htmlelement.rs b/components/script/dom/htmlelement.rs index 5b29b8957f3..73fb7feab79 100644 --- a/components/script/dom/htmlelement.rs +++ b/components/script/dom/htmlelement.rs @@ -672,7 +672,8 @@ impl HTMLElement { .filter_map(|attr| { let raw_name = attr.local_name(); to_camel_case(&raw_name) - }).collect() + }) + .collect() } // https://html.spec.whatwg.org/multipage/#dom-lfe-labels @@ -684,16 +685,17 @@ impl HTMLElement { // Traverse ancestors for implicitly associated <label> elements // https://html.spec.whatwg.org/multipage/#the-label-element:attr-label-for-4 - let ancestors = self.upcast::<Node>() - .ancestors() - .filter_map(DomRoot::downcast::<HTMLElement>) - // If we reach a labelable element, we have a guarantee no ancestors above it - // will be a label for this HTMLElement - .take_while(|elem| !elem.is_labelable_element()) - .filter_map(DomRoot::downcast::<HTMLLabelElement>) - .filter(|elem| !elem.upcast::<Element>().has_attribute(&local_name!("for"))) - .filter(|elem| elem.first_labelable_descendant().r() == Some(self)) - .map(DomRoot::upcast::<Node>); + let ancestors = self + .upcast::<Node>() + .ancestors() + .filter_map(DomRoot::downcast::<HTMLElement>) + // If we reach a labelable element, we have a guarantee no ancestors above it + // will be a label for this HTMLElement + .take_while(|elem| !elem.is_labelable_element()) + .filter_map(DomRoot::downcast::<HTMLLabelElement>) + .filter(|elem| !elem.upcast::<Element>().has_attribute(&local_name!("for"))) + .filter(|elem| elem.first_labelable_descendant().r() == Some(self)) + .map(DomRoot::upcast::<Node>); let id = element.Id(); let id = match &id as &str { diff --git a/components/script/dom/htmlformelement.rs b/components/script/dom/htmlformelement.rs index 848822126c8..d5331cfc356 100755 --- a/components/script/dom/htmlformelement.rs +++ b/components/script/dom/htmlformelement.rs @@ -382,15 +382,25 @@ impl HTMLFormElement { // https://html.spec.whatwg.org/multipage/#submit-dialog }, // https://html.spec.whatwg.org/multipage/#submit-mutate-action - ("http", FormMethod::FormGet) | ("https", FormMethod::FormGet) | ("data", FormMethod::FormGet) => { - load_data.headers.typed_insert(ContentType::from(mime::APPLICATION_WWW_FORM_URLENCODED)); + ("http", FormMethod::FormGet) | + ("https", FormMethod::FormGet) | + ("data", FormMethod::FormGet) => { + load_data + .headers + .typed_insert(ContentType::from(mime::APPLICATION_WWW_FORM_URLENCODED)); self.mutate_action_url(&mut form_data, load_data, encoding, &target_window); }, // https://html.spec.whatwg.org/multipage/#submit-body ("http", FormMethod::FormPost) | ("https", FormMethod::FormPost) => { load_data.method = Method::POST; - self.submit_entity_body(&mut form_data, load_data, enctype, encoding, &target_window); - } + self.submit_entity_body( + &mut form_data, + load_data, + enctype, + encoding, + &target_window, + ); + }, // https://html.spec.whatwg.org/multipage/#submit-get-action ("file", _) | ("about", _) | @@ -445,7 +455,9 @@ impl HTMLFormElement { let bytes = match enctype { FormEncType::UrlEncoded => { let charset = encoding.name(); - load_data.headers.typed_insert(ContentType::from(mime::APPLICATION_WWW_FORM_URLENCODED)); + load_data + .headers + .typed_insert(ContentType::from(mime::APPLICATION_WWW_FORM_URLENCODED)); self.set_encoding_override(load_data.url.as_mut_url().query_pairs_mut()) .clear() @@ -458,12 +470,16 @@ impl HTMLFormElement { load_data.url.query().unwrap_or("").to_string().into_bytes() }, FormEncType::FormDataEncoded => { - let mime: Mime = format!("multipart/form-data; boundary={}", boundary).parse().unwrap(); + let mime: Mime = format!("multipart/form-data; boundary={}", boundary) + .parse() + .unwrap(); load_data.headers.typed_insert(ContentType::from(mime)); encode_multipart_form_data(form_data, boundary, encoding) }, FormEncType::TextPlainEncoded => { - load_data.headers.typed_insert(ContentType::from(mime::TEXT_PLAIN)); + load_data + .headers + .typed_insert(ContentType::from(mime::TEXT_PLAIN)); self.encode_plaintext(form_data).into_bytes() }, }; @@ -555,7 +571,8 @@ impl HTMLFormElement { } else { None } - }).collect::<Vec<FormSubmittableElement>>(); + }) + .collect::<Vec<FormSubmittableElement>>(); // Step 4 if invalid_controls.is_empty() { return Ok(()); @@ -571,7 +588,8 @@ impl HTMLFormElement { return Some(field); } None - }).collect::<Vec<FormSubmittableElement>>(); + }) + .collect::<Vec<FormSubmittableElement>>(); // Step 7 Err(unhandled_invalid_controls) } @@ -1239,17 +1257,30 @@ pub fn encode_multipart_form_data( }, FormDatumValue::File(ref f) => { let extra = if charset.to_lowercase() == "utf-8" { - format!("filename=\"{}\"", String::from_utf8(f.name().as_bytes().into()).unwrap()) + format!( + "filename=\"{}\"", + String::from_utf8(f.name().as_bytes().into()).unwrap() + ) } else { - format!("filename*=\"{}\"''{}", charset, http_percent_encode(f.name().as_bytes())) + format!( + "filename*=\"{}\"''{}", + charset, + http_percent_encode(f.name().as_bytes()) + ) }; let content_disposition = format!("form-data; name=\"{}\"; {}", entry.name, extra); // https://tools.ietf.org/html/rfc7578#section-4.4 - let content_type: Mime = f.upcast::<Blob>().Type().parse().unwrap_or(mime::TEXT_PLAIN); - let mut type_bytes = format!("Content-Disposition: {}\r\ncontent-type: {}\r\n\r\n", - content_disposition, - content_type).into_bytes(); + let content_type: Mime = f + .upcast::<Blob>() + .Type() + .parse() + .unwrap_or(mime::TEXT_PLAIN); + let mut type_bytes = format!( + "Content-Disposition: {}\r\ncontent-type: {}\r\n\r\n", + content_disposition, content_type + ) + .into_bytes(); result.append(&mut type_bytes); let mut bytes = f.upcast::<Blob>().get_bytes().unwrap_or(vec![]); diff --git a/components/script/dom/htmliframeelement.rs b/components/script/dom/htmliframeelement.rs index 2fe6ccb1537..5e835f1122c 100644 --- a/components/script/dom/htmliframeelement.rs +++ b/components/script/dom/htmliframeelement.rs @@ -97,7 +97,8 @@ impl HTMLIFrameElement { } else { document_from_node(self).base_url().join(&url).ok() } - }).unwrap_or_else(|| ServoUrl::parse("about:blank").unwrap()) + }) + .unwrap_or_else(|| ServoUrl::parse("about:blank").unwrap()) } pub fn navigate_or_reload_child_browsing_context( diff --git a/components/script/dom/htmlimageelement.rs b/components/script/dom/htmlimageelement.rs index 89f6eb66e25..8234983b936 100644 --- a/components/script/dom/htmlimageelement.rs +++ b/components/script/dom/htmlimageelement.rs @@ -566,12 +566,11 @@ impl HTMLImageElement { // TODO Handle unsupported mime type let mime = x.value().parse::<Mime>(); match mime { - Ok(m) => - match m.type_() { - mime::IMAGE => (), - _ => continue - }, - _ => continue + Ok(m) => match m.type_() { + mime::IMAGE => (), + _ => continue, + }, + _ => continue, } } @@ -1274,9 +1273,13 @@ impl HTMLImageElement { } pub fn same_origin(&self, origin: &MutableOrigin) -> bool { - self.current_request.borrow_mut().final_url.as_ref().map_or(false, |url| { - url.scheme() == "data" || url.origin().same_origin(origin) - }) + self.current_request + .borrow_mut() + .final_url + .as_ref() + .map_or(false, |url| { + url.scheme() == "data" || url.origin().same_origin(origin) + }) } } @@ -1353,10 +1356,11 @@ impl LayoutHTMLImageElementHelpers for LayoutDom<HTMLImageElement> { #[allow(unsafe_code)] unsafe fn image_data(&self) -> (Option<Arc<Image>>, Option<ImageMetadata>) { - let current_request = (*self.unsafe_get()) - .current_request - .borrow_for_layout(); - (current_request.image.clone(), current_request.metadata.clone()) + let current_request = (*self.unsafe_get()).current_request.borrow_for_layout(); + ( + current_request.image.clone(), + current_request.metadata.clone(), + ) } #[allow(unsafe_code)] @@ -1502,11 +1506,11 @@ impl HTMLImageElementMethods for HTMLImageElement { let elem = self.upcast::<Element>(); let srcset_absent = !elem.has_attribute(&local_name!("srcset")); if !elem.has_attribute(&local_name!("src")) && srcset_absent { - return true + return true; } let src = elem.get_string_attribute(&local_name!("src")); if srcset_absent && src.is_empty() { - return true + return true; } let request = self.current_request.borrow(); let request_state = request.state; @@ -1582,8 +1586,10 @@ impl VirtualMethods for HTMLImageElement { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); match attr.local_name() { - &local_name!("src") | &local_name!("srcset") | - &local_name!("width") | &local_name!("crossorigin") | + &local_name!("src") | + &local_name!("srcset") | + &local_name!("width") | + &local_name!("crossorigin") | &local_name!("sizes") => self.update_the_image_data(), _ => {}, } diff --git a/components/script/dom/htmlinputelement.rs b/components/script/dom/htmlinputelement.rs index ae4dc5c7eef..ae575120df6 100755 --- a/components/script/dom/htmlinputelement.rs +++ b/components/script/dom/htmlinputelement.rs @@ -944,8 +944,10 @@ impl HTMLInputElement { }, // Step 3.1: it's the "Checkbox" or "Radio Button" and whose checkedness is false. - InputType::Radio | InputType::Checkbox => if !self.Checked() || name.is_empty() { - return vec![]; + InputType::Radio | InputType::Checkbox => { + if !self.Checked() || name.is_empty() { + return vec![]; + } }, InputType::File => { @@ -981,8 +983,10 @@ impl HTMLInputElement { InputType::Image => return vec![], // Unimplemented // Step 3.1: it's not the "Image Button" and doesn't have a name attribute. - _ => if name.is_empty() { - return vec![]; + _ => { + if name.is_empty() { + return vec![]; + } }, } @@ -1280,7 +1284,8 @@ impl VirtualMethods for HTMLInputElement { .map_or(DOMString::from(""), |a| { DOMString::from(a.summarize().value) }), - ).expect( + ) + .expect( "Failed to set input value on type change to ValueMode::Value.", ); self.value_dirty.set(false); diff --git a/components/script/dom/htmlmediaelement.rs b/components/script/dom/htmlmediaelement.rs index 010795a0b80..eb8de36e8ab 100644 --- a/components/script/dom/htmlmediaelement.rs +++ b/components/script/dom/htmlmediaelement.rs @@ -690,7 +690,10 @@ impl HTMLMediaElement { }; let mut headers = HeaderMap::new(); // FIXME(eijebong): Use typed headers once we have a constructor for the range header - headers.insert(header::RANGE, HeaderValue::from_str(&format!("bytes={}-", offset.unwrap_or(0))).unwrap()); + headers.insert( + header::RANGE, + HeaderValue::from_str(&format!("bytes={}-", offset.unwrap_or(0))).unwrap(), + ); let request = RequestInit { url: self.resource_url.borrow().as_ref().unwrap().clone(), headers, @@ -1139,7 +1142,8 @@ impl HTMLMediaElement { if self.is::<HTMLVideoElement>() { let video_elem = self.downcast::<HTMLVideoElement>().unwrap(); if video_elem.get_video_width() != metadata.width || - video_elem.get_video_height() != metadata.height { + video_elem.get_video_height() != metadata.height + { video_elem.set_video_width(metadata.width); video_elem.set_video_height(metadata.height); let window = window_from_node(self); @@ -1272,12 +1276,12 @@ impl HTMLMediaElementMethods for HTMLMediaElement { // https://html.spec.whatwg.org/multipage/#dom-navigator-canplaytype fn CanPlayType(&self, type_: DOMString) -> CanPlayTypeResult { match type_.parse::<Mime>() { - Ok(ref mime) if (mime.type_() == mime::APPLICATION && mime.subtype() == mime::OCTET_STREAM) => { - CanPlayTypeResult::_empty - }, - Err(_) => { + Ok(ref mime) + if (mime.type_() == mime::APPLICATION && mime.subtype() == mime::OCTET_STREAM) => + { CanPlayTypeResult::_empty }, + Err(_) => CanPlayTypeResult::_empty, _ => CanPlayTypeResult::Maybe, } } diff --git a/components/script/dom/htmlscriptelement.rs b/components/script/dom/htmlscriptelement.rs index 2b941b909dc..dca27b6b7cd 100644 --- a/components/script/dom/htmlscriptelement.rs +++ b/components/script/dom/htmlscriptelement.rs @@ -184,7 +184,8 @@ impl FetchResponseListener for ScriptContext { .and_then(|m| match m.status { Some((c, _)) => Some(c), _ => None, - }).unwrap_or(0); + }) + .unwrap_or(0); self.status = match status_code { 0 => Err(NetworkError::Internal( @@ -437,20 +438,22 @@ impl HTMLScriptElement { }; // Preparation for step 23. - let kind = - if element.has_attribute(&local_name!("defer")) && was_parser_inserted && !r#async { - // Step 23.a: classic, has src, has defer, was parser-inserted, is not async. - ExternalScriptKind::Deferred - } else if was_parser_inserted && !r#async { - // Step 23.c: classic, has src, was parser-inserted, is not async. - ExternalScriptKind::ParsingBlocking - } else if !r#async && !self.non_blocking.get() { - // Step 23.d: classic, has src, is not async, is not non-blocking. - ExternalScriptKind::AsapInOrder - } else { - // Step 23.f: classic, has src. - ExternalScriptKind::Asap - }; + let kind = if element.has_attribute(&local_name!("defer")) && + was_parser_inserted && + !r#async + { + // Step 23.a: classic, has src, has defer, was parser-inserted, is not async. + ExternalScriptKind::Deferred + } else if was_parser_inserted && !r#async { + // Step 23.c: classic, has src, was parser-inserted, is not async. + ExternalScriptKind::ParsingBlocking + } else if !r#async && !self.non_blocking.get() { + // Step 23.d: classic, has src, is not async, is not non-blocking. + ExternalScriptKind::AsapInOrder + } else { + // Step 23.f: classic, has src. + ExternalScriptKind::Asap + }; // Step 21.6. fetch_a_classic_script( diff --git a/components/script/dom/htmlsourceelement.rs b/components/script/dom/htmlsourceelement.rs index b04117e299f..d2c27d18142 100644 --- a/components/script/dom/htmlsourceelement.rs +++ b/components/script/dom/htmlsourceelement.rs @@ -51,7 +51,9 @@ impl HTMLSourceElement { ) } - fn iterate_next_html_image_element_siblings(next_siblings_iterator: impl Iterator<Item=Root<Dom<Node>>>) { + fn iterate_next_html_image_element_siblings( + next_siblings_iterator: impl Iterator<Item = Root<Dom<Node>>>, + ) { for next_sibling in next_siblings_iterator { if let Some(html_image_element_sibling) = next_sibling.downcast::<HTMLImageElement>() { html_image_element_sibling.update_the_image_data(); @@ -68,8 +70,10 @@ impl VirtualMethods for HTMLSourceElement { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); match attr.local_name() { - &local_name!("srcset") | &local_name!("sizes") | - &local_name!("media") | &local_name!("type") => { + &local_name!("srcset") | + &local_name!("sizes") | + &local_name!("media") | + &local_name!("type") => { let next_sibling_iterator = self.upcast::<Node>().following_siblings(); HTMLSourceElement::iterate_next_html_image_element_siblings(next_sibling_iterator); }, diff --git a/components/script/dom/htmltableelement.rs b/components/script/dom/htmltableelement.rs index 218f5e44d41..044938d3129 100644 --- a/components/script/dom/htmltableelement.rs +++ b/components/script/dom/htmltableelement.rs @@ -139,7 +139,8 @@ impl HTMLTableElement { &local_name!("thead") => self.SetTHead(Some(§ion)), &local_name!("tfoot") => self.SetTFoot(Some(§ion)), _ => unreachable!("unexpected section type"), - }.expect("unexpected section type"); + } + .expect("unexpected section type"); section } @@ -160,7 +161,8 @@ impl HTMLTableElement { .filter_map(|ref node| { node.downcast::<HTMLTableSectionElement>() .map(|_| Dom::from_ref(&**node)) - }).collect(), + }) + .collect(), } } } diff --git a/components/script/dom/htmltablerowelement.rs b/components/script/dom/htmltablerowelement.rs index e84cad5164a..a5d2c978c53 100644 --- a/components/script/dom/htmltablerowelement.rs +++ b/components/script/dom/htmltablerowelement.rs @@ -105,11 +105,7 @@ impl HTMLTableRowElementMethods for HTMLTableRowElement { // https://html.spec.whatwg.org/multipage/#dom-tr-deletecell fn DeleteCell(&self, index: i32) -> ErrorResult { let node = self.upcast::<Node>(); - node.delete_cell_or_row( - index, - || self.Cells(), - |n| n.is::<HTMLTableCellElement>(), - ) + node.delete_cell_or_row(index, || self.Cells(), |n| n.is::<HTMLTableCellElement>()) } // https://html.spec.whatwg.org/multipage/#dom-tr-rowindex diff --git a/components/script/dom/node.rs b/components/script/dom/node.rs index 3fbc1b81c0b..4b2f3211ae0 100644 --- a/components/script/dom/node.rs +++ b/components/script/dom/node.rs @@ -384,7 +384,8 @@ impl<'a> Iterator for QuerySelectorIterator { } } None - }).next() + }) + .next() } } @@ -1238,9 +1239,7 @@ impl LayoutNodeHelpers for LayoutDom<Node> { #[allow(unsafe_code)] fn image_data(&self) -> Option<(Option<StdArc<Image>>, Option<ImageMetadata>)> { - unsafe { - self.downcast::<HTMLImageElement>().map(|e| e.image_data()) - } + unsafe { self.downcast::<HTMLImageElement>().map(|e| e.image_data()) } } #[allow(unsafe_code)] @@ -2837,10 +2836,12 @@ pub struct UnbindContext<'a> { impl<'a> UnbindContext<'a> { /// Create a new `UnbindContext` value. - fn new(parent: &'a Node, - prev_sibling: Option<&'a Node>, - next_sibling: Option<&'a Node>, - cached_index: Option<u32>) -> Self { + fn new( + parent: &'a Node, + prev_sibling: Option<&'a Node>, + next_sibling: Option<&'a Node>, + cached_index: Option<u32>, + ) -> Self { UnbindContext { index: Cell::new(cached_index), parent: parent, diff --git a/components/script/dom/paintrenderingcontext2d.rs b/components/script/dom/paintrenderingcontext2d.rs index 756471b998b..c2a766f8cdf 100644 --- a/components/script/dom/paintrenderingcontext2d.rs +++ b/components/script/dom/paintrenderingcontext2d.rs @@ -85,7 +85,8 @@ impl PaintRenderingContext2D { ) { let size = size * device_pixel_ratio; self.device_pixel_ratio.set(device_pixel_ratio); - self.context.set_bitmap_dimensions(size.to_untyped().to_u32()); + self.context + .set_bitmap_dimensions(size.to_untyped().to_u32()); self.scale_by_device_pixel_ratio(); } diff --git a/components/script/dom/performance.rs b/components/script/dom/performance.rs index f8eeaf06966..b47703f51e2 100644 --- a/components/script/dom/performance.rs +++ b/components/script/dom/performance.rs @@ -73,7 +73,8 @@ impl PerformanceEntryList { name.as_ref().map_or(true, |name_| *e.name() == *name_) && entry_type .as_ref() .map_or(true, |type_| *e.entry_type() == *type_) - }).map(|e| e.clone()) + }) + .map(|e| e.clone()) .collect::<Vec<DomRoot<PerformanceEntry>>>(); res.sort_by(|a, b| { a.start_time() @@ -284,7 +285,8 @@ impl Performance { o.observer.callback(), o.observer.entries(), ) - }).collect(); + }) + .collect(); // Step 7.3. for o in observers.iter() { diff --git a/components/script/dom/promiserejectionevent.rs b/components/script/dom/promiserejectionevent.rs index 8791108e643..b4119cd7242 100644 --- a/components/script/dom/promiserejectionevent.rs +++ b/components/script/dom/promiserejectionevent.rs @@ -36,7 +36,7 @@ impl PromiseRejectionEvent { PromiseRejectionEvent { event: Event::new_inherited(), promise, - reason: Heap::default() + reason: Heap::default(), } } @@ -47,21 +47,17 @@ impl PromiseRejectionEvent { bubbles: EventBubbles, cancelable: EventCancelable, promise: Rc<Promise>, - reason: HandleValue + reason: HandleValue, ) -> DomRoot<Self> { let ev = reflect_dom_object( Box::new(PromiseRejectionEvent::new_inherited(promise)), global, - PromiseRejectionEventBinding::Wrap + PromiseRejectionEventBinding::Wrap, ); { let event = ev.upcast::<Event>(); - event.init_event( - type_, - bool::from(bubbles), - bool::from(cancelable) - ); + event.init_event(type_, bool::from(bubbles), bool::from(cancelable)); ev.reason.set(reason.get()); } @@ -72,12 +68,12 @@ impl PromiseRejectionEvent { pub fn Constructor( global: &GlobalScope, type_: DOMString, - init: RootedTraceableBox<PromiseRejectionEventBinding::PromiseRejectionEventInit> + init: RootedTraceableBox<PromiseRejectionEventBinding::PromiseRejectionEventInit>, ) -> Fallible<DomRoot<Self>> { let reason = init.reason.handle(); let promise = match init.promise.as_ref() { Some(promise) => promise.clone(), - None => Promise::new(global) + None => Promise::new(global), }; let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::from(init.parent.cancelable); @@ -88,7 +84,7 @@ impl PromiseRejectionEvent { bubbles, cancelable, promise, - reason + reason, ); Ok(event) } diff --git a/components/script/dom/radionodelist.rs b/components/script/dom/radionodelist.rs index 8ab5dddd53f..18c392a838c 100644 --- a/components/script/dom/radionodelist.rs +++ b/components/script/dom/radionodelist.rs @@ -59,20 +59,28 @@ impl RadioNodeList { impl RadioNodeListMethods for RadioNodeList { // https://html.spec.whatwg.org/multipage/#dom-radionodelist-value fn Value(&self) -> DOMString { - self.upcast::<NodeList>().as_simple_list().iter().filter_map(|node| { - // Step 1 - node.downcast::<HTMLInputElement>().and_then(|input| { - if input.input_type() == InputType::Radio && input.Checked() { - // Step 3-4 - let value = input.Value(); - Some(if value.is_empty() { DOMString::from("on") } else { value }) - } else { - None - } + self.upcast::<NodeList>() + .as_simple_list() + .iter() + .filter_map(|node| { + // Step 1 + node.downcast::<HTMLInputElement>().and_then(|input| { + if input.input_type() == InputType::Radio && input.Checked() { + // Step 3-4 + let value = input.Value(); + Some(if value.is_empty() { + DOMString::from("on") + } else { + value + }) + } else { + None + } + }) }) - }).next() - // Step 2 - .unwrap_or(DOMString::from("")) + .next() + // Step 2 + .unwrap_or(DOMString::from("")) } // https://html.spec.whatwg.org/multipage/#dom-radionodelist-value diff --git a/components/script/dom/range.rs b/components/script/dom/range.rs index 7bba5ad9f00..3f8d5440917 100644 --- a/components/script/dom/range.rs +++ b/components/script/dom/range.rs @@ -836,7 +836,8 @@ impl RangeMethods for Range { start_offset, start_node.len() - start_offset, DOMString::new(), - ).unwrap(); + ) + .unwrap(); } // Step 8. diff --git a/components/script/dom/request.rs b/components/script/dom/request.rs index 8a6d7108a0f..139931375f7 100644 --- a/components/script/dom/request.rs +++ b/components/script/dom/request.rs @@ -285,7 +285,8 @@ impl Request { } // Step 25.2 let method = match init_method.as_str() { - Some(s) => normalize_method(s).map_err(|e| Error::Type(format!("Method is not valid: {:?}", e)))?, + Some(s) => normalize_method(s) + .map_err(|e| Error::Type(format!("Method is not valid: {:?}", e)))?, None => return Err(Error::Type("Method is not a valid UTF8".to_string())), }; // Step 25.3 @@ -375,10 +376,16 @@ impl Request { let req = r.request.borrow(); let req_method = &req.method; match *req_method { - HttpMethod::GET => return Err(Error::Type( - "Init's body is non-null, and request method is GET".to_string())), - HttpMethod::HEAD => return Err(Error::Type( - "Init's body is non-null, and request method is HEAD".to_string())), + HttpMethod::GET => { + return Err(Error::Type( + "Init's body is non-null, and request method is GET".to_string(), + )) + }, + HttpMethod::HEAD => { + return Err(Error::Type( + "Init's body is non-null, and request method is HEAD".to_string(), + )) + }, _ => {}, } } @@ -500,9 +507,7 @@ fn is_forbidden_method(m: &ByteString) -> bool { // https://fetch.spec.whatwg.org/#cors-safelisted-method fn is_cors_safelisted_method(m: &HttpMethod) -> bool { - m == &HttpMethod::GET || - m == &HttpMethod::HEAD || - m == &HttpMethod::POST + m == &HttpMethod::GET || m == &HttpMethod::HEAD || m == &HttpMethod::POST } // https://url.spec.whatwg.org/#include-credentials diff --git a/components/script/dom/servoparser/async_html.rs b/components/script/dom/servoparser/async_html.rs index 86e1b77675b..8b1c00aeb02 100644 --- a/components/script/dom/servoparser/async_html.rs +++ b/components/script/dom/servoparser/async_html.rs @@ -257,7 +257,8 @@ impl Tokenizer { to_tokenizer_sender, html_tokenizer_receiver, ); - }).expect("HTML Parser thread spawning failed"); + }) + .expect("HTML Parser thread spawning failed"); tokenizer } @@ -273,7 +274,8 @@ impl Tokenizer { self.html_tokenizer_sender .send(ToHtmlTokenizerMsg::Feed { input: send_tendrils, - }).unwrap(); + }) + .unwrap(); loop { match self @@ -715,7 +717,8 @@ impl TreeSink for Sink { .map(|attr| Attribute { name: attr.name, value: String::from(attr.value), - }).collect(); + }) + .collect(); self.send_op(ParseOperation::CreateElement { node: node.id, @@ -835,7 +838,8 @@ impl TreeSink for Sink { .map(|attr| Attribute { name: attr.name, value: String::from(attr.value), - }).collect(); + }) + .collect(); self.send_op(ParseOperation::AddAttrsIfMissing { target: target.id, attrs, diff --git a/components/script/dom/servoparser/html.rs b/components/script/dom/servoparser/html.rs index 1ec6b1feca7..cbdf74789a8 100644 --- a/components/script/dom/servoparser/html.rs +++ b/components/script/dom/servoparser/html.rs @@ -127,7 +127,8 @@ fn start_element<S: Serializer>(node: &Element, serializer: &mut S) -> io::Resul let qname = QualName::new(None, attr.namespace().clone(), attr.local_name().clone()); let value = attr.value().clone(); (qname, value) - }).collect::<Vec<_>>(); + }) + .collect::<Vec<_>>(); let attr_refs = attrs.iter().map(|&(ref qname, ref value)| { let ar: AttrRef = (&qname, &**value); ar diff --git a/components/script/dom/servoparser/mod.rs b/components/script/dom/servoparser/mod.rs index 8ce775f6fa8..10326a4eb82 100644 --- a/components/script/dom/servoparser/mod.rs +++ b/components/script/dom/servoparser/mod.rs @@ -722,8 +722,9 @@ impl FetchResponseListener for ParserContext { let doc_body = DomRoot::upcast::<Node>(doc.GetBody().unwrap()); let img = HTMLImageElement::new(local_name!("img"), None, doc); img.SetSrc(DOMString::from(self.url.to_string())); - doc_body.AppendChild(&DomRoot::upcast::<Node>(img)).expect("Appending failed"); - + doc_body + .AppendChild(&DomRoot::upcast::<Node>(img)) + .expect("Appending failed"); }, Some(ref mime) if mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN => { // https://html.spec.whatwg.org/multipage/#read-text @@ -750,17 +751,20 @@ impl FetchResponseListener for ParserContext { } }, // Handle text/xml, application/xml - Some(ref mime) if (mime.type_() == mime::TEXT && mime.subtype() == mime::XML) || - (mime.type_() == mime::APPLICATION && mime.subtype() == mime::XML) => {}, - Some(ref mime) if mime.type_() == mime::APPLICATION && - mime.subtype().as_str() == "xhtml" && - mime.suffix() == Some(mime::XML) - => {}, // Handle xhtml (application/xhtml+xml) + Some(ref mime) + if (mime.type_() == mime::TEXT && mime.subtype() == mime::XML) || + (mime.type_() == mime::APPLICATION && mime.subtype() == mime::XML) => {}, + Some(ref mime) + if mime.type_() == mime::APPLICATION && + mime.subtype().as_str() == "xhtml" && + mime.suffix() == Some(mime::XML) => {}, // Handle xhtml (application/xhtml+xml) Some(ref mime) => { // Show warning page for unknown mime types. - let page = format!("<html><body><p>Unknown content type ({}/{}).</p></body></html>", - mime.type_().as_str(), - mime.subtype().as_str()); + let page = format!( + "<html><body><p>Unknown content type ({}/{}).</p></body></html>", + mime.type_().as_str(), + mime.subtype().as_str() + ); self.is_synthesized_document = true; parser.push_string_input_chunk(page); parser.parse_sync(); diff --git a/components/script/dom/storage.rs b/components/script/dom/storage.rs index 030d8f662b1..16d0cf6e973 100644 --- a/components/script/dom/storage.rs +++ b/components/script/dom/storage.rs @@ -63,7 +63,8 @@ impl StorageMethods for Storage { sender, self.get_url(), self.storage_type, - )).unwrap(); + )) + .unwrap(); receiver.recv().unwrap() as u32 } @@ -77,7 +78,8 @@ impl StorageMethods for Storage { self.get_url(), self.storage_type, index, - )).unwrap(); + )) + .unwrap(); receiver.recv().unwrap().map(DOMString::from) } @@ -138,7 +140,8 @@ impl StorageMethods for Storage { sender, self.get_url(), self.storage_type, - )).unwrap(); + )) + .unwrap(); if receiver.recv().unwrap() { self.broadcast_change_notification(None, None, None); } @@ -153,7 +156,8 @@ impl StorageMethods for Storage { sender, self.get_url(), self.storage_type, - )).unwrap(); + )) + .unwrap(); receiver .recv() .unwrap() @@ -224,6 +228,7 @@ impl Storage { event.upcast::<Event>().fire(global.upcast()); }), global.upcast(), - ).unwrap(); + ) + .unwrap(); } } diff --git a/components/script/dom/storageevent.rs b/components/script/dom/storageevent.rs index 7f0549bb5cf..4a8ed1432cc 100644 --- a/components/script/dom/storageevent.rs +++ b/components/script/dom/storageevent.rs @@ -141,11 +141,22 @@ impl StorageEventMethods for StorageEvent { } // https://html.spec.whatwg.org/multipage/#dom-storageevent-initstorageevent - fn InitStorageEvent(&self, type_: DOMString, bubbles: bool, cancelable: bool, key: - Option<DOMString>, oldValue: Option<DOMString>, newValue: - Option<DOMString>, url: USVString, storageArea: Option<&Storage>) - { - self.event.init_event(Atom::from(type_), bool::from(bubbles), bool::from(cancelable)); + fn InitStorageEvent( + &self, + type_: DOMString, + bubbles: bool, + cancelable: bool, + key: Option<DOMString>, + oldValue: Option<DOMString>, + newValue: Option<DOMString>, + url: USVString, + storageArea: Option<&Storage>, + ) { + self.event.init_event( + Atom::from(type_), + bool::from(bubbles), + bool::from(cancelable), + ); *self.key.borrow_mut() = key; *self.old_value.borrow_mut() = oldValue; *self.new_value.borrow_mut() = newValue; diff --git a/components/script/dom/timeranges.rs b/components/script/dom/timeranges.rs index 5edddc0acd5..4aec4cac7ef 100644 --- a/components/script/dom/timeranges.rs +++ b/components/script/dom/timeranges.rs @@ -63,9 +63,7 @@ pub struct TimeRangesContainer { impl TimeRangesContainer { pub fn new() -> Self { - Self { - ranges: Vec::new(), - } + Self { ranges: Vec::new() } } pub fn len(&self) -> u32 { @@ -73,11 +71,17 @@ impl TimeRangesContainer { } pub fn start(&self, index: u32) -> Result<f64, TimeRangesError> { - self.ranges.get(index as usize).map(|r| r.start).ok_or(TimeRangesError::OutOfRange) + self.ranges + .get(index as usize) + .map(|r| r.start) + .ok_or(TimeRangesError::OutOfRange) } pub fn end(&self, index: u32) -> Result<f64, TimeRangesError> { - self.ranges.get(index as usize).map(|r| r.end).ok_or(TimeRangesError::OutOfRange) + self.ranges + .get(index as usize) + .map(|r| r.end) + .ok_or(TimeRangesError::OutOfRange) } pub fn add(&mut self, start: f64, end: f64) -> Result<(), TimeRangesError> { @@ -93,13 +97,16 @@ impl TimeRangesContainer { // in between two ranges. let mut idx = 0; while idx < self.ranges.len() { - if new_range.is_overlapping(&self.ranges[idx]) || new_range.is_contiguous(&self.ranges[idx]) { + if new_range.is_overlapping(&self.ranges[idx]) || + new_range.is_contiguous(&self.ranges[idx]) + { // The ranges are either overlapping or contiguous, // we need to merge the new range with the existing one. new_range.union(&self.ranges[idx]); self.ranges.remove(idx); } else if new_range.is_before(&self.ranges[idx]) && - (idx == 0 || self.ranges[idx - 1].is_before(&new_range)) { + (idx == 0 || self.ranges[idx - 1].is_before(&new_range)) + { // We are exactly after the current previous range and before the current // range, while not overlapping with none of them. // Or we are simply at the beginning. @@ -155,9 +162,7 @@ impl TimeRangesMethods for TimeRanges { .borrow() .start(index) .map(Finite::wrap) - .map_err(|_| { - Error::IndexSize - }) + .map_err(|_| Error::IndexSize) } // https://html.spec.whatwg.org/multipage/#dom-timeranges-end @@ -166,8 +171,6 @@ impl TimeRangesMethods for TimeRanges { .borrow() .end(index) .map(Finite::wrap) - .map_err(|_| { - Error::IndexSize - }) + .map_err(|_| Error::IndexSize) } } diff --git a/components/script/dom/url.rs b/components/script/dom/url.rs index a8e389e0758..25e0274cbf5 100644 --- a/components/script/dom/url.rs +++ b/components/script/dom/url.rs @@ -86,7 +86,7 @@ impl URL { return Err(Error::Type(format!("could not parse base: {}", error))); }, } - }, + } }; // Step 3. let parsed_url = match ServoUrl::parse_with_base(parsed_base.as_ref(), &url.0) { @@ -121,7 +121,7 @@ impl URL { /* If the value provided for the url argument is not a Blob URL OR if the value provided for the url argument does not have an entry in the Blob URL Store, - + this method call does nothing. User agents may display a message on the error console. */ let origin = get_blob_origin(&global.get_url()); diff --git a/components/script/dom/urlsearchparams.rs b/components/script/dom/urlsearchparams.rs index d83162eb463..5a417b73bd9 100644 --- a/components/script/dom/urlsearchparams.rs +++ b/components/script/dom/urlsearchparams.rs @@ -108,7 +108,8 @@ impl URLSearchParamsMethods for URLSearchParams { } else { None } - }).collect() + }) + .collect() } // https://url.spec.whatwg.org/#dom-urlsearchparams-has diff --git a/components/script/dom/vrdisplay.rs b/components/script/dom/vrdisplay.rs index 3bd44601c16..1d2a2370b1e 100644 --- a/components/script/dom/vrdisplay.rs +++ b/components/script/dom/vrdisplay.rs @@ -213,7 +213,8 @@ impl VRDisplayMethods for VRDisplay { self.depth_near.get(), self.depth_far.get(), sender, - )).unwrap(); + )) + .unwrap(); return match receiver.recv().unwrap() { Ok(data) => { frameData.update(&data); @@ -239,7 +240,8 @@ impl VRDisplayMethods for VRDisplay { self.global().pipeline_id(), self.DisplayId(), sender, - )).unwrap(); + )) + .unwrap(); if let Ok(data) = receiver.recv().unwrap() { // Some VRDisplay data might change after calling ResetPose() *self.display.borrow_mut() = data; @@ -352,7 +354,8 @@ impl VRDisplayMethods for VRDisplay { self.global().pipeline_id(), self.display.borrow().display_id, sender, - )).unwrap(); + )) + .unwrap(); match receiver.recv().unwrap() { Ok(()) => { *self.layer.borrow_mut() = layer_bounds; @@ -387,7 +390,8 @@ impl VRDisplayMethods for VRDisplay { self.global().pipeline_id(), self.display.borrow().display_id, Some(sender), - )).unwrap(); + )) + .unwrap(); match receiver.recv().unwrap() { Ok(()) => { self.stop_present(); @@ -557,7 +561,8 @@ impl VRDisplay { task, Some(pipeline_id), TaskSourceName::DOMManipulation, - )).unwrap(); + )) + .unwrap(); // Run Sync Poses in parallell on Render thread let msg = WebVRCommand::SyncPoses(display_id, near, far, sync_sender.clone()); @@ -573,7 +578,8 @@ impl VRDisplay { return; } } - }).expect("Thread spawning failed"); + }) + .expect("Thread spawning failed"); } fn stop_present(&self) { @@ -595,7 +601,8 @@ impl VRDisplay { self.global().pipeline_id(), self.display.borrow().display_id, None, - )).unwrap(); + )) + .unwrap(); self.stop_present(); } diff --git a/components/script/dom/webgl_extensions/ext/extcolorbufferhalffloat.rs b/components/script/dom/webgl_extensions/ext/extcolorbufferhalffloat.rs index 5f54ba2c609..d1500aa2c9e 100644 --- a/components/script/dom/webgl_extensions/ext/extcolorbufferhalffloat.rs +++ b/components/script/dom/webgl_extensions/ext/extcolorbufferhalffloat.rs @@ -27,9 +27,11 @@ impl EXTColorBufferHalfFloat { impl WebGLExtension for EXTColorBufferHalfFloat { type Extension = EXTColorBufferHalfFloat; fn new(ctx: &WebGLRenderingContext) -> DomRoot<EXTColorBufferHalfFloat> { - reflect_dom_object(Box::new(EXTColorBufferHalfFloat::new_inherited()), - &*ctx.global(), - EXTColorBufferHalfFloatBinding::Wrap) + reflect_dom_object( + Box::new(EXTColorBufferHalfFloat::new_inherited()), + &*ctx.global(), + EXTColorBufferHalfFloatBinding::Wrap, + ) } fn spec() -> WebGLExtensionSpec { @@ -40,8 +42,7 @@ impl WebGLExtension for EXTColorBufferHalfFloat { OESTextureHalfFloat::is_supported(ext) } - fn enable(_ext: &WebGLExtensions) { - } + fn enable(_ext: &WebGLExtensions) {} fn name() -> &'static str { "EXT_color_buffer_half_float" diff --git a/components/script/dom/webgl_extensions/ext/webglcolorbufferfloat.rs b/components/script/dom/webgl_extensions/ext/webglcolorbufferfloat.rs index 7858598e4c6..aceaf026728 100644 --- a/components/script/dom/webgl_extensions/ext/webglcolorbufferfloat.rs +++ b/components/script/dom/webgl_extensions/ext/webglcolorbufferfloat.rs @@ -27,9 +27,11 @@ impl WEBGLColorBufferFloat { impl WebGLExtension for WEBGLColorBufferFloat { type Extension = WEBGLColorBufferFloat; fn new(ctx: &WebGLRenderingContext) -> DomRoot<WEBGLColorBufferFloat> { - reflect_dom_object(Box::new(WEBGLColorBufferFloat::new_inherited()), - &*ctx.global(), - WEBGLColorBufferFloatBinding::Wrap) + reflect_dom_object( + Box::new(WEBGLColorBufferFloat::new_inherited()), + &*ctx.global(), + WEBGLColorBufferFloatBinding::Wrap, + ) } fn spec() -> WebGLExtensionSpec { @@ -40,8 +42,7 @@ impl WebGLExtension for WEBGLColorBufferFloat { OESTextureFloat::is_supported(ext) } - fn enable(_ext: &WebGLExtensions) { - } + fn enable(_ext: &WebGLExtensions) {} fn name() -> &'static str { "WEBGL_color_buffer_float" diff --git a/components/script/dom/webgl_extensions/extensions.rs b/components/script/dom/webgl_extensions/extensions.rs index b7fb6c58e8e..52f4bf4d47f 100644 --- a/components/script/dom/webgl_extensions/extensions.rs +++ b/components/script/dom/webgl_extensions/extensions.rs @@ -183,7 +183,8 @@ impl WebGLExtensions { } } v.1.is_supported(&self) - }).map(|ref v| v.1.name()) + }) + .map(|ref v| v.1.name()) .collect() } diff --git a/components/script/dom/webglrenderbuffer.rs b/components/script/dom/webglrenderbuffer.rs index 7176194e6a9..616bfc353e3 100644 --- a/components/script/dom/webglrenderbuffer.rs +++ b/components/script/dom/webglrenderbuffer.rs @@ -122,9 +122,9 @@ impl WebGLRenderbuffer { // Validate the internal_format, and save it for completeness // validation. let actual_format = match internal_format { - constants::RGBA4 | - constants::DEPTH_COMPONENT16 | - constants::STENCIL_INDEX8 => internal_format, + constants::RGBA4 | constants::DEPTH_COMPONENT16 | constants::STENCIL_INDEX8 => { + internal_format + }, // https://www.khronos.org/registry/webgl/specs/latest/1.0/#6.8 constants::DEPTH_STENCIL => WebGL2RenderingContextConstants::DEPTH24_STENCIL8, constants::RGB5_A1 => { @@ -134,7 +134,7 @@ impl WebGLRenderbuffer { } else { WebGL2RenderingContextConstants::RGBA8 } - } + }, constants::RGB565 => { // RGB565 is not supported on desktop GL. if is_gles() { @@ -142,16 +142,26 @@ impl WebGLRenderbuffer { } else { WebGL2RenderingContextConstants::RGB8 } - } + }, EXTColorBufferHalfFloatConstants::RGBA16F_EXT | EXTColorBufferHalfFloatConstants::RGB16F_EXT => { - if !self.upcast().context().extension_manager().is_half_float_buffer_renderable() { + if !self + .upcast() + .context() + .extension_manager() + .is_half_float_buffer_renderable() + { return Err(WebGLError::InvalidEnum); } internal_format }, WEBGLColorBufferFloatConstants::RGBA32F_EXT => { - if !self.upcast().context().extension_manager().is_float_buffer_renderable() { + if !self + .upcast() + .context() + .extension_manager() + .is_float_buffer_renderable() + { return Err(WebGLError::InvalidEnum); } internal_format diff --git a/components/script/dom/webglrenderingcontext.rs b/components/script/dom/webglrenderingcontext.rs index 7a9c53a415b..31d2ea67c88 100644 --- a/components/script/dom/webglrenderingcontext.rs +++ b/components/script/dom/webglrenderingcontext.rs @@ -312,7 +312,9 @@ impl WebGLRenderingContext { #[inline] pub fn send_command(&self, command: WebGLCommand) { - self.webgl_sender.send(command, capture_webgl_backtrace(self)).unwrap(); + self.webgl_sender + .send(command, capture_webgl_backtrace(self)) + .unwrap(); } #[inline] @@ -570,7 +572,7 @@ impl WebGLRenderingContext { TexImageSource::HTMLVideoElement(_) => { // TODO: https://github.com/servo/servo/issues/6711 return Ok(None); - } + }, })) } @@ -1427,7 +1429,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { cx, CreateWith::Slice(&receiver.recv().unwrap()), rval.handle_mut(), - ).unwrap(); + ) + .unwrap(); ObjectValue(rval.get()) }, Parameter::Int4(param) => { @@ -1438,7 +1441,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { cx, CreateWith::Slice(&receiver.recv().unwrap()), rval.handle_mut(), - ).unwrap(); + ) + .unwrap(); ObjectValue(rval.get()) }, Parameter::Float(param) => { @@ -1454,7 +1458,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { cx, CreateWith::Slice(&receiver.recv().unwrap()), rval.handle_mut(), - ).unwrap(); + ) + .unwrap(); ObjectValue(rval.get()) }, Parameter::Float4(param) => { @@ -1465,7 +1470,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { cx, CreateWith::Slice(&receiver.recv().unwrap()), rval.handle_mut(), - ).unwrap(); + ) + .unwrap(); ObjectValue(rval.get()) }, } @@ -2895,7 +2901,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { } let (sender, receiver) = ipc::bytes_channel().unwrap(); - self.send_command(WebGLCommand::ReadPixels(src_rect, format, pixel_type, sender)); + self.send_command(WebGLCommand::ReadPixels( + src_rect, format, pixel_type, sender, + )); let src = receiver.recv().unwrap(); let src_row_len = src_rect.size.width as usize * bytes_per_pixel as usize; @@ -3467,7 +3475,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { cx, CreateWith::Slice(&value), rval.handle_mut(), - ).unwrap(); + ) + .unwrap(); ObjectValue(rval.get()) } @@ -3627,7 +3636,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { handle_potential_webgl_error!( self, self.current_vao() - .vertex_attrib_pointer(index, size, type_, normalized, stride, offset, ) + .vertex_attrib_pointer(index, size, type_, normalized, stride, offset) ); } @@ -4063,7 +4072,11 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { return self.webgl_error(InvalidValue); } - let rb = handle_potential_webgl_error!(self, self.bound_renderbuffer.get().ok_or(InvalidOperation), return); + let rb = handle_potential_webgl_error!( + self, + self.bound_renderbuffer.get().ok_or(InvalidOperation), + return + ); handle_potential_webgl_error!(self, rb.storage(internal_format, width, height)); if let Some(fb) = self.bound_framebuffer.get() { fb.invalidate_renderbuffer(&*rb); diff --git a/components/script/dom/websocket.rs b/components/script/dom/websocket.rs index c6efde14cfc..d7a90eca8fb 100644 --- a/components/script/dom/websocket.rs +++ b/components/script/dom/websocket.rs @@ -429,7 +429,7 @@ impl WebSocketMethods for WebSocket { WebSocketRequestState::Connecting => { //Connection is not yet established /*By setting the state to closing, the open function - will abort connecting the websocket*/ + will abort connecting the websocket*/ self.ready_state.set(WebSocketRequestState::Closing); let address = Trusted::new(self); @@ -588,7 +588,8 @@ impl TaskOnce for MessageReceivedTask { cx, CreateWith::Slice(&data), array_buffer.handle_mut() - ).is_ok() + ) + .is_ok() ); (*array_buffer).to_jsval(cx, message.handle_mut()); diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 25fee74860c..110c2cfb137 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -1374,7 +1374,8 @@ impl Window { .send(Msg::UpdateScrollStateFromScript(ScrollState { scroll_id, scroll_offset: Vector2D::new(-x, -y), - })).unwrap(); + })) + .unwrap(); } pub fn update_viewport_for_scroll(&self, x: f32, y: f32) { @@ -1852,7 +1853,8 @@ impl Window { pipeline_id, LoadData::new(url, Some(pipeline_id), referrer_policy, Some(doc.url())), replace, - )).unwrap(); + )) + .unwrap(); }; } diff --git a/components/script/dom/worklet.rs b/components/script/dom/worklet.rs index 346ba443f54..07c21fc5999 100644 --- a/components/script/dom/worklet.rs +++ b/components/script/dom/worklet.rs @@ -323,7 +323,11 @@ impl WorkletThreadPool { } pub(crate) fn exit_worklet(&self, worklet_id: WorkletId) { - for sender in &[&self.control_sender_0, &self.control_sender_1, &self.control_sender_2] { + for sender in &[ + &self.control_sender_0, + &self.control_sender_1, + &self.control_sender_2, + ] { let _ = sender.send(WorkletControl::ExitWorklet(worklet_id)); } self.wake_threads(); diff --git a/components/script/dom/workletglobalscope.rs b/components/script/dom/workletglobalscope.rs index eae9281b687..eab249abc12 100644 --- a/components/script/dom/workletglobalscope.rs +++ b/components/script/dom/workletglobalscope.rs @@ -100,7 +100,8 @@ impl WorkletGlobalScope { name, properties, painter, - }).expect("Worklet thread outlived script thread."); + }) + .expect("Worklet thread outlived script thread."); } /// The base URL of this global. diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index cd3be4c6faf..038a7a018bd 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -291,7 +291,8 @@ impl XMLHttpRequest { .send(Fetch( init, FetchChannels::ResponseMsg(action_sender, Some(cancellation_chan)), - )).unwrap(); + )) + .unwrap(); } } @@ -461,7 +462,10 @@ impl XMLHttpRequestMethods for XMLHttpRequest { None => value.into(), }; - headers.insert(HeaderName::from_str(name_str).unwrap(), HeaderValue::from_bytes(&value).unwrap()); + headers.insert( + HeaderName::from_str(name_str).unwrap(), + HeaderValue::from_bytes(&value).unwrap(), + ); Ok(()) } @@ -532,7 +536,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { // Step 3 let data = match *self.request_method.borrow() { Method::GET | Method::HEAD => None, - _ => data + _ => data, }; // Step 4 (first half) let extracted_or_serialized = match data { @@ -637,14 +641,18 @@ impl XMLHttpRequestMethods for XMLHttpRequest { // XHR spec differs from http, and says UTF-8 should be in capitals, // instead of "utf-8", which is what Hyper defaults to. So not // using content types provided by Hyper. - Some("UTF-8"), + { + Some("UTF-8") + }, _ => None, }; let mut content_type_set = false; if let Some(ref ct) = *content_type { if !request.headers.contains_key(header::CONTENT_TYPE) { - request.headers.insert(header::CONTENT_TYPE, HeaderValue::from_str(ct).unwrap()); + request + .headers + .insert(header::CONTENT_TYPE, HeaderValue::from_str(ct).unwrap()); content_type_set = true; } } @@ -657,24 +665,26 @@ impl XMLHttpRequestMethods for XMLHttpRequest { for param in mime.params() { if param.0 == mime::CHARSET { if !param.1.as_ref().eq_ignore_ascii_case(encoding) { - let new_params: Vec<(Name, Name)> = - mime.params() - .filter(|p| p.0 != mime::CHARSET) - .map(|p| (p.0, p.1)) - .collect(); - - let new_mime = - format!("{}/{}; charset={}{}{}", - mime.type_().as_ref(), - mime.subtype().as_ref(), - encoding, - if new_params.is_empty() { "" } else { "; " }, - new_params - .iter() - .map(|p| format!("{}={}", p.0, p.1)) - .collect::<Vec<String>>() - .join("; ") - ); + let new_params: Vec< + (Name, Name), + > = mime + .params() + .filter(|p| p.0 != mime::CHARSET) + .map(|p| (p.0, p.1)) + .collect(); + + let new_mime = format!( + "{}/{}; charset={}{}{}", + mime.type_().as_ref(), + mime.subtype().as_ref(), + encoding, + if new_params.is_empty() { "" } else { "; " }, + new_params + .iter() + .map(|p| format!("{}={}", p.0, p.1)) + .collect::<Vec<String>>() + .join("; ") + ); let new_mime: Mime = new_mime.parse().unwrap(); request.headers.typed_insert(ContentType::from(new_mime)) } @@ -744,15 +754,14 @@ impl XMLHttpRequestMethods for XMLHttpRequest { let headers = self.filter_response_headers(); let headers = headers.get_all(HeaderName::from_str(&name.as_str()?.to_lowercase()).ok()?); let mut first = true; - let s = headers.iter() - .fold(Vec::new(), |mut vec, value| { - if !first { - vec.extend(", ".as_bytes()); - } - first = false; - vec.extend(value.as_bytes()); - vec - }); + let s = headers.iter().fold(Vec::new(), |mut vec, value| { + if !first { + vec.extend(", ".as_bytes()); + } + first = false; + vec.extend(value.as_bytes()); + vec + }); // There was no header with that name so we never got to change that value if first { @@ -808,9 +817,8 @@ impl XMLHttpRequestMethods for XMLHttpRequest { *self.override_mime_type.borrow_mut() = Some(mime_no_params); // Step 4 let value = override_mime.get_param(mime::CHARSET); - *self.override_charset.borrow_mut() = value.and_then(|value| { - Encoding::for_label(value.as_ref().as_bytes()) - }); + *self.override_charset.borrow_mut() = + value.and_then(|value| Encoding::for_label(value.as_ref().as_bytes())); Ok(()) } @@ -1130,18 +1138,24 @@ impl XMLHttpRequest { } fn dispatch_progress_event(&self, upload: bool, type_: Atom, loaded: u64, total: Option<u64>) { - let (total_length, length_computable) = - if self.response_headers.borrow().contains_key(header::CONTENT_ENCODING) { - (0, false) - } else { - (total.unwrap_or(0), total.is_some()) - }; - let progressevent = ProgressEvent::new(&self.global(), - type_, - EventBubbles::DoesNotBubble, - EventCancelable::NotCancelable, - length_computable, loaded, - total_length); + let (total_length, length_computable) = if self + .response_headers + .borrow() + .contains_key(header::CONTENT_ENCODING) + { + (0, false) + } else { + (total.unwrap_or(0), total.is_some()) + }; + let progressevent = ProgressEvent::new( + &self.global(), + type_, + EventBubbles::DoesNotBubble, + EventCancelable::NotCancelable, + length_computable, + loaded, + total_length, + ); let target = if upload { self.upload.upcast() } else { @@ -1159,7 +1173,11 @@ impl XMLHttpRequest { fn dispatch_response_progress_event(&self, type_: Atom) { let len = self.response.borrow().len() as u64; - let total = self.response_headers.borrow().typed_get::<ContentLength>().map(|v| v.0); + let total = self + .response_headers + .borrow() + .typed_get::<ContentLength>() + .map(|v| v.0); self.dispatch_progress_event(false, type_, len, total); } @@ -1202,7 +1220,11 @@ impl XMLHttpRequest { return response; } // Step 2 - let mime = self.final_mime_type().as_ref().map(|m| m.to_string()).unwrap_or("".to_owned()); + let mime = self + .final_mime_type() + .as_ref() + .map(|m| m.to_string()) + .unwrap_or("".to_owned()); // Step 3, 4 let bytes = self.response.borrow().to_vec(); @@ -1254,10 +1276,12 @@ impl XMLHttpRequest { } }, // Step 7 - Some(ref mime) if (mime.type_() == mime::TEXT && mime.subtype() == mime::XML) || - (mime.type_() == mime::APPLICATION && mime.subtype() == mime::XML) => { + Some(ref mime) + if (mime.type_() == mime::TEXT && mime.subtype() == mime::XML) || + (mime.type_() == mime::APPLICATION && mime.subtype() == mime::XML) => + { temp_doc = self.handle_xml(); - }, + } None => { temp_doc = self.handle_xml(); }, @@ -1441,11 +1465,9 @@ impl XMLHttpRequest { Some(ct) => { let mime: Mime = ct.into(); let value = mime.get_param(mime::CHARSET); - value.and_then(|value|{ - Encoding::for_label(value.as_ref().as_bytes()) - }) - } - None => { None } + value.and_then(|value| Encoding::for_label(value.as_ref().as_bytes())) + }, + None => None, } } } @@ -1455,8 +1477,8 @@ impl XMLHttpRequest { self.override_mime_type.borrow().clone() } else { match self.response_headers.borrow().typed_get::<ContentType>() { - Some(ct) => { Some(ct.into()) }, - None => { None } + Some(ct) => Some(ct.into()), + None => None, } } } diff --git a/components/script/fetch.rs b/components/script/fetch.rs index db3d3479f5a..319a965dcab 100644 --- a/components/script/fetch.rs +++ b/components/script/fetch.rs @@ -176,7 +176,8 @@ pub fn Fetch( .send(NetTraitsFetch( request_init, FetchChannels::ResponseMsg(action_sender, None), - )).unwrap(); + )) + .unwrap(); promise } diff --git a/components/script/script_runtime.rs b/components/script/script_runtime.rs index 560e3fe571d..2625bb4d3ce 100644 --- a/components/script/script_runtime.rs +++ b/components/script/script_runtime.rs @@ -156,40 +156,51 @@ unsafe extern "C" fn promise_rejection_tracker( cx: *mut JSContext, promise: HandleObject, state: PromiseRejectionHandlingState, - _data: *mut c_void + _data: *mut c_void, ) { // TODO: Step 2 - If script's muted errors is true, terminate these steps. // Step 3. let global = GlobalScope::from_context(cx); - wrap_panic(AssertUnwindSafe(|| { - match state { - // Step 4. - PromiseRejectionHandlingState::Unhandled => { - global.add_uncaught_rejection(promise); - }, - // Step 5. - PromiseRejectionHandlingState::Handled => { - // Step 5-1. - if global.get_uncaught_rejections().borrow().contains(&Heap::boxed(promise.get())) { - global.remove_uncaught_rejection(promise); - return; - } - - // Step 5-2. - if !global.get_consumed_rejections().borrow().contains(&Heap::boxed(promise.get())) { - global.add_consumed_rejection(promise); - return; - } - - // Step 5-3. - global.remove_consumed_rejection(promise); - - // TODO: Step 5-4 - Queue a task to fire `rejectionhandled` event - } - }; - }), ()); + wrap_panic( + AssertUnwindSafe(|| { + match state { + // Step 4. + PromiseRejectionHandlingState::Unhandled => { + global.add_uncaught_rejection(promise); + }, + // Step 5. + PromiseRejectionHandlingState::Handled => { + // Step 5-1. + if global + .get_uncaught_rejections() + .borrow() + .contains(&Heap::boxed(promise.get())) + { + global.remove_uncaught_rejection(promise); + return; + } + + // Step 5-2. + if !global + .get_consumed_rejections() + .borrow() + .contains(&Heap::boxed(promise.get())) + { + global.add_consumed_rejection(promise); + return; + } + + // Step 5-3. + global.remove_consumed_rejection(promise); + + // TODO: Step 5-4 - Queue a task to fire `rejectionhandled` event + }, + }; + }), + (), + ); } #[allow(unsafe_code, unrooted_must_root)] @@ -201,11 +212,13 @@ pub fn notify_about_rejected_promises(global: &GlobalScope) { // Step 2. if global.get_uncaught_rejections().borrow().len() > 0 { // Step 1. - let uncaught_rejections: Vec<TrustedPromise> = global.get_uncaught_rejections() + let uncaught_rejections: Vec<TrustedPromise> = global + .get_uncaught_rejections() .borrow() .iter() .map(|promise| { - let promise = Promise::new_with_js_promise(Handle::from_raw(promise.handle()), cx); + let promise = + Promise::new_with_js_promise(Handle::from_raw(promise.handle()), cx); TrustedPromise::new(promise) }) diff --git a/components/script/script_thread.rs b/components/script/script_thread.rs index 1837b512f85..02832ba45ac 100644 --- a/components/script/script_thread.rs +++ b/components/script/script_thread.rs @@ -691,7 +691,8 @@ impl ScriptThreadFactory for ScriptThread { // This must always be the very last operation performed before the thread completes failsafe.neuter(); - }).expect("Thread spawning failed"); + }) + .expect("Thread spawning failed"); (sender, receiver) } @@ -890,7 +891,8 @@ impl ScriptThread { image_cache: script_thread.image_cache.clone(), }; Rc::new(WorkletThreadPool::spawn(init)) - }).clone() + }) + .clone() }) } @@ -2539,7 +2541,8 @@ impl ScriptThread { .send(( incomplete.pipeline_id, ScriptMsg::SetFinalUrl(final_url.clone()), - )).unwrap(); + )) + .unwrap(); } debug!( "ScriptThread: loading {} on pipeline {:?}", @@ -2613,7 +2616,8 @@ impl ScriptThread { window.init_window_proxy(&window_proxy); let last_modified = metadata.headers.as_ref().and_then(|headers| { - headers.typed_get::<LastModified>() + headers + .typed_get::<LastModified>() .map(|tm| dom_last_modified(&tm.into())) }); @@ -2622,18 +2626,22 @@ impl ScriptThread { Some(final_url.clone()), ); - let content_type: Option<Mime> = metadata.content_type - .map(Serde::into_inner) - .map(Into::into); + let content_type: Option<Mime> = + metadata.content_type.map(Serde::into_inner).map(Into::into); let is_html_document = match content_type { - Some(ref mime) if mime.type_() == mime::APPLICATION && - mime.suffix() == Some(mime::XML) => IsHTMLDocument::NonHTMLDocument, + Some(ref mime) + if mime.type_() == mime::APPLICATION && mime.suffix() == Some(mime::XML) => + { + IsHTMLDocument::NonHTMLDocument + }, - Some(ref mime) if - (mime.type_() == mime::TEXT && mime.subtype() == mime::XML) || - (mime.type_() == mime::APPLICATION && mime.subtype() == mime::XML) - => IsHTMLDocument::NonHTMLDocument, + Some(ref mime) + if (mime.type_() == mime::TEXT && mime.subtype() == mime::XML) || + (mime.type_() == mime::APPLICATION && mime.subtype() == mime::XML) => + { + IsHTMLDocument::NonHTMLDocument + }, _ => IsHTMLDocument::HTMLDocument, }; @@ -2642,25 +2650,28 @@ impl ScriptThread { None => None, }; - let referrer_policy = metadata.headers - .as_ref() - .map(Serde::deref) - .and_then(|h| h.typed_get::<ReferrerPolicyHeader>()) - .map(ReferrerPolicy::from); - - let document = Document::new(&window, - HasBrowsingContext::Yes, - Some(final_url.clone()), - incomplete.origin, - is_html_document, - content_type, - last_modified, - incomplete.activity, - DocumentSource::FromParser, - loader, - referrer, - referrer_policy, - incomplete.canceller); + let referrer_policy = metadata + .headers + .as_ref() + .map(Serde::deref) + .and_then(|h| h.typed_get::<ReferrerPolicyHeader>()) + .map(ReferrerPolicy::from); + + let document = Document::new( + &window, + HasBrowsingContext::Yes, + Some(final_url.clone()), + incomplete.origin, + is_html_document, + content_type, + last_modified, + incomplete.activity, + DocumentSource::FromParser, + loader, + referrer, + referrer_policy, + incomplete.canceller, + ); document.set_ready_state(DocumentReadyState::Loading); self.documents @@ -2719,7 +2730,8 @@ impl ScriptThread { ids, self.devtools_sender.clone(), page_info, - )).unwrap(); + )) + .unwrap(); } } @@ -3042,7 +3054,8 @@ impl ScriptThread { .send(( id, ScriptMsg::InitiateNavigateRequest(req_init, cancel_chan), - )).unwrap(); + )) + .unwrap(); self.incomplete_loads.borrow_mut().push(incomplete); } @@ -3189,16 +3202,15 @@ impl ScriptThread { } fn perform_a_microtask_checkpoint(&self) { - let globals = self.documents.borrow() - .iter() - .map(|(_id, document)| document.global()) - .collect(); + let globals = self + .documents + .borrow() + .iter() + .map(|(_id, document)| document.global()) + .collect(); self.microtask_queue - .checkpoint( - |id| self.documents.borrow().find_global(id), - globals - ) + .checkpoint(|id| self.documents.borrow().find_global(id), globals) } } diff --git a/components/script/serviceworker_manager.rs b/components/script/serviceworker_manager.rs index 49f3fecb138..9aee99f2bae 100644 --- a/components/script/serviceworker_manager.rs +++ b/components/script/serviceworker_manager.rs @@ -71,7 +71,8 @@ impl ServiceWorkerManager { .spawn(move || { ServiceWorkerManager::new(own_sender, from_constellation, resource_port) .handle_message(); - }).expect("Thread spawning failed"); + }) + .expect("Thread spawning failed"); } pub fn get_matching_scope(&self, load_url: &ServoUrl) -> Option<ServoUrl> { diff --git a/components/script/stylesheet_loader.rs b/components/script/stylesheet_loader.rs index e1a55b3a8ac..17bf780cf32 100644 --- a/components/script/stylesheet_loader.rs +++ b/components/script/stylesheet_loader.rs @@ -120,7 +120,11 @@ impl FetchResponseListener for StylesheetContext { mime.type_() == mime::TEXT && mime.subtype() == mime::CSS }); - let data = if is_css { mem::replace(&mut self.data, vec![]) } else { vec![] }; + let data = if is_css { + mem::replace(&mut self.data, vec![]) + } else { + vec![] + }; // TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding let environment_encoding = UTF_8; diff --git a/components/script/task_queue.rs b/components/script/task_queue.rs index b82db1aac5b..0b9098c6083 100644 --- a/components/script/task_queue.rs +++ b/components/script/task_queue.rs @@ -84,7 +84,8 @@ impl<T: QueuedTaskConversion> TaskQueue<T> { return false; }, } - }).collect(); + }) + .collect(); for msg in incoming { // Immediately send non-throttled tasks for processing. diff --git a/components/script/textinput.rs b/components/script/textinput.rs index 87bdd1d6345..c12c277c9f2 100644 --- a/components/script/textinput.rs +++ b/components/script/textinput.rs @@ -295,9 +295,7 @@ impl<T: ClipboardProvider> TextInput<T> { fn assert_ok_selection(&self) { debug!( "edit_point: {:?}, selection_origin: {:?}, direction: {:?}", - self.edit_point, - self.selection_origin, - self.selection_direction + self.edit_point, self.selection_origin, self.selection_direction ); if let Some(begin) = self.selection_origin { debug_assert!(begin.line < self.lines.len()); @@ -532,8 +530,7 @@ impl<T: ClipboardProvider> TextInput<T> { fn update_selection_direction(&mut self) { debug!( "edit_point: {:?}, selection_origin: {:?}", - self.edit_point, - self.selection_origin + self.edit_point, self.selection_origin ); self.selection_direction = if Some(self.edit_point) < self.selection_origin { SelectionDirection::Backward diff --git a/components/script/webdriver_handlers.rs b/components/script/webdriver_handlers.rs index 3bc95be171f..30291e62be7 100644 --- a/components/script/webdriver_handlers.rs +++ b/components/script/webdriver_handlers.rs @@ -147,7 +147,8 @@ pub fn handle_get_browsing_context_id( .and_then(|node| { node.downcast::<HTMLIFrameElement>() .and_then(|elem| elem.browsing_context_id()) - }).ok_or(()), + }) + .ok_or(()), WebDriverFrameId::Parent => documents .find_window(pipeline) .and_then(|window| { @@ -155,7 +156,8 @@ pub fn handle_get_browsing_context_id( .window_proxy() .parent() .map(|parent| parent.browsing_context_id()) - }).ok_or(()), + }) + .ok_or(()), }; reply.send(result).unwrap() @@ -187,7 +189,8 @@ pub fn handle_find_elements_css( .and_then(|doc| { doc.QuerySelectorAll(DOMString::from(selector)) .map_err(|_| ()) - }).map(|nodes| { + }) + .map(|nodes| { nodes .iter() .map(|x| x.upcast::<Node>().unique_id()) @@ -217,7 +220,8 @@ pub fn handle_focus_element( }, None => Err(()), }, - ).unwrap(); + ) + .unwrap(); } pub fn handle_get_active_element( @@ -231,7 +235,8 @@ pub fn handle_get_active_element( .find_document(pipeline) .and_then(|doc| doc.GetActiveElement()) .map(|elem| elem.upcast::<Node>().unique_id()), - ).unwrap(); + ) + .unwrap(); } pub fn handle_get_cookies( @@ -326,7 +331,8 @@ pub fn handle_add_cookie( Ok(()) }, (_, _) => Err(WebDriverCookieError::UnableToSetCookie), - }).unwrap(); + }) + .unwrap(); } pub fn handle_get_title(documents: &Documents, pipeline: PipelineId, reply: IpcSender<String>) { @@ -382,7 +388,8 @@ pub fn handle_get_rect( }, None => Err(()), }, - ).unwrap(); + ) + .unwrap(); } pub fn handle_get_text( @@ -395,7 +402,8 @@ pub fn handle_get_text( .send(match find_node_by_unique_id(documents, pipeline, node_id) { Some(ref node) => Ok(node.GetTextContent().map_or("".to_owned(), String::from)), None => Err(()), - }).unwrap(); + }) + .unwrap(); } pub fn handle_get_name( @@ -408,7 +416,8 @@ pub fn handle_get_name( .send(match find_node_by_unique_id(documents, pipeline, node_id) { Some(node) => Ok(String::from(node.downcast::<Element>().unwrap().TagName())), None => Err(()), - }).unwrap(); + }) + .unwrap(); } pub fn handle_get_attribute( @@ -426,7 +435,8 @@ pub fn handle_get_attribute( .GetAttribute(DOMString::from(name)) .map(String::from)), None => Err(()), - }).unwrap(); + }) + .unwrap(); } pub fn handle_get_css( @@ -448,7 +458,8 @@ pub fn handle_get_css( )) }, None => Err(()), - }).unwrap(); + }) + .unwrap(); } pub fn handle_get_url(documents: &Documents, pipeline: PipelineId, reply: IpcSender<ServoUrl>) { @@ -475,7 +486,8 @@ pub fn handle_is_enabled( }, None => Err(()), }, - ).unwrap(); + ) + .unwrap(); } pub fn handle_is_selected( @@ -500,5 +512,6 @@ pub fn handle_is_selected( }, None => Err(()), }, - ).unwrap(); + ) + .unwrap(); } diff --git a/components/script_layout_interface/wrapper_traits.rs b/components/script_layout_interface/wrapper_traits.rs index fdb35f07333..d3de357a3e4 100644 --- a/components/script_layout_interface/wrapper_traits.rs +++ b/components/script_layout_interface/wrapper_traits.rs @@ -449,7 +449,8 @@ pub trait ThreadSafeLayoutElement: /* is_probe = */ false, &ServoMetricsProvider, /* matching_func = */ None, - ).unwrap() + ) + .unwrap() }, } }, diff --git a/components/selectors/matching.rs b/components/selectors/matching.rs index ef0c6563f3c..ef942708873 100644 --- a/components/selectors/matching.rs +++ b/components/selectors/matching.rs @@ -588,7 +588,8 @@ where element.is_html_element_in_html_document(), &local_name.name, &local_name.lower_name, - ).borrow(); + ) + .borrow(); element.local_name() == name } diff --git a/components/selectors/parser.rs b/components/selectors/parser.rs index 3e82a49b348..433f58992af 100644 --- a/components/selectors/parser.rs +++ b/components/selectors/parser.rs @@ -270,7 +270,9 @@ where // Ensure they're actually all compound selectors without pseudo-elements. if selector.has_pseudo_element() { - return Err(location.new_custom_error(SelectorParseErrorKind::PseudoElementInComplexSelector)); + return Err( + location.new_custom_error(SelectorParseErrorKind::PseudoElementInComplexSelector) + ); } if selector.iter_raw_match_order().any(|s| s.is_combinator()) { @@ -457,7 +459,7 @@ where ) { return false; } - }, + } AttributeOther(ref attr_selector) if !attr_selector.never_matches => { let empty_string; let namespace = match attr_selector.namespace() { @@ -1720,7 +1722,8 @@ where if namespace.is_none() && include!(concat!( env!("OUT_DIR"), "/ascii_case_insensitive_html_attributes.rs" - )).contains(&*local_name_lower_cow) + )) + .contains(&*local_name_lower_cow) { case_sensitivity = ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument @@ -1872,33 +1875,30 @@ where SimpleSelectorParseResult::PseudoElement(p) => { slotted_selector = None; pseudo_element = Some(p); - } + }, SimpleSelectorParseResult::SlottedPseudo(selector) => { slotted_selector = Some(selector); - let maybe_pseudo = parse_one_simple_selector( - parser, - input, - /* inside_negation = */ false, - )?; + let maybe_pseudo = + parse_one_simple_selector(parser, input, /* inside_negation = */ false)?; pseudo_element = match maybe_pseudo { None => None, Some(SimpleSelectorParseResult::PseudoElement(pseudo)) => { if !pseudo.valid_after_slotted() { return Err(input.new_custom_error( - SelectorParseErrorKind::InvalidPseudoElementAfterSlotted + SelectorParseErrorKind::InvalidPseudoElementAfterSlotted, )); } Some(pseudo) - } + }, Some(SimpleSelectorParseResult::SimpleSelector(..)) | Some(SimpleSelectorParseResult::SlottedPseudo(..)) => { return Err(input.new_custom_error( - SelectorParseErrorKind::NonPseudoElementAfterSlotted + SelectorParseErrorKind::NonPseudoElementAfterSlotted, )); - } + }, }; - } + }, } debug_assert!(slotted_selector.is_some() || pseudo_element.is_some()); @@ -1925,14 +1925,12 @@ where let name = match input.next_including_whitespace()? { &Token::Ident(ref name) => name.clone(), t => { - return Err(location.new_custom_error( - SelectorParseErrorKind::NoIdentForPseudo(t.clone()), - )) + return Err(location + .new_custom_error(SelectorParseErrorKind::NoIdentForPseudo(t.clone()))) }, }; - let pseudo_class = - P::parse_non_ts_pseudo_class(parser, location, name.clone())?; + let pseudo_class = P::parse_non_ts_pseudo_class(parser, location, name.clone())?; if !p.supports_pseudo_class(&pseudo_class) { return Err(input.new_custom_error( SelectorParseErrorKind::UnsupportedPseudoClassOrElement(name), @@ -2139,7 +2137,8 @@ where "last-of-type" => Ok(Component::LastOfType), "only-of-type" => Ok(Component::OnlyOfType), _ => Err(()) - }).or_else(|()| { + }) + .or_else(|()| { P::parse_non_ts_pseudo_class(parser, location, name).map(Component::NonTSPseudoClass) }) } @@ -2422,9 +2421,9 @@ pub mod tests { vec![Component::LocalName(LocalName { name: DummyAtom::from("EeÉ"), lower_name: DummyAtom::from("eeÉ"), - }), ], + })], specificity(0, 0, 1), - ), ])) + )])) ); assert_eq!( parse("|e"), @@ -2437,7 +2436,7 @@ pub mod tests { }), ], specificity(0, 0, 1), - ), ])) + )])) ); // When the default namespace is not set, *| should be elided. // https://github.com/servo/servo/pull/17537 @@ -2447,9 +2446,9 @@ pub mod tests { vec![Component::LocalName(LocalName { name: DummyAtom::from("e"), lower_name: DummyAtom::from("e"), - }), ], + })], specificity(0, 0, 1), - ), ])) + )])) ); // When the default namespace is set, *| should _not_ be elided (as foo // is no longer equivalent to *|foo--the former is only for foo in the @@ -2469,14 +2468,14 @@ pub mod tests { }), ], specificity(0, 0, 1), - ), ])) + )])) ); assert_eq!( parse("*"), Ok(SelectorList::from_vec(vec![Selector::from_vec( vec![Component::ExplicitUniversalType], specificity(0, 0, 0) - ), ])) + )])) ); assert_eq!( parse("|*"), @@ -2486,14 +2485,14 @@ pub mod tests { Component::ExplicitUniversalType, ], specificity(0, 0, 0), - ), ])) + )])) ); assert_eq!( parse_expected("*|*", Some("*")), Ok(SelectorList::from_vec(vec![Selector::from_vec( vec![Component::ExplicitUniversalType], specificity(0, 0, 0) - ), ])) + )])) ); assert_eq!( parse_ns( @@ -2506,7 +2505,7 @@ pub mod tests { Component::ExplicitUniversalType, ], specificity(0, 0, 0), - ), ])) + )])) ); assert_eq!( parse(".foo:lang(en-US)"), @@ -2516,14 +2515,14 @@ pub mod tests { Component::NonTSPseudoClass(PseudoClass::Lang("en-US".to_owned())), ], specificity(0, 2, 0), - ), ])) + )])) ); assert_eq!( parse("#bar"), Ok(SelectorList::from_vec(vec![Selector::from_vec( vec![Component::ID(DummyAtom::from("bar"))], specificity(1, 0, 0), - ), ])) + )])) ); assert_eq!( parse("e.foo#bar"), @@ -2537,7 +2536,7 @@ pub mod tests { Component::ID(DummyAtom::from("bar")), ], specificity(1, 1, 1), - ), ])) + )])) ); assert_eq!( parse("e.foo #bar"), @@ -2552,7 +2551,7 @@ pub mod tests { Component::ID(DummyAtom::from("bar")), ], specificity(1, 1, 1), - ), ])) + )])) ); // Default namespace does not apply to attribute selectors // https://github.com/mozilla/servo/pull/1652 @@ -2563,9 +2562,9 @@ pub mod tests { vec![Component::AttributeInNoNamespaceExists { local_name: DummyAtom::from("Foo"), local_name_lower: DummyAtom::from("foo"), - }, ], + }], specificity(0, 1, 0), - ), ])) + )])) ); assert!(parse_ns("svg|circle", &parser).is_err()); parser @@ -2582,7 +2581,7 @@ pub mod tests { }), ], specificity(0, 0, 1), - ), ])) + )])) ); assert_eq!( parse_ns("svg|*", &parser), @@ -2592,7 +2591,7 @@ pub mod tests { Component::ExplicitUniversalType, ], specificity(0, 0, 0), - ), ])) + )])) ); // Default namespace does not apply to attribute selectors // https://github.com/mozilla/servo/pull/1652 @@ -2610,7 +2609,7 @@ pub mod tests { }, ], specificity(0, 1, 0), - ), ])) + )])) ); // Default namespace does apply to type selectors assert_eq!( @@ -2624,7 +2623,7 @@ pub mod tests { }), ], specificity(0, 0, 1), - ), ])) + )])) ); assert_eq!( parse_ns("*", &parser), @@ -2634,7 +2633,7 @@ pub mod tests { Component::ExplicitUniversalType, ], specificity(0, 0, 0), - ), ])) + )])) ); assert_eq!( parse_ns("*|*", &parser), @@ -2644,7 +2643,7 @@ pub mod tests { Component::ExplicitUniversalType, ], specificity(0, 0, 0), - ), ])) + )])) ); // Default namespace applies to universal and type selectors inside :not and :matches, // but not otherwise. @@ -2660,7 +2659,7 @@ pub mod tests { ), ], specificity(0, 1, 0), - ), ])) + )])) ); assert_eq!( parse_ns(":not(*)", &parser), @@ -2671,12 +2670,13 @@ pub mod tests { vec![ Component::DefaultNamespace(MATHML.into()), Component::ExplicitUniversalType, - ].into_boxed_slice() + ] + .into_boxed_slice() .into(), ), ], specificity(0, 0, 0), - ), ])) + )])) ); assert_eq!( parse_ns(":not(e)", &parser), @@ -2690,12 +2690,13 @@ pub mod tests { name: DummyAtom::from("e"), lower_name: DummyAtom::from("e"), }), - ].into_boxed_slice() + ] + .into_boxed_slice() .into(), ), ], specificity(0, 0, 1), - ), ])) + )])) ); assert_eq!( parse("[attr|=\"foo\"]"), @@ -2706,9 +2707,9 @@ pub mod tests { value: DummyAtom::from("foo"), never_matches: false, case_sensitivity: ParsedCaseSensitivity::CaseSensitive, - }, ], + }], specificity(0, 1, 0), - ), ])) + )])) ); // https://github.com/mozilla/servo/issues/1723 assert_eq!( @@ -2716,7 +2717,7 @@ pub mod tests { Ok(SelectorList::from_vec(vec![Selector::from_vec( vec![Component::PseudoElement(PseudoElement::Before)], specificity(0, 0, 1) | HAS_PSEUDO_BIT, - ), ])) + )])) ); assert_eq!( parse("::before:hover"), @@ -2726,7 +2727,7 @@ pub mod tests { Component::NonTSPseudoClass(PseudoClass::Hover), ], specificity(0, 1, 1) | HAS_PSEUDO_BIT, - ), ])) + )])) ); assert_eq!( parse("::before:hover:hover"), @@ -2737,7 +2738,7 @@ pub mod tests { Component::NonTSPseudoClass(PseudoClass::Hover), ], specificity(0, 2, 1) | HAS_PSEUDO_BIT, - ), ])) + )])) ); assert!(parse("::before:hover:active").is_err()); assert!(parse("::before:hover .foo").is_err()); @@ -2760,7 +2761,7 @@ pub mod tests { Component::PseudoElement(PseudoElement::After), ], specificity(0, 0, 2) | HAS_PSEUDO_BIT, - ), ])) + )])) ); assert_eq!( parse("#d1 > .ok"), @@ -2771,7 +2772,7 @@ pub mod tests { Component::Class(DummyAtom::from("ok")), ], (1 << 20) + (1 << 10) + (0 << 0), - ), ])) + )])) ); parser.default_ns = None; assert!(parse(":not(#provel.old)").is_err()); @@ -2784,9 +2785,9 @@ pub mod tests { vec![Component::ID(DummyAtom::from("provel"))] .into_boxed_slice() .into(), - ), ], + )], specificity(1, 0, 0), - ), ])) + )])) ); assert_eq!( parse_ns(":not(svg|circle)", &parser), @@ -2798,11 +2799,12 @@ pub mod tests { name: DummyAtom::from("circle"), lower_name: DummyAtom::from("circle"), }), - ].into_boxed_slice() + ] + .into_boxed_slice() .into(), - ), ], + )], specificity(0, 0, 1), - ), ])) + )])) ); // https://github.com/servo/servo/issues/16017 assert_eq!( @@ -2812,9 +2814,9 @@ pub mod tests { vec![Component::ExplicitUniversalType] .into_boxed_slice() .into(), - ), ], + )], specificity(0, 0, 0), - ), ])) + )])) ); assert_eq!( parse_ns(":not(|*)", &parser), @@ -2823,11 +2825,12 @@ pub mod tests { vec![ Component::ExplicitNoNamespace, Component::ExplicitUniversalType, - ].into_boxed_slice() + ] + .into_boxed_slice() .into(), - ), ], + )], specificity(0, 0, 0), - ), ])) + )])) ); // *| should be elided if there is no default namespace. // https://github.com/servo/servo/pull/17537 @@ -2838,9 +2841,9 @@ pub mod tests { vec![Component::ExplicitUniversalType] .into_boxed_slice() .into(), - ), ], + )], specificity(0, 0, 0), - ), ])) + )])) ); assert_eq!( parse_ns(":not(svg|*)", &parser), @@ -2849,11 +2852,12 @@ pub mod tests { vec![ Component::Namespace(DummyAtom("svg".into()), SVG.into()), Component::ExplicitUniversalType, - ].into_boxed_slice() + ] + .into_boxed_slice() .into(), - ), ], + )], specificity(0, 0, 0), - ), ])) + )])) ); assert!(parse("::slotted()").is_err()); @@ -2891,7 +2895,8 @@ pub mod tests { let selector = &parse_ns( "*|*::before", &DummyParser::default_with_namespace(DummyAtom::from("https://mozilla.org")), - ).unwrap() + ) + .unwrap() .0[0]; assert!(selector.is_universal()); } diff --git a/components/selectors/tree.rs b/components/selectors/tree.rs index 9db190c8109..1e899f22104 100644 --- a/components/selectors/tree.rs +++ b/components/selectors/tree.rs @@ -22,7 +22,9 @@ impl OpaqueElement { /// Creates a new OpaqueElement from an arbitrarily-typed pointer. pub fn new<T>(ptr: &T) -> Self { unsafe { - OpaqueElement(NonNull::new_unchecked(ptr as *const T as *const () as *mut ())) + OpaqueElement(NonNull::new_unchecked( + ptr as *const T as *const () as *mut (), + )) } } } diff --git a/components/servo/lib.rs b/components/servo/lib.rs index 796050573a7..c1b1e21f91a 100644 --- a/components/servo/lib.rs +++ b/components/servo/lib.rs @@ -199,7 +199,8 @@ where ..Default::default() }, None, - ).expect("Unable to initialize webrender!") + ) + .expect("Unable to initialize webrender!") }; let webrender_api = webrender_api_sender.create_api(); @@ -378,7 +379,10 @@ where WindowEvent::SendError(ctx, e) => { let msg = ConstellationMsg::SendError(ctx, e); if let Err(e) = self.constellation_chan.send(msg) { - warn!("Sending SendError message to constellation failed ({:?}).", e); + warn!( + "Sending SendError message to constellation failed ({:?}).", + e + ); } }, } @@ -397,14 +401,8 @@ where (_, ShutdownState::ShuttingDown) => {}, - ( - EmbedderMsg::Keyboard(key_event), - ShutdownState::NotShuttingDown, - ) => { - let event = ( - top_level_browsing_context, - EmbedderMsg::Keyboard(key_event), - ); + (EmbedderMsg::Keyboard(key_event), ShutdownState::NotShuttingDown) => { + let event = (top_level_browsing_context, EmbedderMsg::Keyboard(key_event)); self.embedder_events.push(event); }, diff --git a/components/style/animation.rs b/components/style/animation.rs index 70db7c2c5b7..0dc55739e5f 100644 --- a/components/style/animation.rs +++ b/components/style/animation.rs @@ -32,7 +32,6 @@ use values::computed::box_::TransitionProperty; use values::generics::box_::AnimationIterationCount; use values::generics::easing::{StepPosition, TimingFunction as GenericTimingFunction}; - /// This structure represents a keyframes animation current iteration state. /// /// If the iteration count is infinite, there's no other state, otherwise we @@ -316,7 +315,8 @@ impl PropertyAnimation { old_style, new_style, ) - }).collect(), + }) + .collect(), TransitionProperty::Longhand(longhand_id) => { let animation = PropertyAnimation::from_longhand( longhand_id, @@ -367,8 +367,9 @@ impl PropertyAnimation { let mut current_step = (time * (steps as f64)).floor() as i32; if pos == StepPosition::Start || - pos == StepPosition::JumpStart || - pos == StepPosition::JumpBoth { + pos == StepPosition::JumpStart || + pos == StepPosition::JumpBoth + { current_step = current_step + 1; } @@ -472,7 +473,8 @@ pub fn start_transitions_if_applicable( duration: box_style.transition_duration_mod(i).seconds() as f64, property_animation, }, - )).unwrap(); + )) + .unwrap(); had_animations = true; } @@ -759,7 +761,8 @@ where } else { None } - }).unwrap_or(animation.steps.len() - 1); + }) + .unwrap_or(animation.steps.len() - 1); }, _ => unreachable!(), } diff --git a/components/style/build.rs b/components/style/build.rs index 8de16176c34..046699c4312 100644 --- a/components/style/build.rs +++ b/components/style/build.rs @@ -67,7 +67,8 @@ fn find_python() -> String { "python2.7" } else { "python" - }.to_owned() + } + .to_owned() } lazy_static! { diff --git a/components/style/build_gecko.rs b/components/style/build_gecko.rs index eff6d94027a..adce4698ce6 100644 --- a/components/style/build_gecko.rs +++ b/components/style/build_gecko.rs @@ -284,7 +284,8 @@ mod bindings { let macro_name = captures.get(1).unwrap().as_str().to_string(); let type_name = captures.get(2).unwrap().as_str().to_string(); (macro_name, type_name) - }).collect() + }) + .collect() } fn get_borrowed_types() -> Vec<(bool, String)> { @@ -419,7 +420,8 @@ mod bindings { servo, if generic { "<T>" } else { "" } )) - }).get_builder(); + }) + .get_builder(); write_binding_file(builder, STRUCTS_FILE, &fixups); } @@ -467,7 +469,8 @@ mod bindings { filter: env::var("STYLO_BUILD_FILTER") .ok() .unwrap_or_else(|| "bindgen".to_owned()), - })).expect("Failed to set logger."); + })) + .expect("Failed to set logger."); true } else { @@ -486,7 +489,8 @@ mod bindings { .handle_common(&mut fixups) .handle_str_items("whitelist-functions", |b, item| b.whitelist_function(item)) .handle_str_items("structs-types", |mut builder, ty| { - builder = builder.blacklist_type(ty) + builder = builder + .blacklist_type(ty) .raw_line(format!("use gecko_bindings::structs::{};", ty)); structs_types.insert(ty); // TODO this is hacky, figure out a better way to do it without @@ -504,10 +508,14 @@ mod bindings { .handle_table_items("array-types", |builder, item| { let cpp_type = item["cpp-type"].as_str().unwrap(); let rust_type = item["rust-type"].as_str().unwrap(); - builder - .raw_line(format!(concat!("pub type nsTArrayBorrowed_{}<'a> = ", - "&'a mut ::gecko_bindings::structs::nsTArray<{}>;"), - cpp_type, rust_type)) + builder.raw_line(format!( + concat!( + "pub type nsTArrayBorrowed_{}<'a> = ", + "&'a mut ::gecko_bindings::structs::nsTArray<{}>;" + ), + cpp_type, + rust_type + )) }) .handle_str_items("servo-immutable-borrow-types", |b, ty| b.borrowed_type(ty)) // Right now the only immutable borrow types are ones which we import @@ -529,7 +537,8 @@ mod bindings { .raw_line(format!( "pub type {0}Strong = ::gecko_bindings::sugar::ownership::Strong<{0}>;", ty - )).borrowed_type(ty) + )) + .borrowed_type(ty) .zero_size_type(ty, &structs_types); } for ty in get_boxed_types().iter() { @@ -538,14 +547,16 @@ mod bindings { .raw_line(format!( "pub type {0}Owned = ::gecko_bindings::sugar::ownership::Owned<{0}>;", ty - )).blacklist_type(format!("{}OwnedOrNull", ty)) + )) + .blacklist_type(format!("{}OwnedOrNull", ty)) .raw_line(format!( concat!( "pub type {0}OwnedOrNull = ", "::gecko_bindings::sugar::ownership::OwnedOrNull<{0}>;" ), ty - )).mutable_borrowed_type(ty) + )) + .mutable_borrowed_type(ty) .zero_size_type(ty, &structs_types); } write_binding_file(builder, BINDINGS_FILE, &fixups); @@ -622,7 +633,8 @@ mod bindings { println!("cargo:rerun-if-changed={}", dir.display()); copy_dir(&dir, &*OUTDIR_PATH, |path| { println!("cargo:rerun-if-changed={}", path.display()); - }).expect("Fail to copy generated files to out dir"); + }) + .expect("Fail to copy generated files to out dir"); } } diff --git a/components/style/counter_style/mod.rs b/components/style/counter_style/mod.rs index 653d199545c..97c8d414d89 100644 --- a/components/style/counter_style/mod.rs +++ b/components/style/counter_style/mod.rs @@ -502,7 +502,8 @@ impl Parse for Ranges { } } Ok(opt_start..opt_end) - }).map(Ranges) + }) + .map(Ranges) } } } diff --git a/components/style/custom_properties.rs b/components/style/custom_properties.rs index 574031453e5..7f91c93378b 100644 --- a/components/style/custom_properties.rs +++ b/components/style/custom_properties.rs @@ -631,11 +631,8 @@ impl<'a> CustomPropertiesBuilder<'a> { // environment variable here, perform substitution here instead // of forcing a full traversal in `substitute_all` afterwards. let value = if !has_references && unparsed_value.references_environment { - let result = substitute_references_in_value( - unparsed_value, - &map, - &self.environment, - ); + let result = + substitute_references_in_value(unparsed_value, &map, &self.environment); match result { Ok(new_value) => Arc::new(new_value), Err(..) => { @@ -886,11 +883,7 @@ fn substitute_all(custom_properties_map: &mut CustomPropertiesMap, environment: // Now we have shown that this variable is not in a loop, and // all of its dependencies should have been resolved. We can // start substitution now. - let result = substitute_references_in_value( - &value, - &context.map, - &context.environment, - ); + let result = substitute_references_in_value(&value, &context.map, &context.environment); match result { Ok(computed_value) => { diff --git a/components/style/dom_apis.rs b/components/style/dom_apis.rs index b7a5fbd24c0..9b613f15057 100644 --- a/components/style/dom_apis.rs +++ b/components/style/dom_apis.rs @@ -338,7 +338,10 @@ fn local_name_matches<E>(element: E, local_name: &LocalName<E::Impl>) -> bool where E: TElement, { - let LocalName { ref name, ref lower_name } = *local_name; + let LocalName { + ref name, + ref lower_name, + } = *local_name; if element.is_html_element_in_html_document() { element.local_name() == lower_name.borrow() } else { @@ -543,23 +546,15 @@ where let case_sensitivity = quirks_mode.classes_and_ids_case_sensitivity(); collect_all_elements::<E, Q, _>(root, results, |element| { element.has_class(class, case_sensitivity) && - matching::matches_selector_list( - selector_list, - &element, - matching_context, - ) + matching::matches_selector_list(selector_list, &element, matching_context) }); - } + }, SimpleFilter::LocalName(ref local_name) => { collect_all_elements::<E, Q, _>(root, results, |element| { local_name_matches(element, local_name) && - matching::matches_selector_list( - selector_list, - &element, - matching_context, - ) + matching::matches_selector_list(selector_list, &element, matching_context) }); - } + }, } Ok(()) diff --git a/components/style/font_face.rs b/components/style/font_face.rs index b207b0291bc..b09c929c2df 100644 --- a/components/style/font_face.rs +++ b/components/style/font_face.rs @@ -55,7 +55,10 @@ impl OneOrMoreSeparated for Source { pub enum FontFaceSourceListComponent { Url(*const ::gecko_bindings::structs::mozilla::css::URLValue), Local(*mut ::gecko_bindings::structs::nsAtom), - FormatHint { length: usize, utf8_bytes: *const u8 }, + FormatHint { + length: usize, + utf8_bytes: *const u8, + }, } /// A `UrlSource` represents a font-face source that has been specified with a @@ -133,7 +136,7 @@ macro_rules! impl_range { Ok(()) } } - } + }; } /// The font-weight descriptor: @@ -192,10 +195,7 @@ impl FontStretchRange { } } - let (min, max) = sort_range( - compute_stretch(&self.0), - compute_stretch(&self.1), - ); + let (min, max) = sort_range(compute_stretch(&self.0), compute_stretch(&self.1)); ComputedFontStretchRange(min, max) } } @@ -277,7 +277,7 @@ impl FontStyle { SpecifiedFontStyle::compute_angle_degrees(second), ); ComputedFontStyleDescriptor::Oblique(min, max) - } + }, } } } @@ -340,7 +340,8 @@ impl<'a> FontFace<'a> { } else { true } - }).cloned() + }) + .cloned() .collect(), ) } diff --git a/components/style/gecko/conversions.rs b/components/style/gecko/conversions.rs index eeb13fce732..947a8c6e1a6 100644 --- a/components/style/gecko/conversions.rs +++ b/components/style/gecko/conversions.rs @@ -113,13 +113,15 @@ impl From<nsStyleCoord_CalcValue> for NonNegativeLengthOrPercentageOrAuto { use style_traits::values::specified::AllowedNumericType; use values::generics::NonNegative; NonNegative(if other.mLength < 0 || other.mPercent < 0. { - LengthOrPercentageOrAuto::Calc( - CalcLengthOrPercentage::with_clamping_mode( - Au(other.mLength).into(), - if other.mHasPercent { Some(Percentage(other.mPercent)) } else { None }, - AllowedNumericType::NonNegative, - ) - ) + LengthOrPercentageOrAuto::Calc(CalcLengthOrPercentage::with_clamping_mode( + Au(other.mLength).into(), + if other.mHasPercent { + Some(Percentage(other.mPercent)) + } else { + None + }, + AllowedNumericType::NonNegative, + )) } else { other.into() }) @@ -625,7 +627,8 @@ impl nsStyleImage { position: LengthOrPercentage::from_gecko_style_coord(&stop.mLocation), }) } - }).collect(); + }) + .collect(); let compat_mode = if gecko_gradient.mMozLegacySyntax { CompatMode::Moz @@ -718,7 +721,8 @@ pub mod basic_shape { match other.mType { StyleShapeSourceType::URL => unsafe { let shape_image = &*other.__bindgen_anon_1.mShapeImage.as_ref().mPtr; - let other_url = RefPtr::new(*shape_image.__bindgen_anon_1.mURLValue.as_ref() as *mut _); + let other_url = + RefPtr::new(*shape_image.__bindgen_anon_1.mURLValue.as_ref() as *mut _); let url = ComputedUrl::from_url_value(other_url); ShapeSource::ImageOrUrl(url) }, diff --git a/components/style/gecko/media_features.rs b/components/style/gecko/media_features.rs index e6f08c60f0c..c0453b18d22 100644 --- a/components/style/gecko/media_features.rs +++ b/components/style/gecko/media_features.rs @@ -305,15 +305,15 @@ bitflags! { } fn primary_pointer_capabilities(device: &Device) -> PointerCapabilities { - PointerCapabilities::from_bits_truncate( - unsafe { bindings::Gecko_MediaFeatures_PrimaryPointerCapabilities(device.document()) } - ) + PointerCapabilities::from_bits_truncate(unsafe { + bindings::Gecko_MediaFeatures_PrimaryPointerCapabilities(device.document()) + }) } fn all_pointer_capabilities(device: &Device) -> PointerCapabilities { - PointerCapabilities::from_bits_truncate( - unsafe { bindings::Gecko_MediaFeatures_AllPointerCapabilities(device.document()) } - ) + PointerCapabilities::from_bits_truncate(unsafe { + bindings::Gecko_MediaFeatures_AllPointerCapabilities(device.document()) + }) } #[derive(Clone, Copy, Debug, FromPrimitive, Parse, ToCss)] diff --git a/components/style/gecko/non_ts_pseudo_class_list.rs b/components/style/gecko/non_ts_pseudo_class_list.rs index 813250e4383..b37af9d71b6 100644 --- a/components/style/gecko/non_ts_pseudo_class_list.rs +++ b/components/style/gecko/non_ts_pseudo_class_list.rs @@ -3,29 +3,29 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* - * This file contains a helper macro includes all supported non-tree-structural - * pseudo-classes. - * +* This file contains a helper macro includes all supported non-tree-structural +* pseudo-classes. +* - * FIXME: Find a way to autogenerate this file. - * - * Expected usage is as follows: - * ``` - * macro_rules! pseudo_class_macro{ - * ([$(($css:expr, $name:ident, $gecko_type:tt, $state:tt, $flags:tt),)*]) => { - * // do stuff - * } - * } - * apply_non_ts_list!(pseudo_class_macro) - * ``` - * - * $gecko_type can be either "_" or an ident in Gecko's CSSPseudoClassType. - * $state can be either "_" or an expression of type ElementState. If present, - * the semantics are that the pseudo-class matches if any of the bits in - * $state are set on the element. - * $flags can be either "_" or an expression of type NonTSPseudoClassFlag, - * see selector_parser.rs for more details. - */ +* FIXME: Find a way to autogenerate this file. +* +* Expected usage is as follows: +* ``` +* macro_rules! pseudo_class_macro{ +* ([$(($css:expr, $name:ident, $gecko_type:tt, $state:tt, $flags:tt),)*]) => { +* // do stuff +* } +* } +* apply_non_ts_list!(pseudo_class_macro) +* ``` +* +* $gecko_type can be either "_" or an ident in Gecko's CSSPseudoClassType. +* $state can be either "_" or an expression of type ElementState. If present, +* the semantics are that the pseudo-class matches if any of the bits in +* $state are set on the element. +* $flags can be either "_" or an expression of type NonTSPseudoClassFlag, +* see selector_parser.rs for more details. +*/ macro_rules! apply_non_ts_list { ($apply_macro:ident) => { diff --git a/components/style/gecko/url.rs b/components/style/gecko/url.rs index 64ea654ba0c..a95eb037e35 100644 --- a/components/style/gecko/url.rs +++ b/components/style/gecko/url.rs @@ -123,10 +123,7 @@ impl SpecifiedUrl { fn from_css_url_with_cors(url: CssUrl, cors: CORSMode) -> Self { let url_value = unsafe { - let ptr = bindings::Gecko_URLValue_Create( - url.0.clone().into_strong(), - cors, - ); + let ptr = bindings::Gecko_URLValue_Create(url.0.clone().into_strong(), cors); // We do not expect Gecko_URLValue_Create returns null. debug_assert!(!ptr.is_null()); RefPtr::from_addrefed(ptr) @@ -261,11 +258,7 @@ impl ToCss for ComputedUrl { where W: Write, { - serialize_computed_url( - &self.0.url_value, - dest, - bindings::Gecko_GetComputedURLSpec, - ) + serialize_computed_url(&self.0.url_value, dest, bindings::Gecko_GetComputedURLSpec) } } diff --git a/components/style/gecko/values.rs b/components/style/gecko/values.rs index 4b982404809..ffa7a65ee0c 100644 --- a/components/style/gecko/values.rs +++ b/components/style/gecko/values.rs @@ -537,7 +537,8 @@ impl CounterStyleOrNone { .map(|symbol| match *symbol { Symbol::String(ref s) => nsCStr::from(s), Symbol::Ident(_) => unreachable!("Should not have identifier in symbols()"), - }).collect(); + }) + .collect(); let symbols: Vec<_> = symbols .iter() .map(|symbol| symbol as &nsACString as *const _) diff --git a/components/style/gecko/wrapper.rs b/components/style/gecko/wrapper.rs index efe37e647c5..7c40fd4c2ec 100644 --- a/components/style/gecko/wrapper.rs +++ b/components/style/gecko/wrapper.rs @@ -937,7 +937,8 @@ impl<'le> GeckoElement<'le> { .animate( to.as_ref().unwrap(), Procedure::Interpolate { progress: 0.5 }, - ).is_ok() + ) + .is_ok() } } @@ -1278,7 +1279,8 @@ impl<'le> TElement for GeckoElement<'le> { Some( Locked::<PropertyDeclarationBlock>::as_arc( &*(&raw as *const &structs::RawServoDeclarationBlock), - ).borrow_arc(), + ) + .borrow_arc(), ) } } diff --git a/components/style/gecko_bindings/sugar/ns_css_value.rs b/components/style/gecko_bindings/sugar/ns_css_value.rs index f41150712b3..a40671eb598 100644 --- a/components/style/gecko_bindings/sugar/ns_css_value.rs +++ b/components/style/gecko_bindings/sugar/ns_css_value.rs @@ -234,9 +234,13 @@ impl nsCSSValue { } debug_assert_eq!(self.mUnit, nsCSSUnit::eCSSUnit_List); let list: &mut structs::nsCSSValueList = &mut unsafe { - self.mValue.mList.as_ref() // &*nsCSSValueList_heap - .as_mut().expect("List pointer should be non-null") - }._base; + self.mValue + .mList + .as_ref() // &*nsCSSValueList_heap + .as_mut() + .expect("List pointer should be non-null") + } + ._base; for (item, new_value) in list.into_iter().zip(values) { *item = new_value; } @@ -255,9 +259,13 @@ impl nsCSSValue { } debug_assert_eq!(self.mUnit, nsCSSUnit::eCSSUnit_PairList); let mut item_ptr = &mut unsafe { - self.mValue.mPairList.as_ref() // &*nsCSSValuePairList_heap - .as_mut().expect("List pointer should be non-null") - }._base as *mut structs::nsCSSValuePairList; + self.mValue + .mPairList + .as_ref() // &*nsCSSValuePairList_heap + .as_mut() + .expect("List pointer should be non-null") + } + ._base as *mut structs::nsCSSValuePairList; while let Some(item) = unsafe { item_ptr.as_mut() } { let value = values.next().expect("Values shouldn't have been exhausted"); item.mXValue = value.0; diff --git a/components/style/gecko_bindings/sugar/ns_t_array.rs b/components/style/gecko_bindings/sugar/ns_t_array.rs index 72a7481fe96..dba867c66fe 100644 --- a/components/style/gecko_bindings/sugar/ns_t_array.rs +++ b/components/style/gecko_bindings/sugar/ns_t_array.rs @@ -117,7 +117,9 @@ impl<T> nsTArray<T> { I: ExactSizeIterator + Iterator<Item = T>, { debug_assert!(iter.len() <= 0xFFFFFFFF); - unsafe { self.set_len_pod(iter.len() as u32); } + unsafe { + self.set_len_pod(iter.len() as u32); + } self.iter_mut().zip(iter).for_each(|(r, v)| *r = v); } } diff --git a/components/style/lib.rs b/components/style/lib.rs index 1f50e062545..7c0a78a36bc 100644 --- a/components/style/lib.rs +++ b/components/style/lib.rs @@ -84,7 +84,8 @@ pub extern crate servo_arc; #[cfg(feature = "servo")] #[macro_use] extern crate servo_atoms; -#[cfg(feature = "servo")] extern crate servo_channel; +#[cfg(feature = "servo")] +extern crate servo_channel; #[cfg(feature = "servo")] extern crate servo_config; #[cfg(feature = "servo")] diff --git a/components/style/matching.rs b/components/style/matching.rs index 9d840a5bbd9..fd1569bea68 100644 --- a/components/style/matching.rs +++ b/components/style/matching.rs @@ -224,7 +224,8 @@ trait PrivateMatchMethods: TElement { context, RuleInclusion::All, PseudoElementResolution::IfApplicable, - ).cascade_style_and_visited_with_default_parents(inputs); + ) + .cascade_style_and_visited_with_default_parents(inputs); Some(style.0) } @@ -618,14 +619,12 @@ trait PrivateMatchMethods: TElement { match *running_animation { Animation::Transition(..) => unreachable!(), - Animation::Keyframes(_, _, _, ref mut state) => { - match update { - AnimationUpdate::Regular => {}, - AnimationUpdate::AnimationCanceled => { - state.expired = true; - } - } - } + Animation::Keyframes(_, _, _, ref mut state) => match update { + AnimationUpdate::Regular => {}, + AnimationUpdate::AnimationCanceled => { + state.expired = true; + }, + }, } } } diff --git a/components/style/media_queries/media_query.rs b/components/style/media_queries/media_query.rs index 46c35618b22..fd1727fe2b2 100644 --- a/components/style/media_queries/media_query.rs +++ b/components/style/media_queries/media_query.rs @@ -130,7 +130,8 @@ impl MediaQuery { let ident = input.expect_ident().map_err(|_| ())?; let media_type = MediaQueryType::parse(&ident)?; Ok((qualifier, Some(media_type))) - }).unwrap_or_default(); + }) + .unwrap_or_default(); let condition = if explicit_media_type.is_none() { Some(MediaCondition::parse(context, input)?) diff --git a/components/style/rule_tree/mod.rs b/components/style/rule_tree/mod.rs index 59c06e58923..3222625749c 100644 --- a/components/style/rule_tree/mod.rs +++ b/components/style/rule_tree/mod.rs @@ -526,7 +526,8 @@ impl RuleTree { path, guards, &mut dummy, - ).expect("Should return a valid rule node") + ) + .expect("Should return a valid rule node") } } diff --git a/components/style/sharing/mod.rs b/components/style/sharing/mod.rs index 23916ce7ff4..3a4a3635206 100644 --- a/components/style/sharing/mod.rs +++ b/components/style/sharing/mod.rs @@ -120,9 +120,8 @@ unsafe impl Sync for OpaqueComputedValues {} impl OpaqueComputedValues { fn from(cv: &ComputedValues) -> Self { - let p = unsafe { - NonNull::new_unchecked(cv as *const ComputedValues as *const () as *mut ()) - }; + let p = + unsafe { NonNull::new_unchecked(cv as *const ComputedValues as *const () as *mut ()) }; OpaqueComputedValues(p) } @@ -204,7 +203,8 @@ impl ValidationData { let values = OpaqueComputedValues::from(parent.borrow_data().unwrap().styles.primary()); values - }).clone() + }) + .clone() } /// Computes the revalidation results if needed, and returns it. diff --git a/components/style/style_adjuster.rs b/components/style/style_adjuster.rs index af53e3dcc7b..ab6c15029ca 100644 --- a/components/style/style_adjuster.rs +++ b/components/style/style_adjuster.rs @@ -713,12 +713,15 @@ impl<'a, 'b: 'a> StyleAdjuster<'a, 'b> { if self.style.pseudo.is_some() { return; } - let is_html_select_element = - element.map_or(false, |e| e.is_html_element() && e.local_name() == &*local_name!("select")); + let is_html_select_element = element.map_or(false, |e| { + e.is_html_element() && e.local_name() == &*local_name!("select") + }); if !is_html_select_element { return; } - self.style.mutate_inherited_text().set_line_height(LineHeight::normal()); + self.style + .mutate_inherited_text() + .set_line_height(LineHeight::normal()); } } diff --git a/components/style/stylesheets/document_rule.rs b/components/style/stylesheets/document_rule.rs index 9598763e438..4dc36953ee2 100644 --- a/components/style/stylesheets/document_rule.rs +++ b/components/style/stylesheets/document_rule.rs @@ -120,7 +120,8 @@ macro_rules! parse_quoted_or_unquoted_string { .parse_entirely(|input| { let string = input.expect_string()?; Ok($url_matching_function(string.as_ref().to_owned())) - }).or_else(|_: ParseError| { + }) + .or_else(|_: ParseError| { while let Ok(_) = input.next() {} Ok($url_matching_function(input.slice_from(start).to_string())) }) diff --git a/components/style/stylesheets/keyframes_rule.rs b/components/style/stylesheets/keyframes_rule.rs index 50c61047e52..f16a3363f5e 100644 --- a/components/style/stylesheets/keyframes_rule.rs +++ b/components/style/stylesheets/keyframes_rule.rs @@ -89,7 +89,8 @@ impl DeepCloneWithLock for KeyframesRule { Arc::new( lock.wrap(x.read_with(guard).deep_clone_with_lock(lock, guard, params)), ) - }).collect(), + }) + .collect(), vendor_prefix: self.vendor_prefix.clone(), source_location: self.source_location.clone(), } @@ -327,7 +328,8 @@ impl KeyframesStep { let (declaration, _) = guard .get(PropertyDeclarationId::Longhand( LonghandId::AnimationTimingFunction, - )).unwrap(); + )) + .unwrap(); match *declaration { PropertyDeclaration::AnimationTimingFunction(ref value) => { // Use the first value. @@ -499,7 +501,8 @@ pub fn parse_keyframe_list( shared_lock: shared_lock, declarations: &mut declarations, }, - ).filter_map(Result::ok) + ) + .filter_map(Result::ok) .collect() } diff --git a/components/style/stylesheets/mod.rs b/components/style/stylesheets/mod.rs index 81726950665..cf0497f5c3d 100644 --- a/components/style/stylesheets/mod.rs +++ b/components/style/stylesheets/mod.rs @@ -109,7 +109,8 @@ impl fmt::Debug for UrlExtraData { .field( "referrer", &DebugURI(self.0.mReferrer.raw::<structs::nsIURI>()), - ).finish() + ) + .finish() } } diff --git a/components/style/stylesheets/supports_rule.rs b/components/style/stylesheets/supports_rule.rs index 06a7807e41d..7af983541d2 100644 --- a/components/style/stylesheets/supports_rule.rs +++ b/components/style/stylesheets/supports_rule.rs @@ -172,9 +172,7 @@ impl SupportsCondition { } /// <https://drafts.csswg.org/css-conditional-3/#supports_condition_in_parens> - fn parse_in_parens<'i, 't>( - input: &mut Parser<'i, 't>, - ) -> Result<Self, ParseError<'i>> { + fn parse_in_parens<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { // Whitespace is normally taken care of in `Parser::next`, // but we want to not include it in `pos` for the SupportsCondition::FutureSyntax cases. while input.try(Parser::expect_whitespace).is_ok() {} @@ -183,9 +181,8 @@ impl SupportsCondition { // FIXME: remove clone() when lifetimes are non-lexical match input.next()?.clone() { Token::ParenthesisBlock => { - let nested = input.try(|input| { - input.parse_nested_block(parse_condition_or_declaration) - }); + let nested = + input.try(|input| input.parse_nested_block(parse_condition_or_declaration)); if nested.is_ok() { return nested; } @@ -209,11 +206,7 @@ impl SupportsCondition { } /// Evaluate a supports condition - pub fn eval( - &self, - cx: &ParserContext, - namespaces: &Namespaces, - ) -> bool { + pub fn eval(&self, cx: &ParserContext, namespaces: &Namespaces) -> bool { match *self { SupportsCondition::Not(ref cond) => !cond.eval(cx, namespaces), SupportsCondition::Parenthesized(ref cond) => cond.eval(cx, namespaces), @@ -300,7 +293,7 @@ impl ToCss for SupportsCondition { dest.write_str("selector(")?; selector.to_css(dest)?; dest.write_str(")") - } + }, SupportsCondition::MozBoolPref(ref name) => { dest.write_str("-moz-bool-pref(")?; let name = @@ -328,51 +321,51 @@ impl ToCss for RawSelector { impl RawSelector { /// Tries to evaluate a `selector()` function. - pub fn eval( - &self, - context: &ParserContext, - namespaces: &Namespaces, - ) -> bool { + pub fn eval(&self, context: &ParserContext, namespaces: &Namespaces) -> bool { #[cfg(feature = "gecko")] { - if unsafe { !::gecko_bindings::structs::StaticPrefs_sVarCache_layout_css_supports_selector_enabled } { + if unsafe { + !::gecko_bindings::structs::StaticPrefs_sVarCache_layout_css_supports_selector_enabled + } { return false; } } let mut input = ParserInput::new(&self.0); let mut input = Parser::new(&mut input); - input.parse_entirely(|input| -> Result<(), CssParseError<()>> { - let parser = SelectorParser { - namespaces, - stylesheet_origin: context.stylesheet_origin, - url_data: Some(context.url_data), - }; - - #[allow(unused_variables)] - let selector = Selector::<SelectorImpl>::parse(&parser, input) - .map_err(|_| input.new_custom_error(()))?; - - #[cfg(feature = "gecko")] - { - use selector_parser::PseudoElement; - use selectors::parser::Component; - - let has_any_unknown_webkit_pseudo = - selector.has_pseudo_element() && - selector.iter_raw_match_order().any(|component| { - matches!( - *component, - Component::PseudoElement(PseudoElement::UnknownWebkit(..)) - ) - }); - if has_any_unknown_webkit_pseudo { - return Err(input.new_custom_error(())); + input + .parse_entirely(|input| -> Result<(), CssParseError<()>> { + let parser = SelectorParser { + namespaces, + stylesheet_origin: context.stylesheet_origin, + url_data: Some(context.url_data), + }; + + #[allow(unused_variables)] + let selector = Selector::<SelectorImpl>::parse(&parser, input) + .map_err(|_| input.new_custom_error(()))?; + + #[cfg(feature = "gecko")] + { + use selector_parser::PseudoElement; + use selectors::parser::Component; + + let has_any_unknown_webkit_pseudo = selector.has_pseudo_element() && selector + .iter_raw_match_order() + .any(|component| { + matches!( + *component, + Component::PseudoElement(PseudoElement::UnknownWebkit(..)) + ) + }); + if has_any_unknown_webkit_pseudo { + return Err(input.new_custom_error(())); + } } - } - Ok(()) - }).is_ok() + Ok(()) + }) + .is_ok() } } @@ -412,20 +405,22 @@ impl Declaration { let mut input = ParserInput::new(&self.0); let mut input = Parser::new(&mut input); - input.parse_entirely(|input| -> Result<(), CssParseError<()>> { - let prop = input.expect_ident_cloned().unwrap(); - input.expect_colon().unwrap(); - - let id = - PropertyId::parse(&prop, context).map_err(|_| input.new_custom_error(()))?; - - let mut declarations = SourcePropertyDeclaration::new(); - input.parse_until_before(Delimiter::Bang, |input| { - PropertyDeclaration::parse_into(&mut declarations, id, &context, input) - .map_err(|_| input.new_custom_error(())) - })?; - let _ = input.try(parse_important); - Ok(()) - }).is_ok() + input + .parse_entirely(|input| -> Result<(), CssParseError<()>> { + let prop = input.expect_ident_cloned().unwrap(); + input.expect_colon().unwrap(); + + let id = + PropertyId::parse(&prop, context).map_err(|_| input.new_custom_error(()))?; + + let mut declarations = SourcePropertyDeclaration::new(); + input.parse_until_before(Delimiter::Bang, |input| { + PropertyDeclaration::parse_into(&mut declarations, id, &context, input) + .map_err(|_| input.new_custom_error(())) + })?; + let _ = input.try(parse_important); + Ok(()) + }) + .is_ok() } } diff --git a/components/style/stylist.rs b/components/style/stylist.rs index 2772891a3db..0013248e41e 100644 --- a/components/style/stylist.rs +++ b/components/style/stylist.rs @@ -517,7 +517,8 @@ impl Stylist { self.stylesheets.iter(), guards, &self.device, - ).finish(), + ) + .finish(), }; self.viewport_constraints = @@ -1017,7 +1018,8 @@ impl Stylist { stylesheets.clone(), guards, &device, - ).finish(), + ) + .finish(), } }; @@ -1535,7 +1537,6 @@ impl Stylist { ); } - results } diff --git a/components/style/traversal.rs b/components/style/traversal.rs index 5f81f3544a9..317fe99a123 100644 --- a/components/style/traversal.rs +++ b/components/style/traversal.rs @@ -361,7 +361,8 @@ where context, rule_inclusion, PseudoElementResolution::IfApplicable, - ).resolve_primary_style( + ) + .resolve_primary_style( style.as_ref().map(|s| &**s), layout_parent_style.as_ref().map(|s| &**s), ); @@ -382,10 +383,12 @@ where context, rule_inclusion, PseudoElementResolution::Force, - ).resolve_style( + ) + .resolve_style( style.as_ref().map(|s| &**s), layout_parent_style.as_ref().map(|s| &**s), - ).into() + ) + .into() } /// Calculates the style for a single node. diff --git a/components/style/values/animated/font.rs b/components/style/values/animated/font.rs index 5a85bc14b18..58da5c58258 100644 --- a/components/style/values/animated/font.rs +++ b/components/style/values/animated/font.rs @@ -143,7 +143,9 @@ impl<'a> FontSettingTagIter<'a> { impl<'a> Iterator for FontSettingTagIter<'a> { type Item = Result<(&'a ComputedVariationValue, &'a ComputedVariationValue), ()>; - fn next(&mut self) -> Option<Result<(&'a ComputedVariationValue, &'a ComputedVariationValue), ()>> { + fn next( + &mut self, + ) -> Option<Result<(&'a ComputedVariationValue, &'a ComputedVariationValue), ()>> { match ( FontSettingTagIter::next_tag(&mut self.a_state), FontSettingTagIter::next_tag(&mut self.b_state), diff --git a/components/style/values/animated/length.rs b/components/style/values/animated/length.rs index f655ec33a2d..d3c6d8aa3c2 100644 --- a/components/style/values/animated/length.rs +++ b/components/style/values/animated/length.rs @@ -23,9 +23,15 @@ impl Animate for CalcLengthOrPercentage { Ok(Some(this.animate(&other, procedure)?)) }; - let length = self.unclamped_length().animate(&other.unclamped_length(), procedure)?; + let length = self + .unclamped_length() + .animate(&other.unclamped_length(), procedure)?; let percentage = animate_percentage_half(self.percentage, other.percentage)?; - Ok(CalcLengthOrPercentage::with_clamping_mode(length, percentage, self.clamping_mode)) + Ok(CalcLengthOrPercentage::with_clamping_mode( + length, + percentage, + self.clamping_mode, + )) } } diff --git a/components/style/values/animated/mod.rs b/components/style/values/animated/mod.rs index 3fe369c4e91..ae2236928fc 100644 --- a/components/style/values/animated/mod.rs +++ b/components/style/values/animated/mod.rs @@ -38,16 +38,16 @@ enum PropertyCategory { impl PropertyCategory { fn of(id: &PropertyId) -> Self { match *id { - PropertyId::Shorthand(..) | - PropertyId::ShorthandAlias(..) => PropertyCategory::Shorthand, - PropertyId::Longhand(id) | - PropertyId::LonghandAlias(id, ..) => { + PropertyId::Shorthand(..) | PropertyId::ShorthandAlias(..) => { + PropertyCategory::Shorthand + }, + PropertyId::Longhand(id) | PropertyId::LonghandAlias(id, ..) => { if id.is_logical() { PropertyCategory::LogicalLonghand } else { PropertyCategory::PhysicalLonghand } - } + }, PropertyId::Custom(..) => PropertyCategory::Custom, } } @@ -81,9 +81,9 @@ pub fn compare_property_priority(a: &PropertyId, b: &PropertyId) -> cmp::Orderin // name. let subprop_count_a = a.longhands().count(); let subprop_count_b = b.longhands().count(); - subprop_count_a.cmp(&subprop_count_b).then_with(|| { - a.idl_name_sort_order().cmp(&b.idl_name_sort_order()) - }) + subprop_count_a + .cmp(&subprop_count_b) + .then_with(|| a.idl_name_sort_order().cmp(&b.idl_name_sort_order())) } /// Animate from one value to another. diff --git a/components/style/values/animated/svg.rs b/components/style/values/animated/svg.rs index df8c43368a1..4c6961de956 100644 --- a/components/style/values/animated/svg.rs +++ b/components/style/values/animated/svg.rs @@ -32,13 +32,11 @@ fn to_number_or_percentage( value: &SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number>, ) -> Result<NumberOrPercentage, ()> { Ok(match *value { - SvgLengthOrPercentageOrNumber::LengthOrPercentage(ref l) => { - match *l { - LengthOrPercentage::Length(ref l) => NumberOrPercentage::Number(l.px()), - LengthOrPercentage::Percentage(ref p) => NumberOrPercentage::Percentage(*p), - LengthOrPercentage::Calc(..) => return Err(()), - } - } + SvgLengthOrPercentageOrNumber::LengthOrPercentage(ref l) => match *l { + LengthOrPercentage::Length(ref l) => NumberOrPercentage::Number(l.px()), + LengthOrPercentage::Percentage(ref p) => NumberOrPercentage::Percentage(*p), + LengthOrPercentage::Calc(..) => return Err(()), + }, SvgLengthOrPercentageOrNumber::Number(ref n) => NumberOrPercentage::Number(*n), }) } @@ -50,22 +48,15 @@ impl Animate for SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number> { let other = to_number_or_percentage(other)?; match (this, other) { - ( - NumberOrPercentage::Number(ref this), - NumberOrPercentage::Number(ref other), - ) => { - Ok(SvgLengthOrPercentageOrNumber::Number( - this.animate(other, procedure)? - )) - }, + (NumberOrPercentage::Number(ref this), NumberOrPercentage::Number(ref other)) => Ok( + SvgLengthOrPercentageOrNumber::Number(this.animate(other, procedure)?), + ), ( NumberOrPercentage::Percentage(ref this), NumberOrPercentage::Percentage(ref other), - ) => { - Ok(SvgLengthOrPercentageOrNumber::LengthOrPercentage( - LengthOrPercentage::Percentage(this.animate(other, procedure)?) - )) - }, + ) => Ok(SvgLengthOrPercentageOrNumber::LengthOrPercentage( + LengthOrPercentage::Percentage(this.animate(other, procedure)?), + )), _ => Err(()), } } @@ -73,8 +64,7 @@ impl Animate for SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number> { impl ComputeSquaredDistance for SvgLengthOrPercentageOrNumber<LengthOrPercentage, Number> { fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { - to_number_or_percentage(self)? - .compute_squared_distance(&to_number_or_percentage(other)?) + to_number_or_percentage(self)?.compute_squared_distance(&to_number_or_percentage(other)?) } } @@ -105,9 +95,9 @@ where return Err(()); } match (self, other) { - (&SVGStrokeDashArray::Values(ref this), &SVGStrokeDashArray::Values(ref other)) => { - Ok(SVGStrokeDashArray::Values(this.animate_repeatable_list(other, procedure)?)) - }, + (&SVGStrokeDashArray::Values(ref this), &SVGStrokeDashArray::Values(ref other)) => Ok( + SVGStrokeDashArray::Values(this.animate_repeatable_list(other, procedure)?), + ), _ => Err(()), } } @@ -135,11 +125,12 @@ where #[inline] fn to_animated_zero(&self) -> Result<Self, ()> { match *self { - SVGStrokeDashArray::Values(ref values) => { - Ok(SVGStrokeDashArray::Values( - values.iter().map(ToAnimatedZero::to_animated_zero).collect::<Result<Vec<_>, _>>()?, - )) - } + SVGStrokeDashArray::Values(ref values) => Ok(SVGStrokeDashArray::Values( + values + .iter() + .map(ToAnimatedZero::to_animated_zero) + .collect::<Result<Vec<_>, _>>()?, + )), SVGStrokeDashArray::ContextValue => Ok(SVGStrokeDashArray::ContextValue), } } diff --git a/components/style/values/computed/angle.rs b/components/style/values/computed/angle.rs index 1c66498f7bd..f46c8087309 100644 --- a/components/style/values/computed/angle.rs +++ b/components/style/values/computed/angle.rs @@ -92,6 +92,7 @@ impl ComputeSquaredDistance for Angle { fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> { // Use the formula for calculating the distance between angles defined in SVG: // https://www.w3.org/TR/SVG/animate.html#complexDistances - self.radians64().compute_squared_distance(&other.radians64()) + self.radians64() + .compute_squared_distance(&other.radians64()) } } diff --git a/components/style/values/computed/length.rs b/components/style/values/computed/length.rs index d32ddcfafa0..ff41f2c37ba 100644 --- a/components/style/values/computed/length.rs +++ b/components/style/values/computed/length.rs @@ -207,12 +207,12 @@ impl ToCss for CalcLengthOrPercentage { if length.px() == 0. && self.clamping_mode.clamp(p.0) == p.0 { return p.to_css(dest); } - } + }, None => { if self.clamping_mode.clamp(length.px()) == length.px() { return length.to_css(dest); } - } + }, } dest.write_str("calc(")?; @@ -950,8 +950,18 @@ pub type NonNegativeLengthOrPercentageOrNormal = Either<NonNegativeLengthOrPerce /// block-size, and inline-size. #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] -#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, - ToComputedValue, ToCss)] +#[derive( + Clone, + Copy, + Debug, + Eq, + MallocSizeOf, + Parse, + PartialEq, + SpecifiedValueInfo, + ToComputedValue, + ToCss, +)] pub enum ExtremumLength { MozMaxContent, MozMinContent, diff --git a/components/style/values/computed/list.rs b/components/style/values/computed/list.rs index 0924cfc96fa..84136007711 100644 --- a/components/style/values/computed/list.rs +++ b/components/style/values/computed/list.rs @@ -24,7 +24,8 @@ impl Quotes { "\u{2018}".to_owned().into_boxed_str(), "\u{2019}".to_owned().into_boxed_str(), ), - ].into_boxed_slice(), + ] + .into_boxed_slice(), ) } } diff --git a/components/style/values/computed/svg.rs b/components/style/values/computed/svg.rs index b41c59082ed..778292a6735 100644 --- a/components/style/values/computed/svg.rs +++ b/components/style/values/computed/svg.rs @@ -51,7 +51,7 @@ impl SVGLength { /// `0px` pub fn zero() -> Self { generic::SVGLength::Length(generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage( - LengthOrPercentage::zero() + LengthOrPercentage::zero(), )) } } @@ -84,7 +84,7 @@ impl SVGWidth { pub fn one() -> Self { use values::generics::NonNegative; generic::SVGLength::Length(generic::SvgLengthOrPercentageOrNumber::LengthOrPercentage( - NonNegative(LengthOrPercentage::one()) + NonNegative(LengthOrPercentage::one()), )) } } diff --git a/components/style/values/generics/basic_shape.rs b/components/style/values/generics/basic_shape.rs index 513e5de0e2b..f571d488a8e 100644 --- a/components/style/values/generics/basic_shape.rs +++ b/components/style/values/generics/basic_shape.rs @@ -307,7 +307,8 @@ where this.0.animate(&other.0, procedure)?, this.1.animate(&other.1, procedure)?, )) - }).collect::<Result<Vec<_>, _>>()?; + }) + .collect::<Result<Vec<_>, _>>()?; Ok(Polygon { fill: self.fill, coordinates, @@ -333,7 +334,8 @@ where let d1 = this.0.compute_squared_distance(&other.0)?; let d2 = this.1.compute_squared_distance(&other.1)?; Ok(d1 + d2) - }).sum() + }) + .sum() } } diff --git a/components/style/values/generics/easing.rs b/components/style/values/generics/easing.rs index c4436fb2efd..616fd63d172 100644 --- a/components/style/values/generics/easing.rs +++ b/components/style/values/generics/easing.rs @@ -9,7 +9,9 @@ use parser::ParserContext; use values::CSSFloat; /// A generic easing function. -#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)] +#[derive( + Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, +)] #[value_info(ty = "TIMING_FUNCTION")] #[repr(u8, C)] pub enum TimingFunction<Integer, Number> { diff --git a/components/style/values/generics/length.rs b/components/style/values/generics/length.rs index 99976be493e..15832b4616d 100644 --- a/components/style/values/generics/length.rs +++ b/components/style/values/generics/length.rs @@ -45,7 +45,7 @@ pub enum MozLength<LengthOrPercentageOrAuto> { SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, - ToCss + ToCss, )] pub enum MaxLength<LengthOrPercentageOrNone> { LengthOrPercentageOrNone(LengthOrPercentageOrNone), diff --git a/components/style/values/generics/ui.rs b/components/style/values/generics/ui.rs index 73f050bb12a..2154c42f5d6 100644 --- a/components/style/values/generics/ui.rs +++ b/components/style/values/generics/ui.rs @@ -71,8 +71,20 @@ impl<ImageUrl: ToCss, Number: ToCss> ToCss for CursorImage<ImageUrl, Number> { /// A generic value for `scrollbar-color` property. /// /// https://drafts.csswg.org/css-scrollbars-1/#scrollbar-color -#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, - SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss)] +#[derive( + Animate, + Clone, + ComputeSquaredDistance, + Copy, + Debug, + MallocSizeOf, + PartialEq, + SpecifiedValueInfo, + ToAnimatedValue, + ToAnimatedZero, + ToComputedValue, + ToCss, +)] pub enum ScrollbarColor<Color> { /// `auto` Auto, @@ -82,7 +94,7 @@ pub enum ScrollbarColor<Color> { thumb: Color, /// Second `<color>`, for color of the scrollbar track. track: Color, - } + }, } impl<Color> Default for ScrollbarColor<Color> { diff --git a/components/style/values/specified/angle.rs b/components/style/values/specified/angle.rs index b634756d89f..5d1740c6991 100644 --- a/components/style/values/specified/angle.rs +++ b/components/style/values/specified/angle.rs @@ -152,11 +152,7 @@ impl Parse for Angle { impl Angle { /// Parse an `<angle>` value given a value and an unit. - pub fn parse_dimension( - value: CSSFloat, - unit: &str, - was_calc: bool, - ) -> Result<Angle, ()> { + pub fn parse_dimension(value: CSSFloat, unit: &str, was_calc: bool) -> Result<Angle, ()> { let value = match_ignore_ascii_case! { unit, "deg" => AngleDimension::Deg(value), "grad" => AngleDimension::Grad(value), @@ -200,7 +196,8 @@ impl Angle { return input.parse_nested_block(|i| CalcNode::parse_angle(context, i)) }, _ => Err(()), - }.map_err(|()| input.new_unexpected_token_error(token.clone())) + } + .map_err(|()| input.new_unexpected_token_error(token.clone())) } } diff --git a/components/style/values/specified/basic_shape.rs b/components/style/values/specified/basic_shape.rs index dcf04dcc0df..64bd362f748 100644 --- a/components/style/values/specified/basic_shape.rs +++ b/components/style/values/specified/basic_shape.rs @@ -275,7 +275,8 @@ impl Ellipse { ShapeRadius::parse(context, i)?, ShapeRadius::parse(context, i)?, )) - }).unwrap_or_default(); + }) + .unwrap_or_default(); let position = if input.try(|i| i.expect_ident_matching("at")).is_ok() { Position::parse(context, input)? } else { @@ -422,7 +423,8 @@ impl Polygon { let fill = FillRule::parse(i)?; i.expect_comma()?; // only eat the comma if there is something before it Ok(fill) - }).unwrap_or_default(); + }) + .unwrap_or_default(); let buf = input.parse_comma_separated(|i| { Ok(PolygonCoord( @@ -459,7 +461,8 @@ impl Path { let fill = FillRule::parse(i)?; i.expect_comma()?; Ok(fill) - }).unwrap_or_default(); + }) + .unwrap_or_default(); let path = SVGPathData::parse(context, input)?; Ok(Path { fill, path }) } diff --git a/components/style/values/specified/border.rs b/components/style/values/specified/border.rs index 7a681c2ef2c..2f4d3548351 100644 --- a/components/style/values/specified/border.rs +++ b/components/style/values/specified/border.rs @@ -92,7 +92,8 @@ impl ToComputedValue for BorderSideWidth { BorderSideWidth::Medium => Length::from_px(3.).to_computed_value(context), BorderSideWidth::Thick => Length::from_px(5.).to_computed_value(context), BorderSideWidth::Length(ref length) => length.to_computed_value(context), - }.into() + } + .into() } #[inline] @@ -182,7 +183,8 @@ impl Parse for BorderSpacing { ) -> Result<Self, ParseError<'i>> { Size::parse_with(context, input, |context, input| { Length::parse_non_negative_quirky(context, input, AllowQuirks::Yes).map(From::from) - }).map(GenericBorderSpacing) + }) + .map(GenericBorderSpacing) } } diff --git a/components/style/values/specified/calc.rs b/components/style/values/specified/calc.rs index 3a28d42223c..0bb8abc62aa 100644 --- a/components/style/values/specified/calc.rs +++ b/components/style/values/specified/calc.rs @@ -529,8 +529,7 @@ impl CalcNode { context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<CSSInteger, ParseError<'i>> { - Self::parse_number(context, input) - .map(|n| n.round() as CSSInteger) + Self::parse_number(context, input).map(|n| n.round() as CSSInteger) } /// Convenience parsing function for `<length> | <percentage>`. diff --git a/components/style/values/specified/counters.rs b/components/style/values/specified/counters.rs index ce7e3991227..ea369f9dec7 100644 --- a/components/style/values/specified/counters.rs +++ b/components/style/values/specified/counters.rs @@ -93,7 +93,8 @@ impl Content { .try(|input| { input.expect_comma()?; ListStyleType::parse(input) - }).unwrap_or(ListStyleType::Decimal) + }) + .unwrap_or(ListStyleType::Decimal) } #[cfg(feature = "gecko")] @@ -102,7 +103,8 @@ impl Content { .try(|input| { input.expect_comma()?; CounterStyleOrNone::parse(context, input) - }).unwrap_or(CounterStyleOrNone::decimal()) + }) + .unwrap_or(CounterStyleOrNone::decimal()) } } diff --git a/components/style/values/specified/easing.rs b/components/style/values/specified/easing.rs index 017643cdab7..d6235612693 100644 --- a/components/style/values/specified/easing.rs +++ b/components/style/values/specified/easing.rs @@ -74,10 +74,9 @@ impl Parse for TimingFunction { Ok(GenericTimingFunction::Steps(steps, position)) }, _ => Err(()), - }).map_err(|()| { - location.new_custom_error( - StyleParseErrorKind::UnexpectedFunction(function.clone()) - ) + }) + .map_err(|()| { + location.new_custom_error(StyleParseErrorKind::UnexpectedFunction(function.clone())) }) }) } diff --git a/components/style/values/specified/font.rs b/components/style/values/specified/font.rs index c07bbe66f75..c69b9b1a6fc 100644 --- a/components/style/values/specified/font.rs +++ b/components/style/values/specified/font.rs @@ -733,7 +733,8 @@ impl ToComputedValue for KeywordSize { KeywordSize::XLarge => Au::from_px(FONT_MEDIUM_PX) * 3 / 2, KeywordSize::XXLarge => Au::from_px(FONT_MEDIUM_PX) * 2, KeywordSize::XXXLarge => Au::from_px(FONT_MEDIUM_PX) * 3, - }.into() + } + .into() } #[inline] @@ -837,7 +838,8 @@ impl FontSize { 6 => KeywordSize::XXLarge, // If value is greater than 7, let it be 7. _ => KeywordSize::XXXLarge, - }.into(), + } + .into(), ) } @@ -906,7 +908,8 @@ impl FontSize { .to_computed_value_zoomed( context, FontBaseSize::InheritedStyleButStripEmUnits, - ).length_component(); + ) + .length_component(); info = parent.keyword_info.map(|i| i.compose(ratio, abs.into())); } @@ -2108,7 +2111,8 @@ impl ToComputedValue for FontLanguageOverride { String::from_utf8(buf.to_vec()).unwrap() } else { unsafe { String::from_utf8_unchecked(buf.to_vec()) } - }.into_boxed_str(), + } + .into_boxed_str(), ) } } diff --git a/components/style/values/specified/image.rs b/components/style/values/specified/image.rs index 73cec6da7b1..b8c1c9f3958 100644 --- a/components/style/values/specified/image.rs +++ b/components/style/values/specified/image.rs @@ -189,7 +189,9 @@ impl Image { context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Image, ParseError<'i>> { - if let Ok(url) = input.try(|input| SpecifiedImageUrl::parse_with_cors_anonymous(context, input)) { + if let Ok(url) = + input.try(|input| SpecifiedImageUrl::parse_with_cors_anonymous(context, input)) + { return Ok(generic::Image::Url(url)); } Self::parse(context, input) @@ -1023,7 +1025,8 @@ impl Parse for PaintWorklet { .try(|input| { input.expect_comma()?; input.parse_comma_separated(|input| SpecifiedValue::parse(input)) - }).unwrap_or(vec![]); + }) + .unwrap_or(vec![]); Ok(PaintWorklet { name, arguments }) }) } diff --git a/components/style/values/specified/source_size_list.rs b/components/style/values/specified/source_size_list.rs index 2d86d5a058f..e00f4ee1d5d 100644 --- a/components/style/values/specified/source_size_list.rs +++ b/components/style/values/specified/source_size_list.rs @@ -73,10 +73,12 @@ impl SourceSizeList { Some(ref v) => v.to_computed_value(context), None => Length::NoCalc(NoCalcLength::ViewportPercentage( ViewportPercentageLength::Vw(100.), - )).to_computed_value(context), + )) + .to_computed_value(context), }, } - }).into() + }) + .into() } } diff --git a/components/style/values/specified/svg_path.rs b/components/style/values/specified/svg_path.rs index 3f1fdc39d97..c3acf4585fa 100644 --- a/components/style/values/specified/svg_path.rs +++ b/components/style/values/specified/svg_path.rs @@ -563,7 +563,6 @@ impl ToAnimatedZero for ArcFlag { } } - /// SVG Path parser. struct PathParser<'a> { chars: Peekable<Cloned<slice::Iter<'a, u8>>>, diff --git a/components/style/values/specified/text.rs b/components/style/values/specified/text.rs index 6bd0af23eb2..3168dd4c06f 100644 --- a/components/style/values/specified/text.rs +++ b/components/style/values/specified/text.rs @@ -613,30 +613,40 @@ impl TextEmphasisShapeKeyword { pub fn char(&self, fill: TextEmphasisFillMode) -> &str { let fill = fill == TextEmphasisFillMode::Filled; match *self { - TextEmphasisShapeKeyword::Dot => if fill { - "\u{2022}" - } else { - "\u{25e6}" + TextEmphasisShapeKeyword::Dot => { + if fill { + "\u{2022}" + } else { + "\u{25e6}" + } }, - TextEmphasisShapeKeyword::Circle => if fill { - "\u{25cf}" - } else { - "\u{25cb}" + TextEmphasisShapeKeyword::Circle => { + if fill { + "\u{25cf}" + } else { + "\u{25cb}" + } }, - TextEmphasisShapeKeyword::DoubleCircle => if fill { - "\u{25c9}" - } else { - "\u{25ce}" + TextEmphasisShapeKeyword::DoubleCircle => { + if fill { + "\u{25c9}" + } else { + "\u{25ce}" + } }, - TextEmphasisShapeKeyword::Triangle => if fill { - "\u{25b2}" - } else { - "\u{25b3}" + TextEmphasisShapeKeyword::Triangle => { + if fill { + "\u{25b2}" + } else { + "\u{25b3}" + } }, - TextEmphasisShapeKeyword::Sesame => if fill { - "\u{fe45}" - } else { - "\u{fe46}" + TextEmphasisShapeKeyword::Sesame => { + if fill { + "\u{fe45}" + } else { + "\u{fe46}" + } }, } } diff --git a/components/style_derive/cg.rs b/components/style_derive/cg.rs index 6cc13c89497..9338e3b4f5e 100644 --- a/components/style_derive/cg.rs +++ b/components/style_derive/cg.rs @@ -58,7 +58,8 @@ pub fn fmap_trait_output(input: &DeriveInput, trait_path: &Path, trait_output: I ) }, ref arg => panic!("arguments {:?} cannot be mapped yet", arg), - }).collect(), + }) + .collect(), colon2_token: Default::default(), gt_token: Default::default(), lt_token: Default::default(), @@ -154,14 +155,16 @@ where }) }, ref arg => panic!("arguments {:?} cannot be mapped yet", arg), - }).collect(), + }) + .collect(), ..data.clone() }) }, ref arg @ PathArguments::None => arg.clone(), ref parameters => panic!("parameters {:?} cannot be mapped yet", parameters), }, - }).collect(), + }) + .collect(), } } diff --git a/components/style_derive/to_css.rs b/components/style_derive/to_css.rs index a5811471cb1..2eafbacb548 100644 --- a/components/style_derive/to_css.rs +++ b/components/style_derive/to_css.rs @@ -130,7 +130,8 @@ fn derive_variant_fields_expr( return None; } Some((binding, attrs)) - }).peekable(); + }) + .peekable(); let (first, attrs) = match iter.next() { Some(pair) => pair, diff --git a/components/webdriver_server/lib.rs b/components/webdriver_server/lib.rs index e5724d64c63..179ebb82922 100644 --- a/components/webdriver_server/lib.rs +++ b/components/webdriver_server/lib.rs @@ -66,9 +66,23 @@ use webdriver::response::{WebDriverResponse, WindowRectResponse}; use webdriver::server::{self, Session, WebDriverHandler}; fn extension_routes() -> Vec<(Method, &'static str, ServoExtensionRoute)> { - return vec![(Method::POST, "/session/{sessionId}/servo/prefs/get", ServoExtensionRoute::GetPrefs), - (Method::POST, "/session/{sessionId}/servo/prefs/set", ServoExtensionRoute::SetPrefs), - (Method::POST, "/session/{sessionId}/servo/prefs/reset", ServoExtensionRoute::ResetPrefs)] + return vec![ + ( + Method::POST, + "/session/{sessionId}/servo/prefs/get", + ServoExtensionRoute::GetPrefs, + ), + ( + Method::POST, + "/session/{sessionId}/servo/prefs/set", + ServoExtensionRoute::SetPrefs, + ), + ( + Method::POST, + "/session/{sessionId}/servo/prefs/reset", + ServoExtensionRoute::ResetPrefs, + ), + ]; } fn cookie_msg_to_cookie(cookie: cookie_rs::Cookie) -> Cookie { @@ -77,7 +91,9 @@ fn cookie_msg_to_cookie(cookie: cookie_rs::Cookie) -> Cookie { value: cookie.value().to_owned(), path: cookie.path().map(|s| s.to_owned()), domain: cookie.domain().map(|s| s.to_owned()), - expiry: cookie.expires().map(|time| Date(time.to_timespec().sec as u64)), + expiry: cookie + .expires() + .map(|time| Date(time.to_timespec().sec as u64)), secure: cookie.secure().unwrap_or(false), httpOnly: cookie.http_only().unwrap_or(false), } @@ -93,7 +109,8 @@ pub fn start_server(port: u16, constellation_chan: Sender<ConstellationMsg>) { Ok(listening) => info!("WebDriver server listening on {}", listening.socket), Err(_) => panic!("Unable to start WebDriver HTTPD server"), } - }).expect("Thread spawning failed"); + }) + .expect("Thread spawning failed"); } /// Represents the current WebDriver session and holds relevant session state. @@ -147,9 +164,11 @@ enum ServoExtensionRoute { impl WebDriverExtensionRoute for ServoExtensionRoute { type Command = ServoExtensionCommand; - fn command(&self, - _captures: &Captures, - body_data: &Value) -> WebDriverResult<WebDriverCommand<ServoExtensionCommand>> { + fn command( + &self, + _captures: &Captures, + body_data: &Value, + ) -> WebDriverResult<WebDriverCommand<ServoExtensionCommand>> { let command = match *self { ServoExtensionRoute::GetPrefs => { let parameters: GetPrefsParameters = serde_json::from_value(body_data.clone())?; @@ -226,7 +245,6 @@ impl<'de> Deserialize<'de> for WebDriverPrefValue { { struct Visitor; - impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = WebDriverPrefValue; @@ -274,7 +292,6 @@ impl<'de> Deserialize<'de> for WebDriverPrefValue { } } - #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] struct GetPrefsParameters { prefs: Vec<String>, @@ -287,14 +304,15 @@ struct SetPrefsParameters { } fn map_to_vec<'de, D>(de: D) -> Result<Vec<(String, WebDriverPrefValue)>, D::Error> - where D: Deserializer<'de> { +where + D: Deserializer<'de>, +{ de.deserialize_map(TupleVecMapVisitor) } struct TupleVecMapVisitor; -impl<'de> Visitor<'de> for TupleVecMapVisitor -{ +impl<'de> Visitor<'de> for TupleVecMapVisitor { type Value = Vec<(String, WebDriverPrefValue)>; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { @@ -383,8 +401,12 @@ impl Handler { let mut capabilities = serde_json::Map::new(); capabilities.insert("browserName".to_owned(), serde_json::to_value("servo")?); capabilities.insert("browserVersion".to_owned(), serde_json::to_value("0.0.1")?); - capabilities.insert("acceptInsecureCerts".to_owned(), serde_json::to_value(false)?); - let response = NewSessionResponse::new(session.id.to_string(), Value::Object(capabilities)); + capabilities.insert( + "acceptInsecureCerts".to_owned(), + serde_json::to_value(false)?, + ); + let response = + NewSessionResponse::new(session.id.to_string(), Value::Object(capabilities)); debug!("new session created {}.", session.id); self.session = Some(session); Ok(WebDriverResponse::NewSession(response)) @@ -477,7 +499,9 @@ impl Handler { let url = receiver.recv().unwrap(); - Ok(WebDriverResponse::Generic(ValueResponse(serde_json::to_value(url.as_str())?))) + Ok(WebDriverResponse::Generic(ValueResponse( + serde_json::to_value(url.as_str())?, + ))) } fn handle_window_size(&self) -> WebDriverResult<WebDriverResponse> { @@ -554,8 +578,13 @@ impl Handler { ))?; match receiver.recv().unwrap() { - Ok(is_enabled) => Ok(WebDriverResponse::Generic(ValueResponse(serde_json::to_value(is_enabled)?))), - Err(_) => Err(WebDriverError::new(ErrorStatus::StaleElementReference, "Element not found")) + Ok(is_enabled) => Ok(WebDriverResponse::Generic(ValueResponse( + serde_json::to_value(is_enabled)?, + ))), + Err(_) => Err(WebDriverError::new( + ErrorStatus::StaleElementReference, + "Element not found", + )), } } @@ -568,8 +597,13 @@ impl Handler { ))?; match receiver.recv().unwrap() { - Ok(is_selected) => Ok(WebDriverResponse::Generic(ValueResponse(serde_json::to_value(is_selected)?))), - Err(_) => Err(WebDriverError::new(ErrorStatus::StaleElementReference, "Element not found")) + Ok(is_selected) => Ok(WebDriverResponse::Generic(ValueResponse( + serde_json::to_value(is_selected)?, + ))), + Err(_) => Err(WebDriverError::new( + ErrorStatus::StaleElementReference, + "Element not found", + )), } } @@ -608,21 +642,29 @@ impl Handler { self.top_level_script_command(WebDriverScriptCommand::GetTitle(sender))?; let value = receiver.recv().unwrap(); - Ok(WebDriverResponse::Generic(ValueResponse(serde_json::to_value(value)?))) + Ok(WebDriverResponse::Generic(ValueResponse( + serde_json::to_value(value)?, + ))) } fn handle_window_handle(&self) -> WebDriverResult<WebDriverResponse> { // For now we assume there's only one window so just use the session // id as the window id let handle = self.session.as_ref().unwrap().id.to_string(); - Ok(WebDriverResponse::Generic(ValueResponse(serde_json::to_value(handle)?))) + Ok(WebDriverResponse::Generic(ValueResponse( + serde_json::to_value(handle)?, + ))) } fn handle_window_handles(&self) -> WebDriverResult<WebDriverResponse> { // For now we assume there's only one window so just use the session // id as the window id - let handles = vec![serde_json::to_value(self.session.as_ref().unwrap().id.to_string())?]; - Ok(WebDriverResponse::Generic(ValueResponse(serde_json::to_value(handles)?))) + let handles = vec![serde_json::to_value( + self.session.as_ref().unwrap().id.to_string(), + )?]; + Ok(WebDriverResponse::Generic(ValueResponse( + serde_json::to_value(handles)?, + ))) } fn handle_find_element( @@ -644,12 +686,14 @@ impl Handler { match receiver.recv().unwrap() { Ok(value) => { let value_resp = serde_json::to_value( - value.map(|x| serde_json::to_value(WebElement::new(x)).unwrap()) + value.map(|x| serde_json::to_value(WebElement::new(x)).unwrap()), )?; Ok(WebDriverResponse::Generic(ValueResponse(value_resp))) - } - Err(_) => Err(WebDriverError::new(ErrorStatus::InvalidSelector, - "Invalid selector")) + }, + Err(_) => Err(WebDriverError::new( + ErrorStatus::InvalidSelector, + "Invalid selector", + )), } } @@ -666,7 +710,7 @@ impl Handler { return Ok(WebDriverResponse::Void); }, Some(FrameId::Short(ref x)) => WebDriverFrameId::Short(*x), - Some(FrameId::Element(ref x)) => WebDriverFrameId::Element(x.id.clone()) + Some(FrameId::Element(ref x)) => WebDriverFrameId::Element(x.id.clone()), }; self.switch_to_frame(frame_id) @@ -716,12 +760,18 @@ impl Handler { self.browsing_context_script_command(cmd)?; match receiver.recv().unwrap() { Ok(value) => { - let resp_value: Vec<Value> = value.into_iter().map( - |x| serde_json::to_value(WebElement::new(x)).unwrap()).collect(); - Ok(WebDriverResponse::Generic(ValueResponse(serde_json::to_value(resp_value)?))) - } - Err(_) => Err(WebDriverError::new(ErrorStatus::InvalidSelector, - "Invalid selector")) + let resp_value: Vec<Value> = value + .into_iter() + .map(|x| serde_json::to_value(WebElement::new(x)).unwrap()) + .collect(); + Ok(WebDriverResponse::Generic(ValueResponse( + serde_json::to_value(resp_value)?, + ))) + }, + Err(_) => Err(WebDriverError::new( + ErrorStatus::InvalidSelector, + "Invalid selector", + )), } } @@ -752,9 +802,13 @@ impl Handler { let cmd = WebDriverScriptCommand::GetElementText(element.id.clone(), sender); self.browsing_context_script_command(cmd)?; match receiver.recv().unwrap() { - Ok(value) => Ok(WebDriverResponse::Generic(ValueResponse(serde_json::to_value(value)?))), - Err(_) => Err(WebDriverError::new(ErrorStatus::StaleElementReference, - "Unable to find element in document")) + Ok(value) => Ok(WebDriverResponse::Generic(ValueResponse( + serde_json::to_value(value)?, + ))), + Err(_) => Err(WebDriverError::new( + ErrorStatus::StaleElementReference, + "Unable to find element in document", + )), } } @@ -762,8 +816,13 @@ impl Handler { let (sender, receiver) = ipc::channel().unwrap(); let cmd = WebDriverScriptCommand::GetActiveElement(sender); self.browsing_context_script_command(cmd)?; - let value = receiver.recv().unwrap().map(|x| serde_json::to_value(WebElement::new(x)).unwrap()); - Ok(WebDriverResponse::Generic(ValueResponse(serde_json::to_value(value)?))) + let value = receiver + .recv() + .unwrap() + .map(|x| serde_json::to_value(WebElement::new(x)).unwrap()); + Ok(WebDriverResponse::Generic(ValueResponse( + serde_json::to_value(value)?, + ))) } fn handle_element_tag_name(&self, element: &WebElement) -> WebDriverResult<WebDriverResponse> { @@ -771,9 +830,13 @@ impl Handler { let cmd = WebDriverScriptCommand::GetElementTagName(element.id.clone(), sender); self.browsing_context_script_command(cmd)?; match receiver.recv().unwrap() { - Ok(value) => Ok(WebDriverResponse::Generic(ValueResponse(serde_json::to_value(value)?))), - Err(_) => Err(WebDriverError::new(ErrorStatus::StaleElementReference, - "Unable to find element in document")) + Ok(value) => Ok(WebDriverResponse::Generic(ValueResponse( + serde_json::to_value(value)?, + ))), + Err(_) => Err(WebDriverError::new( + ErrorStatus::StaleElementReference, + "Unable to find element in document", + )), } } @@ -790,9 +853,13 @@ impl Handler { ); self.browsing_context_script_command(cmd)?; match receiver.recv().unwrap() { - Ok(value) => Ok(WebDriverResponse::Generic(ValueResponse(serde_json::to_value(value)?))), - Err(_) => Err(WebDriverError::new(ErrorStatus::StaleElementReference, - "Unable to find element in document")) + Ok(value) => Ok(WebDriverResponse::Generic(ValueResponse( + serde_json::to_value(value)?, + ))), + Err(_) => Err(WebDriverError::new( + ErrorStatus::StaleElementReference, + "Unable to find element in document", + )), } } @@ -806,9 +873,13 @@ impl Handler { WebDriverScriptCommand::GetElementCSS(element.id.clone(), name.to_owned(), sender); self.browsing_context_script_command(cmd)?; match receiver.recv().unwrap() { - Ok(value) => Ok(WebDriverResponse::Generic(ValueResponse(serde_json::to_value(value)?))), - Err(_) => Err(WebDriverError::new(ErrorStatus::StaleElementReference, - "Unable to find element in document")) + Ok(value) => Ok(WebDriverResponse::Generic(ValueResponse( + serde_json::to_value(value)?, + ))), + Err(_) => Err(WebDriverError::new( + ErrorStatus::StaleElementReference, + "Unable to find element in document", + )), } } @@ -817,9 +888,10 @@ impl Handler { let cmd = WebDriverScriptCommand::GetCookies(sender); self.browsing_context_script_command(cmd)?; let cookies = receiver.recv().unwrap(); - let response = cookies.into_iter().map(|cookie| { - cookie_msg_to_cookie(cookie.into_inner()) - }).collect::<Vec<Cookie>>(); + let response = cookies + .into_iter() + .map(|cookie| cookie_msg_to_cookie(cookie.into_inner())) + .collect::<Vec<Cookie>>(); Ok(WebDriverResponse::Cookies(CookiesResponse(response))) } @@ -828,9 +900,11 @@ impl Handler { let cmd = WebDriverScriptCommand::GetCookie(name.to_owned(), sender); self.browsing_context_script_command(cmd)?; let cookies = receiver.recv().unwrap(); - let response = cookies.into_iter().map(|cookie| { - cookie_msg_to_cookie(cookie.into_inner()) - }).next().unwrap(); + let response = cookies + .into_iter() + .map(|cookie| cookie_msg_to_cookie(cookie.into_inner())) + .next() + .unwrap(); Ok(WebDriverResponse::Cookie(CookieResponse(response))) } @@ -936,8 +1010,9 @@ impl Handler { result: WebDriverJSResult, ) -> WebDriverResult<WebDriverResponse> { match result { - Ok(value) => - Ok(WebDriverResponse::Generic(ValueResponse(serde_json::to_value(SendableWebDriverJSValue(value))?))), + Ok(value) => Ok(WebDriverResponse::Generic(ValueResponse( + serde_json::to_value(SendableWebDriverJSValue(value))?, + ))), Err(WebDriverJSError::Timeout) => Err(WebDriverError::new(ErrorStatus::Timeout, "")), Err(WebDriverJSError::UnknownType) => Err(WebDriverError::new( ErrorStatus::UnsupportedOperation, @@ -1032,7 +1107,9 @@ impl Handler { .unwrap(); let encoded = base64::encode(&png_data); - Ok(WebDriverResponse::Generic(ValueResponse(serde_json::to_value(encoded)?))) + Ok(WebDriverResponse::Generic(ValueResponse( + serde_json::to_value(encoded)?, + ))) } fn handle_get_prefs( @@ -1045,7 +1122,9 @@ impl Handler { .map(|item| (item.clone(), serde_json::to_value(PREFS.get(item)).unwrap())) .collect::<BTreeMap<_, _>>(); - Ok(WebDriverResponse::Generic(ValueResponse(serde_json::to_value(prefs)?))) + Ok(WebDriverResponse::Generic(ValueResponse( + serde_json::to_value(prefs)?, + ))) } fn handle_set_prefs( @@ -1069,10 +1148,17 @@ impl Handler { parameters .prefs .iter() - .map(|item| (item.clone(), serde_json::to_value(PREFS.reset(item)).unwrap())) + .map(|item| { + ( + item.clone(), + serde_json::to_value(PREFS.reset(item)).unwrap(), + ) + }) .collect::<BTreeMap<_, _>>() }; - Ok(WebDriverResponse::Generic(ValueResponse(serde_json::to_value(prefs)?))) + Ok(WebDriverResponse::Generic(ValueResponse( + serde_json::to_value(prefs)?, + ))) } } @@ -1148,7 +1234,10 @@ impl WebDriverHandler<ServoExtensionRoute> for Handler { fn delete_session(&mut self, _session: &Option<Session>) { // Servo doesn't support multiple sessions, so we exit on session deletion - let _ = self.constellation_chan.send(ConstellationMsg::Exit).unwrap(); + let _ = self + .constellation_chan + .send(ConstellationMsg::Exit) + .unwrap(); self.session = None; } } diff --git a/components/webvr/webvr_thread.rs b/components/webvr/webvr_thread.rs index 55d7e31c7c6..cdfd4f6140a 100644 --- a/components/webvr/webvr_thread.rs +++ b/components/webvr/webvr_thread.rs @@ -82,8 +82,10 @@ impl WebVRThread { sender_clone, constellation_chan, vr_compositor_chan, - ).start(); - }).expect("Thread spawning failed"); + ) + .start(); + }) + .expect("Thread spawning failed"); (sender, constellation_sender) } @@ -263,7 +265,8 @@ impl WebVRThread { Some(g.data()) }; (data, g.state()) - }).collect(); + }) + .collect(); sender.send(Ok(data)).unwrap(); } @@ -324,7 +327,8 @@ impl WebVRThread { } thread::sleep(time::Duration::from_millis(polling_interval)); } - }).expect("Thread spawning failed"); + }) + .expect("Thread spawning failed"); } } diff --git a/ports/libmlservo/src/lib.rs b/ports/libmlservo/src/lib.rs index 2f8873716d4..39e6f2af481 100644 --- a/ports/libmlservo/src/lib.rs +++ b/ports/libmlservo/src/lib.rs @@ -3,7 +3,8 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate egl; -#[macro_use] extern crate log; +#[macro_use] +extern crate log; extern crate servo; extern crate smallvec; @@ -62,10 +63,10 @@ pub enum MLLogLevel { } #[repr(transparent)] -pub struct MLLogger(extern "C" fn (MLLogLevel, *const c_char)); +pub struct MLLogger(extern "C" fn(MLLogLevel, *const c_char)); #[repr(transparent)] -pub struct MLHistoryUpdate(extern "C" fn (MLApp, bool, *const c_char, bool)); +pub struct MLHistoryUpdate(extern "C" fn(MLApp, bool, *const c_char, bool)); #[repr(transparent)] #[derive(Clone, Copy)] @@ -74,17 +75,18 @@ pub struct MLApp(*mut c_void); const LOG_LEVEL: log::LevelFilter = log::LevelFilter::Info; #[no_mangle] -pub unsafe extern "C" fn init_servo(ctxt: EGLContext, - surf: EGLSurface, - disp: EGLDisplay, - app: MLApp, - logger: MLLogger, - history_update: MLHistoryUpdate, - url: *const c_char, - width: u32, - height: u32, - hidpi: f32) -> *mut ServoInstance -{ +pub unsafe extern "C" fn init_servo( + ctxt: EGLContext, + surf: EGLSurface, + disp: EGLDisplay, + app: MLApp, + logger: MLLogger, + history_update: MLHistoryUpdate, + url: *const c_char, + width: u32, + height: u32, + hidpi: f32, +) -> *mut ServoInstance { // Servo initialization goes here! servo::embedder_traits::resources::set(Box::new(ResourceReaderInstance::new())); let _ = log::set_boxed_logger(Box::new(logger)); @@ -112,9 +114,7 @@ pub unsafe extern "C" fn init_servo(ctxt: EGLContext, let blank_url = ServoUrl::parse("about:blank").expect("Failed to parse about:blank!"); let url = CStr::from_ptr(url).to_str().unwrap_or("about:blank"); let url = ServoUrl::parse(url).unwrap_or(blank_url); - servo.handle_events(vec![ - WindowEvent::NewBrowser(url, browser_id), - ]); + servo.handle_events(vec![WindowEvent::NewBrowser(url, browser_id)]); let result = Box::new(ServoInstance { app: app, @@ -157,7 +157,12 @@ pub unsafe extern "C" fn heartbeat_servo(servo: *mut ServoInstance) { if let Ok(cstr) = CString::new(url.as_str()) { let can_go_back = index > 0; let can_go_fwd = (index + 1) < urls.len(); - (servo.history_update.0)(servo.app, can_go_back, cstr.as_ptr(), can_go_fwd); + (servo.history_update.0)( + servo.app, + can_go_back, + cstr.as_ptr(), + can_go_fwd, + ); } } }, @@ -204,13 +209,17 @@ pub unsafe extern "C" fn move_servo(servo: *mut ServoInstance, x: f32, y: f32) { ScrollState::TriggerUp, WindowEvent::MouseWindowMoveEventClass(point), ), - ScrollState::TriggerDown(start) if (start - point).square_length() < DRAG_CUTOFF_SQUARED => return, + ScrollState::TriggerDown(start) + if (start - point).square_length() < DRAG_CUTOFF_SQUARED => + { + return + }, ScrollState::TriggerDown(start) => ( ScrollState::TriggerDragging(start, point), WindowEvent::Scroll( ScrollLocation::Delta((point - start) * servo.scroll_scale), start.to_i32(), - TouchEventType::Down + TouchEventType::Down, ), ), ScrollState::TriggerDragging(start, prev) => ( @@ -218,7 +227,7 @@ pub unsafe extern "C" fn move_servo(servo: *mut ServoInstance, x: f32, y: f32) { WindowEvent::Scroll( ScrollLocation::Delta((point - prev) * servo.scroll_scale), start.to_i32(), - TouchEventType::Move + TouchEventType::Move, ), ), }; @@ -235,16 +244,22 @@ pub unsafe extern "C" fn trigger_servo(servo: *mut ServoInstance, x: f32, y: f32 let (new_state, window_events) = match servo.scroll_state { ScrollState::TriggerUp if down => ( ScrollState::TriggerDown(point), - vec![ - WindowEvent::MouseWindowEventClass(MouseWindowEvent::MouseDown(MouseButton::Left, point)), - ], + vec![WindowEvent::MouseWindowEventClass( + MouseWindowEvent::MouseDown(MouseButton::Left, point), + )], ), ScrollState::TriggerDown(start) if !down => ( ScrollState::TriggerUp, vec![ - WindowEvent::MouseWindowEventClass(MouseWindowEvent::MouseUp(MouseButton::Left, start)), - WindowEvent::MouseWindowEventClass(MouseWindowEvent::Click(MouseButton::Left, start)), - WindowEvent::MouseWindowMoveEventClass(point), + WindowEvent::MouseWindowEventClass(MouseWindowEvent::MouseUp( + MouseButton::Left, + start, + )), + WindowEvent::MouseWindowEventClass(MouseWindowEvent::Click( + MouseButton::Left, + start, + )), + WindowEvent::MouseWindowMoveEventClass(point), ], ), ScrollState::TriggerDragging(start, prev) if !down => ( @@ -253,9 +268,12 @@ pub unsafe extern "C" fn trigger_servo(servo: *mut ServoInstance, x: f32, y: f32 WindowEvent::Scroll( ScrollLocation::Delta((point - prev) * servo.scroll_scale), start.to_i32(), - TouchEventType::Up + TouchEventType::Up, ), - WindowEvent::MouseWindowEventClass(MouseWindowEvent::MouseUp(MouseButton::Left, point)), + WindowEvent::MouseWindowEventClass(MouseWindowEvent::MouseUp( + MouseButton::Left, + point, + )), WindowEvent::MouseWindowMoveEventClass(point), ], ), @@ -275,7 +293,10 @@ pub unsafe extern "C" fn traverse_servo(servo: *mut ServoInstance, delta: i32) { } else if delta < 0 { WindowEvent::Navigation(servo.browser_id, TraversalDirection::Back(-delta as usize)) } else { - WindowEvent::Navigation(servo.browser_id, TraversalDirection::Forward(delta as usize)) + WindowEvent::Navigation( + servo.browser_id, + TraversalDirection::Forward(delta as usize), + ) }; servo.servo.handle_events(vec![window_event]); } @@ -284,11 +305,13 @@ pub unsafe extern "C" fn traverse_servo(servo: *mut ServoInstance, delta: i32) { #[no_mangle] pub unsafe extern "C" fn navigate_servo(servo: *mut ServoInstance, text: *const c_char) { if let Some(servo) = servo.as_mut() { - let text = CStr::from_ptr(text).to_str().expect("Failed to convert text to UTF-8"); + let text = CStr::from_ptr(text) + .to_str() + .expect("Failed to convert text to UTF-8"); let url = ServoUrl::parse(text).unwrap_or_else(|_| { let mut search = ServoUrl::parse("http://google.com/search") - .expect("Failed to parse search URL") - .into_url(); + .expect("Failed to parse search URL") + .into_url(); search.query_pairs_mut().append_pair("q", text); ServoUrl::from_url(search) }); @@ -314,8 +337,8 @@ pub unsafe extern "C" fn discard_servo(servo: *mut ServoInstance) { } } if Instant::now() > finish { - warn!("Incomplete shutdown."); - break 'outer; + warn!("Incomplete shutdown."); + break 'outer; } thread::sleep(SHUTDOWN_POLL_INTERVAL); servo.servo.handle_events(vec![]); @@ -345,9 +368,9 @@ struct WindowInstance { #[derive(Clone, Copy)] enum ScrollState { - TriggerUp, - TriggerDown(DevicePoint), - TriggerDragging(DevicePoint, DevicePoint), + TriggerUp, + TriggerDown(DevicePoint), + TriggerDragging(DevicePoint, DevicePoint), } impl WindowMethods for WindowInstance { @@ -357,7 +380,8 @@ impl WindowMethods for WindowInstance { fn prepare_for_composite(&self) -> bool { MakeCurrent(self.disp, self.surf, self.surf, self.ctxt); - self.gl.viewport(0, 0, self.width as i32, self.height as i32); + self.gl + .viewport(0, 0, self.width as i32, self.height as i32); true } @@ -374,14 +398,19 @@ impl WindowMethods for WindowInstance { hidpi_factor: TypedScale::new(self.hidpi), screen: TypedSize2D::new(self.width, self.height), screen_avail: TypedSize2D::new(self.width, self.height), - window: (TypedSize2D::new(self.width, self.height), TypedPoint2D::new(0, 0)), + window: ( + TypedSize2D::new(self.width, self.height), + TypedPoint2D::new(0, 0), + ), framebuffer: TypedSize2D::new(self.width, self.height), - viewport: TypedRect::new(TypedPoint2D::new(0, 0), TypedSize2D::new(self.width, self.height)), + viewport: TypedRect::new( + TypedPoint2D::new(0, 0), + TypedSize2D::new(self.width, self.height), + ), } } - fn set_animation_state(&self, _state: AnimationState) { - } + fn set_animation_state(&self, _state: AnimationState) {} } struct EventLoopWakerInstance; @@ -397,8 +426,7 @@ impl EventLoopWaker for EventLoopWakerInstance { Box::new(EventLoopWakerInstance) } - fn wake(&self) { - } + fn wake(&self) {} } struct ResourceReaderInstance; @@ -413,17 +441,23 @@ impl ResourceReaderMethods for ResourceReaderInstance { fn read(&self, res: Resource) -> Vec<u8> { Vec::from(match res { Resource::Preferences => &include_bytes!("../../../resources/prefs.json")[..], - Resource::HstsPreloadList => &include_bytes!("../../../resources/hsts_preload.json")[..], + Resource::HstsPreloadList => { + &include_bytes!("../../../resources/hsts_preload.json")[..] + }, Resource::SSLCertificates => &include_bytes!("../../../resources/certs")[..], Resource::BadCertHTML => &include_bytes!("../../../resources/badcert.html")[..], Resource::NetErrorHTML => &include_bytes!("../../../resources/neterror.html")[..], Resource::UserAgentCSS => &include_bytes!("../../../resources/user-agent.css")[..], Resource::ServoCSS => &include_bytes!("../../../resources/servo.css")[..], - Resource::PresentationalHintsCSS => &include_bytes!("../../../resources/presentational-hints.css")[..], + Resource::PresentationalHintsCSS => { + &include_bytes!("../../../resources/presentational-hints.css")[..] + }, Resource::QuirksModeCSS => &include_bytes!("../../../resources/quirks-mode.css")[..], Resource::RippyPNG => &include_bytes!("../../../resources/rippy.png")[..], Resource::DomainList => &include_bytes!("../../../resources/public_domains.txt")[..], - Resource::BluetoothBlocklist => &include_bytes!("../../../resources/gatt_blocklist.txt")[..], + Resource::BluetoothBlocklist => { + &include_bytes!("../../../resources/gatt_blocklist.txt")[..] + }, }) } diff --git a/ports/libsimpleservo/src/api.rs b/ports/libsimpleservo/src/api.rs index beac00cb81d..8ecc9ed6eb1 100644 --- a/ports/libsimpleservo/src/api.rs +++ b/ports/libsimpleservo/src/api.rs @@ -112,9 +112,8 @@ pub fn init( resources::set(Box::new(ResourceReader(readfile))); if let Some(args) = init_opts.args { - let mut args: Vec<String> = serde_json::from_str(&args).map_err(|_| { - "Invalid arguments. Servo arguments must be formatted as a JSON array" - })?; + let mut args: Vec<String> = serde_json::from_str(&args) + .map_err(|_| "Invalid arguments. Servo arguments must be formatted as a JSON array")?; // opts::from_cmdline_args expects the first argument to be the binary name. args.insert(0, "servo".to_string()); @@ -123,19 +122,19 @@ pub fn init( opts::from_cmdline_args(&args); } - let embedder_url = init_opts.url.as_ref().and_then(|s| { - ServoUrl::parse(s).ok() - }); + let embedder_url = init_opts.url.as_ref().and_then(|s| ServoUrl::parse(s).ok()); let cmdline_url = opts::get().url.clone(); - let pref_url = PREFS.get("shell.homepage").as_string().and_then(|s| { - ServoUrl::parse(s).ok() - }); + let pref_url = PREFS + .get("shell.homepage") + .as_string() + .and_then(|s| ServoUrl::parse(s).ok()); let blank_url = ServoUrl::parse("about:blank").ok(); let url = embedder_url .or(cmdline_url) .or(pref_url) - .or(blank_url).unwrap(); + .or(blank_url) + .unwrap(); gl.clear_color(1.0, 1.0, 1.0, 1.0); gl.clear(gl::COLOR_BUFFER_BIT); @@ -171,16 +170,14 @@ pub fn init( } pub fn deinit() { - SERVO.with(|s| { - s.replace(None).unwrap().deinit() - }); + SERVO.with(|s| s.replace(None).unwrap().deinit()); } impl ServoGlue { fn get_browser_id(&self) -> Result<BrowserId, &'static str> { let browser_id = match self.browser_id { Some(id) => id, - None => return Err("No BrowserId set yet.") + None => return Err("No BrowserId set yet."), }; Ok(browser_id) } @@ -417,7 +414,8 @@ impl ServoGlue { let _ = self.browsers.pop(); if let Some(prev_browser_id) = self.browsers.last() { self.browser_id = Some(*prev_browser_id); - self.events.push(WindowEvent::SelectBrowser(*prev_browser_id)); + self.events + .push(WindowEvent::SelectBrowser(*prev_browser_id)); } else { self.events.push(WindowEvent::Quit); } @@ -476,7 +474,8 @@ impl WindowMethods for ServoCallbacks { fn set_animation_state(&self, state: AnimationState) { debug!("WindowMethods::set_animation_state"); - self.host_callbacks.on_animating_changed(state == AnimationState::Animating); + self.host_callbacks + .on_animating_changed(state == AnimationState::Animating); } fn get_coordinates(&self) -> EmbedderCoordinates { diff --git a/ports/libsimpleservo/src/capi.rs b/ports/libsimpleservo/src/capi.rs index c0834b8c76d..b5b1f393924 100644 --- a/ports/libsimpleservo/src/capi.rs +++ b/ports/libsimpleservo/src/capi.rs @@ -10,7 +10,10 @@ use std::mem; use std::os::raw::c_char; use std::rc::Rc; -fn call<F>(f: F) where F: Fn(&mut ServoGlue) -> Result<(), &'static str> { +fn call<F>(f: F) +where + F: Fn(&mut ServoGlue) -> Result<(), &'static str>, +{ SERVO.with(|s| { if let Err(error) = match s.borrow_mut().as_mut() { Some(ref mut s) => (f)(s), @@ -27,15 +30,15 @@ fn call<F>(f: F) where F: Fn(&mut ServoGlue) -> Result<(), &'static str> { /// Callback used by Servo internals #[repr(C)] pub struct CHostCallbacks { - pub flush: extern fn(), - pub make_current: extern fn(), - pub on_load_started: extern fn(), - pub on_load_ended: extern fn(), - pub on_title_changed: extern fn(title: *const c_char), - pub on_url_changed: extern fn(url: *const c_char), - pub on_history_changed: extern fn(can_go_back: bool, can_go_forward: bool), - pub on_animating_changed: extern fn(animating: bool), - pub on_shutdown_complete: extern fn(), + pub flush: extern "C" fn(), + pub make_current: extern "C" fn(), + pub on_load_started: extern "C" fn(), + pub on_load_ended: extern "C" fn(), + pub on_title_changed: extern "C" fn(title: *const c_char), + pub on_url_changed: extern "C" fn(url: *const c_char), + pub on_history_changed: extern "C" fn(can_go_back: bool, can_go_forward: bool), + pub on_animating_changed: extern "C" fn(animating: bool), + pub on_shutdown_complete: extern "C" fn(), } /// Servo options @@ -62,9 +65,10 @@ pub extern "C" fn servo_version() -> *const c_char { fn init( opts: CInitOptions, gl: Rc<gl::Gl>, - wakeup: extern fn(), - readfile: extern fn(*const c_char) -> *const c_char, - callbacks: CHostCallbacks) { + wakeup: extern "C" fn(), + readfile: extern "C" fn(*const c_char) -> *const c_char, + callbacks: CHostCallbacks, +) { let args = unsafe { CStr::from_ptr(opts.args) }; let args = args.to_str().map(|s| s.to_string()).ok(); @@ -91,20 +95,26 @@ fn init( #[no_mangle] pub extern "C" fn init_with_egl( opts: CInitOptions, - wakeup: extern fn(), - readfile: extern fn(*const c_char) -> *const c_char, - callbacks: CHostCallbacks) { + wakeup: extern "C" fn(), + readfile: extern "C" fn(*const c_char) -> *const c_char, + callbacks: CHostCallbacks, +) { let gl = gl_glue::egl::init().unwrap(); init(opts, gl, wakeup, readfile, callbacks) } -#[cfg(any(target_os = "linux", target_os = "windows", target_os = "macos"))] +#[cfg(any( + target_os = "linux", + target_os = "windows", + target_os = "macos" +))] #[no_mangle] pub extern "C" fn init_with_gl( opts: CInitOptions, - wakeup: extern fn(), - readfile: extern fn(*const c_char) -> *const c_char, - callbacks: CHostCallbacks) { + wakeup: extern "C" fn(), + readfile: extern "C" fn(*const c_char) -> *const c_char, + callbacks: CHostCallbacks, +) { let gl = gl_glue::gl::init().unwrap(); init(opts, gl, wakeup, readfile, callbacks) } @@ -219,10 +229,10 @@ pub extern "C" fn click(x: i32, y: i32) { call(|s| s.click(x as u32, y as u32)); } -pub struct WakeupCallback(extern fn()); +pub struct WakeupCallback(extern "C" fn()); impl WakeupCallback { - fn new(callback: extern fn()) -> WakeupCallback { + fn new(callback: extern "C" fn()) -> WakeupCallback { WakeupCallback(callback) } } @@ -236,10 +246,10 @@ impl EventLoopWaker for WakeupCallback { } } -pub struct ReadFileCallback(extern fn(*const c_char) -> *const c_char); +pub struct ReadFileCallback(extern "C" fn(*const c_char) -> *const c_char); impl ReadFileCallback { - fn new(callback: extern fn(*const c_char) -> *const c_char) -> ReadFileCallback { + fn new(callback: extern "C" fn(*const c_char) -> *const c_char) -> ReadFileCallback { ReadFileCallback(callback) } } diff --git a/ports/libsimpleservo/src/gl_glue.rs b/ports/libsimpleservo/src/gl_glue.rs index 39ea281724a..3d8903a4e10 100644 --- a/ports/libsimpleservo/src/gl_glue.rs +++ b/ports/libsimpleservo/src/gl_glue.rs @@ -22,7 +22,11 @@ pub mod egl { pub type EGLNativeWindowType = *const libc::c_void; #[cfg(target_os = "android")] pub type EGLNativeWindowType = *const libc::c_void; - #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "openbsd" + ))] pub type EGLNativeWindowType = *const libc::c_void; pub type khronos_utime_nanoseconds_t = khronos_uint64_t; @@ -77,7 +81,11 @@ pub mod egl { } } -#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))] +#[cfg(any( + target_os = "windows", + target_os = "linux", + target_os = "macos" +))] pub mod gl { use servo::gl::Gl; use std::rc::Rc; diff --git a/ports/libsimpleservo/src/jniapi.rs b/ports/libsimpleservo/src/jniapi.rs index aca073640b9..27bc375d28c 100644 --- a/ports/libsimpleservo/src/jniapi.rs +++ b/ports/libsimpleservo/src/jniapi.rs @@ -55,7 +55,7 @@ pub fn Java_org_mozilla_servoview_JNIServo_init( Err(err) => { throw(&env, &err); return; - } + }, }; if log { @@ -95,7 +95,7 @@ pub fn Java_org_mozilla_servoview_JNIServo_init( Err(_) => { throw(&env, "Failed to get global reference of callback argument"); return; - } + }, }; let wakeup = Box::new(WakeupCallback::new(callbacks_ref.clone(), &env)); @@ -110,11 +110,7 @@ pub fn Java_org_mozilla_servoview_JNIServo_init( } #[no_mangle] -pub fn Java_org_mozilla_servoview_JNIServo_setBatchMode( - env: JNIEnv, - _: JClass, - batch: jboolean, -) { +pub fn Java_org_mozilla_servoview_JNIServo_setBatchMode(env: JNIEnv, _: JClass, batch: jboolean) { debug!("setBatchMode"); call(&env, |s| s.set_batch_mode(batch == JNI_TRUE)); } @@ -158,7 +154,7 @@ pub fn Java_org_mozilla_servoview_JNIServo_loadUri(env: JNIEnv, _class: JClass, }, Err(_) => { throw(&env, "Failed to convert Java string"); - } + }, }; } @@ -202,7 +198,9 @@ pub fn Java_org_mozilla_servoview_JNIServo_scrollStart( y: jint, ) { debug!("scrollStart"); - call(&env, |s| s.scroll_start(dx as i32, dy as i32, x as u32, y as u32)); + call(&env, |s| { + s.scroll_start(dx as i32, dy as i32, x as u32, y as u32) + }); } #[no_mangle] @@ -215,10 +213,11 @@ pub fn Java_org_mozilla_servoview_JNIServo_scrollEnd( y: jint, ) { debug!("scrollEnd"); - call(&env, |s| s.scroll_end(dx as i32, dy as i32, x as u32, y as u32)); + call(&env, |s| { + s.scroll_end(dx as i32, dy as i32, x as u32, y as u32) + }); } - #[no_mangle] pub fn Java_org_mozilla_servoview_JNIServo_scroll( env: JNIEnv, @@ -241,7 +240,9 @@ pub fn Java_org_mozilla_servoview_JNIServo_pinchZoomStart( y: jint, ) { debug!("pinchZoomStart"); - call(&env, |s| s.pinchzoom_start(factor as f32, x as u32, y as u32)); + call(&env, |s| { + s.pinchzoom_start(factor as f32, x as u32, y as u32) + }); } #[no_mangle] @@ -268,7 +269,6 @@ pub fn Java_org_mozilla_servoview_JNIServo_pinchZoomEnd( call(&env, |s| s.pinchzoom_end(factor as f32, x as u32, y as u32)); } - #[no_mangle] pub fn Java_org_mozilla_servoview_JNIServo_click(env: JNIEnv, _: JClass, x: jint, y: jint) { debug!("click"); @@ -391,7 +391,8 @@ impl HostTrait for HostCallbacks { "onTitleChanged", "(Ljava/lang/String;)V", &[s], - ).unwrap(); + ) + .unwrap(); } fn on_url_changed(&self, url: String) { @@ -407,7 +408,8 @@ impl HostTrait for HostCallbacks { "onUrlChanged", "(Ljava/lang/String;)V", &[s], - ).unwrap(); + ) + .unwrap(); } fn on_history_changed(&self, can_go_back: bool, can_go_forward: bool) { @@ -420,7 +422,8 @@ impl HostTrait for HostCallbacks { "onHistoryChanged", "(ZZ)V", &[can_go_back, can_go_forward], - ).unwrap(); + ) + .unwrap(); } fn on_animating_changed(&self, animating: bool) { @@ -432,7 +435,8 @@ impl HostTrait for HostCallbacks { "onAnimatingChanged", "(Z)V", &[animating], - ).unwrap(); + ) + .unwrap(); } } @@ -441,17 +445,11 @@ fn initialize_android_glue(env: &JNIEnv, activity: JObject) { // From jni-rs to android_injected_glue - let mut app: ffi::android_app = unsafe { - std::mem::zeroed() - }; - let mut native_activity: ffi::ANativeActivity = unsafe { - std::mem::zeroed() - }; + let mut app: ffi::android_app = unsafe { std::mem::zeroed() }; + let mut native_activity: ffi::ANativeActivity = unsafe { std::mem::zeroed() }; let clazz = Box::into_raw(Box::new(env.new_global_ref(activity).unwrap())); - native_activity.clazz = unsafe { - (*clazz).as_obj().into_inner() as *mut c_void - }; + native_activity.clazz = unsafe { (*clazz).as_obj().into_inner() as *mut c_void }; let vm = env.get_java_vm().unwrap().get_java_vm_pointer(); native_activity.vm = vm as *mut ffi::_JavaVM; @@ -463,7 +461,7 @@ fn initialize_android_glue(env: &JNIEnv, activity: JObject) { } } -extern { +extern "C" { pub fn __android_log_write(prio: c_int, tag: *const c_char, text: *const c_char) -> c_int; } @@ -497,7 +495,11 @@ fn redirect_stdout_to_logcat() { let result = { let read_into = &mut buf[cursor..]; unsafe { - read(descriptor, read_into.as_mut_ptr() as *mut _, read_into.len()) + read( + descriptor, + read_into.as_mut_ptr() as *mut _, + read_into.len(), + ) } }; @@ -505,7 +507,11 @@ fn redirect_stdout_to_logcat() { return; } else if result < 0 { unsafe { - __android_log_write(3, tag, b"error in log thread; closing\0".as_ptr() as *const _); + __android_log_write( + 3, + tag, + b"error in log thread; closing\0".as_ptr() as *const _, + ); } return; } else { @@ -546,7 +552,10 @@ fn redirect_stdout_to_logcat() { fn throw(env: &JNIEnv, err: &str) { if let Err(e) = env.throw(("java/lang/Exception", err)) { - warn!("Failed to throw Java exception: `{}`. Exception was: `{}`", e, err); + warn!( + "Failed to throw Java exception: `{}`. Exception was: `{}`", + e, err + ); } } diff --git a/support/rust-task_info/src/lib.rs b/support/rust-task_info/src/lib.rs index 4c978291502..62a1164ff1d 100644 --- a/support/rust-task_info/src/lib.rs +++ b/support/rust-task_info/src/lib.rs @@ -11,4 +11,3 @@ #![crate_type = "rlib"] pub mod task_basic_info; - diff --git a/support/rust-task_info/src/task_basic_info.rs b/support/rust-task_info/src/task_basic_info.rs index 8eff98e20ee..a4379260881 100644 --- a/support/rust-task_info/src/task_basic_info.rs +++ b/support/rust-task_info/src/task_basic_info.rs @@ -18,22 +18,26 @@ type size_t = usize; /// Obtains task_basic_info::virtual_size. pub fn virtual_size() -> Option<usize> { let mut virtual_size: size_t = 0; - let rv = unsafe { - TaskBasicInfoVirtualSize(&mut virtual_size) - }; - if rv == 0 { Some(virtual_size as usize) } else { None } + let rv = unsafe { TaskBasicInfoVirtualSize(&mut virtual_size) }; + if rv == 0 { + Some(virtual_size as usize) + } else { + None + } } /// Obtains task_basic_info::resident_size. pub fn resident_size() -> Option<usize> { let mut resident_size: size_t = 0; - let rv = unsafe { - TaskBasicInfoResidentSize(&mut resident_size) - }; - if rv == 0 { Some(resident_size as usize) } else { None } + let rv = unsafe { TaskBasicInfoResidentSize(&mut resident_size) }; + if rv == 0 { + Some(resident_size as usize) + } else { + None + } } -extern { +extern "C" { fn TaskBasicInfoVirtualSize(virtual_size: *mut size_t) -> c_int; fn TaskBasicInfoResidentSize(resident_size: *mut size_t) -> c_int; } diff --git a/tests/unit/malloc_size_of/lib.rs b/tests/unit/malloc_size_of/lib.rs index 8aae5a40310..dd933402623 100644 --- a/tests/unit/malloc_size_of/lib.rs +++ b/tests/unit/malloc_size_of/lib.rs @@ -25,9 +25,9 @@ pub mod does_not_impl_malloc_size_of { ```compile_fail,E0277 extern crate malloc_size_of; extern crate servo_arc; - + fn sizeable<T: malloc_size_of::MallocSizeOf>() {} - + fn main() { sizeable::<servo_arc::Arc<i32>>(); } @@ -35,13 +35,12 @@ pub mod does_not_impl_malloc_size_of { */ pub fn servo_arc() {} - /** ```compile_fail,E0277 extern crate malloc_size_of; - + fn sizeable<T: malloc_size_of::MallocSizeOf>() {} - + fn main() { sizeable::<std::sync::Arc<i32>>(); } @@ -49,13 +48,12 @@ pub mod does_not_impl_malloc_size_of { */ pub fn std_arc() {} - /** ```compile_fail,E0277 extern crate malloc_size_of; - + fn sizeable<T: malloc_size_of::MallocSizeOf>() {} - + fn main() { sizeable::<std::rc::Rc<i32>>(); } @@ -69,9 +67,9 @@ pub mod does_not_impl_malloc_shallow_size_of { ```compile_fail,E0277 extern crate malloc_size_of; extern crate servo_arc; - + fn shallow_sizeable<T: malloc_size_of::MallocShallowSizeOf>() {} - + fn main() { shallow_sizeable::<servo_arc::Arc<i32>>(); } @@ -79,13 +77,12 @@ pub mod does_not_impl_malloc_shallow_size_of { */ pub fn servo_arc() {} - /** ```compile_fail,E0277 extern crate malloc_size_of; - + fn shallow_sizeable<T: malloc_size_of::MallocShallowSizeOf>() {} - + fn main() { shallow_sizeable::<std::sync::Arc<i32>>(); } @@ -93,13 +90,12 @@ pub mod does_not_impl_malloc_shallow_size_of { */ pub fn std_arc() {} - /** ```compile_fail,E0277 extern crate malloc_size_of; - + fn shallow_sizeable<T: malloc_size_of::MallocShallowSizeOf>() {} - + fn main() { shallow_sizeable::<std::rc::Rc<i32>>(); } diff --git a/tests/unit/metrics/interactive_time.rs b/tests/unit/metrics/interactive_time.rs index c8999df4b3b..c525ccdfc2c 100644 --- a/tests/unit/metrics/interactive_time.rs +++ b/tests/unit/metrics/interactive_time.rs @@ -16,14 +16,11 @@ impl ProfilerMetadataFactory for DummyProfilerMetadataFactory { } } - fn test_interactive() -> InteractiveMetrics { let (sender, _) = ipc::channel().unwrap(); let profiler_chan = ProfilerChan(sender); - let mut interactive = InteractiveMetrics::new( - profiler_chan, - ServoUrl::parse("about:blank").unwrap(), - ); + let mut interactive = + InteractiveMetrics::new(profiler_chan, ServoUrl::parse("about:blank").unwrap()); assert_eq!((&interactive).get_navigation_start(), None); assert_eq!(interactive.get_tti(), None); @@ -38,12 +35,18 @@ fn test_set_dcl() { let profiler_metadata_factory = DummyProfilerMetadataFactory {}; let interactive = test_interactive(); - interactive.maybe_set_tti(&profiler_metadata_factory, InteractiveFlag::DOMContentLoaded); + interactive.maybe_set_tti( + &profiler_metadata_factory, + InteractiveFlag::DOMContentLoaded, + ); let dcl = interactive.get_dom_content_loaded(); assert!(dcl.is_some()); //try to overwrite - interactive.maybe_set_tti(&profiler_metadata_factory, InteractiveFlag::DOMContentLoaded); + interactive.maybe_set_tti( + &profiler_metadata_factory, + InteractiveFlag::DOMContentLoaded, + ); assert_eq!(interactive.get_dom_content_loaded(), dcl); assert_eq!(interactive.get_tti(), None); } @@ -84,7 +87,10 @@ fn test_set_tti_dcl() { let mta = interactive.get_main_thread_available(); assert!(mta.is_some()); - interactive.maybe_set_tti(&profiler_metadata_factory, InteractiveFlag::DOMContentLoaded); + interactive.maybe_set_tti( + &profiler_metadata_factory, + InteractiveFlag::DOMContentLoaded, + ); let dcl = interactive.get_dom_content_loaded(); assert!(dcl.is_some()); @@ -97,7 +103,10 @@ fn test_set_tti_mta() { let profiler_metadata_factory = DummyProfilerMetadataFactory {}; let interactive = test_interactive(); - interactive.maybe_set_tti(&profiler_metadata_factory, InteractiveFlag::DOMContentLoaded); + interactive.maybe_set_tti( + &profiler_metadata_factory, + InteractiveFlag::DOMContentLoaded, + ); let dcl = interactive.get_dom_content_loaded(); assert!(dcl.is_some()); diff --git a/tests/unit/metrics/paint_time.rs b/tests/unit/metrics/paint_time.rs index 0207324a9c2..9112570fe7f 100644 --- a/tests/unit/metrics/paint_time.rs +++ b/tests/unit/metrics/paint_time.rs @@ -125,7 +125,7 @@ fn test_first_contentful_paint_setter() { image_rendering: ImageRendering::Auto, alpha_type: AlphaType::PremultipliedAlpha, color: ColorF::WHITE, - } + }, )); let display_list = DisplayList { list: vec![image], diff --git a/tests/unit/profile/time.rs b/tests/unit/profile/time.rs index 0cd41086065..6377256b937 100644 --- a/tests/unit/profile/time.rs +++ b/tests/unit/profile/time.rs @@ -22,8 +22,9 @@ fn time_profiler_smoke_test() { #[test] fn time_profiler_stats_test() { - let even_data = vec![1.234, 3.24567, 3.54578, 5.0, 5.324, 7.345, - 9.2345, 10.2342345, 13.2599, 15.0]; + let even_data = vec![ + 1.234, 3.24567, 3.54578, 5.0, 5.324, 7.345, 9.2345, 10.2342345, 13.2599, 15.0, + ]; let (even_mean, even_median, even_min, even_max) = time::Profiler::get_statistics(&even_data); assert_eq!(7.34230845, even_mean); @@ -31,8 +32,9 @@ fn time_profiler_stats_test() { assert_eq!(1.234, even_min); assert_eq!(15.0, even_max); - let odd_data = vec![1.234, 3.24567, 3.54578, 5.0, 5.324, 7.345, - 9.2345, 10.2342345, 13.2599]; + let odd_data = vec![ + 1.234, 3.24567, 3.54578, 5.0, 5.324, 7.345, 9.2345, 10.2342345, 13.2599, + ]; let (odd_mean, odd_median, odd_min, odd_max) = time::Profiler::get_statistics(&odd_data); assert_eq!(6.491453833333334, odd_mean); @@ -54,14 +56,16 @@ fn channel_profiler_test() { assert_eq!(val_profile_receiver, 43); let (sender, receiver) = ipc::channel().unwrap(); - chan.send(ProfilerMsg::Get((ProfilerCategory::IpcReceiver, None), sender.clone())); + chan.send(ProfilerMsg::Get( + (ProfilerCategory::IpcReceiver, None), + sender.clone(), + )); match receiver.recv().unwrap() { // asserts that the time spent in the sleeping thread is more than 1500 milliseconds ProfilerData::Record(time_data) => assert!(time_data[0] > 1.5e3), ProfilerData::NoRecords => assert!(false), }; - } #[test] @@ -77,14 +81,16 @@ fn bytes_channel_profiler_test() { assert_eq!(val_profile_receiver, [1, 2, 3]); let (sender, receiver) = ipc::channel().unwrap(); - chan.send(ProfilerMsg::Get((ProfilerCategory::IpcBytesReceiver, None), sender.clone())); + chan.send(ProfilerMsg::Get( + (ProfilerCategory::IpcBytesReceiver, None), + sender.clone(), + )); match receiver.recv().unwrap() { // asserts that the time spent in the sleeping thread is more than 1500 milliseconds ProfilerData::Record(time_data) => assert!(time_data[0] > 1.5e3), ProfilerData::NoRecords => assert!(false), }; - } #[cfg(debug_assertions)] diff --git a/tests/unit/script/headers.rs b/tests/unit/script/headers.rs index e990b706cdd..a08b82b5dfa 100644 --- a/tests/unit/script/headers.rs +++ b/tests/unit/script/headers.rs @@ -34,7 +34,8 @@ fn test_normalize_non_empty_no_whitespace_bytestring() { #[test] fn test_normalize_non_empty_leading_whitespace_bytestring() { // Non-empty, leading whitespace, no trailing whitespace ByteString test - let leading_whitespace_bytestring = ByteString::new(vec![b'\t', b'\n', b' ', b'\r', b'S', b'!']); + let leading_whitespace_bytestring = + ByteString::new(vec![b'\t', b'\n', b' ', b'\r', b'S', b'!']); let actual = normalize_value(leading_whitespace_bytestring); let expected = ByteString::new(vec![b'S', b'!']); assert_eq!(actual, expected); @@ -43,7 +44,8 @@ fn test_normalize_non_empty_leading_whitespace_bytestring() { #[test] fn test_normalize_non_empty_no_leading_whitespace_trailing_whitespace_bytestring() { // Non-empty, no leading whitespace, but with trailing whitespace ByteString test - let trailing_whitespace_bytestring = ByteString::new(vec![b'S', b'!', b'\t', b'\n', b' ', b'\r']); + let trailing_whitespace_bytestring = + ByteString::new(vec![b'S', b'!', b'\t', b'\n', b' ', b'\r']); let actual = normalize_value(trailing_whitespace_bytestring); let expected = ByteString::new(vec![b'S', b'!']); assert_eq!(actual, expected); @@ -52,8 +54,9 @@ fn test_normalize_non_empty_no_leading_whitespace_trailing_whitespace_bytestring #[test] fn test_normalize_non_empty_leading_and_trailing_whitespace_bytestring() { // Non-empty, leading whitespace, and trailing whitespace ByteString test - let whitespace_sandwich_bytestring = - ByteString::new(vec![b'\t', b'\n', b' ', b'\r', b'S', b'!', b'\t', b'\n', b' ', b'\r']); + let whitespace_sandwich_bytestring = ByteString::new(vec![ + b'\t', b'\n', b' ', b'\r', b'S', b'!', b'\t', b'\n', b' ', b'\r', + ]); let actual = normalize_value(whitespace_sandwich_bytestring); let expected = ByteString::new(vec![b'S', b'!']); assert_eq!(actual, expected); @@ -63,10 +66,9 @@ fn test_normalize_non_empty_leading_and_trailing_whitespace_bytestring() { fn test_normalize_non_empty_leading_trailing_and_internal_whitespace_bytestring() { // Non-empty, leading whitespace, trailing whitespace, // and internal whitespace ByteString test - let whitespace_bigmac_bytestring = - ByteString::new(vec![b'\t', b'\n', b' ', b'\r', b'S', - b'\t', b'\n', b' ', b'\r', b'!', - b'\t', b'\n', b' ', b'\r']); + let whitespace_bigmac_bytestring = ByteString::new(vec![ + b'\t', b'\n', b' ', b'\r', b'S', b'\t', b'\n', b' ', b'\r', b'!', b'\t', b'\n', b' ', b'\r', + ]); let actual = normalize_value(whitespace_bigmac_bytestring); let expected = ByteString::new(vec![b'S', b'\t', b'\n', b' ', b'\r', b'!']); assert_eq!(actual, expected); diff --git a/tests/unit/script/htmlareaelement.rs b/tests/unit/script/htmlareaelement.rs index c2a98fd8681..be4cb12c0cc 100644 --- a/tests/unit/script/htmlareaelement.rs +++ b/tests/unit/script/htmlareaelement.rs @@ -28,14 +28,26 @@ fn delimiter_input() { // Area::Circle tests #[test] fn valid_circle_inputs() { - assert_eq!(Area::parse("10.2, 3.4, 5.2", Shape::Circle), - Some(Area::Circle { left: 10.2, top: 3.4, radius: 5.2 })); + assert_eq!( + Area::parse("10.2, 3.4, 5.2", Shape::Circle), + Some(Area::Circle { + left: 10.2, + top: 3.4, + radius: 5.2 + }) + ); } #[test] fn valid_negative_circle_inputs() { - assert_eq!(Area::parse("-10.2, -3.4, 5.2", Shape::Circle), - Some(Area::Circle { left: -10.2, top: -3.4, radius: 5.2 })); + assert_eq!( + Area::parse("-10.2, -3.4, 5.2", Shape::Circle), + Some(Area::Circle { + left: -10.2, + top: -3.4, + radius: 5.2 + }) + ); } #[test] @@ -46,77 +58,133 @@ fn invalid_negative_circle_radius() { // Area::Rectangle tests #[test] fn rectangle_valid_input() { - assert_eq!(Area::parse("5.2, 1.1, 10.2, 3.4", Shape::Rectangle), - Some(Area::Rectangle { top_left: (5.2, 1.1), - bottom_right: (10.2, 3.4) })); + assert_eq!( + Area::parse("5.2, 1.1, 10.2, 3.4", Shape::Rectangle), + Some(Area::Rectangle { + top_left: (5.2, 1.1), + bottom_right: (10.2, 3.4) + }) + ); } #[test] fn rectangle_valid_negative_input() { - assert_eq!(Area::parse("-10.2, -3.4, -5.2, -1.1", Shape::Rectangle), - Some(Area::Rectangle { top_left: (-10.2, -3.4), - bottom_right: (-5.2, -1.1) })); + assert_eq!( + Area::parse("-10.2, -3.4, -5.2, -1.1", Shape::Rectangle), + Some(Area::Rectangle { + top_left: (-10.2, -3.4), + bottom_right: (-5.2, -1.1) + }) + ); } #[test] fn rectangle_invalid_input() { - assert_eq!(Area::parse("5.2, 4.3, 10.2, 1.1.2", Shape::Rectangle), - Some(Area::Rectangle { top_left: (5.2, 0.0), - bottom_right: (10.2, 4.3) })); + assert_eq!( + Area::parse("5.2, 4.3, 10.2, 1.1.2", Shape::Rectangle), + Some(Area::Rectangle { + top_left: (5.2, 0.0), + bottom_right: (10.2, 4.3) + }) + ); } #[test] fn rectangle_unordered_input() { - assert_eq!(Area::parse("5.2, 1.1, 10.2, 4.3", Shape::Rectangle), - Some(Area::Rectangle { top_left: (5.2, 1.1), - bottom_right: (10.2, 4.3) })); + assert_eq!( + Area::parse("5.2, 1.1, 10.2, 4.3", Shape::Rectangle), + Some(Area::Rectangle { + top_left: (5.2, 1.1), + bottom_right: (10.2, 4.3) + }) + ); } // Area::Polygon tests #[test] fn polygon_six_points_valid_input() { - assert_eq!(Area::parse("1.1, 1.1, 6.1, 1.1, 3.1, 3.1", Shape::Polygon), - Some(Area::Polygon { points: vec![1.1, 1.1, 6.1, 1.1, 3.1, 3.1] })); + assert_eq!( + Area::parse("1.1, 1.1, 6.1, 1.1, 3.1, 3.1", Shape::Polygon), + Some(Area::Polygon { + points: vec![1.1, 1.1, 6.1, 1.1, 3.1, 3.1] + }) + ); } #[test] fn polygon_six_points_valid_negative_input() { - assert_eq!(Area::parse("1.1, -1.1, 6.1, -1.1, 3.1, -3.1", Shape::Polygon), - Some(Area::Polygon { points: vec![1.1, -1.1, 6.1, -1.1, 3.1, -3.1] })); + assert_eq!( + Area::parse("1.1, -1.1, 6.1, -1.1, 3.1, -3.1", Shape::Polygon), + Some(Area::Polygon { + points: vec![1.1, -1.1, 6.1, -1.1, 3.1, -3.1] + }) + ); } #[test] fn polygon_six_points_invalid_input() { - assert_eq!(Area::parse(";1.1, 1.1,'; 6.1,(*^() 1.1, 3.1, 3.1, 100.1 %$,;", Shape::Polygon), - Some(Area::Polygon { points: vec![1.1, 1.1, 6.1, 1.1, 3.1, 3.1] })); + assert_eq!( + Area::parse( + ";1.1, 1.1,'; 6.1,(*^() 1.1, 3.1, 3.1, 100.1 %$,;", + Shape::Polygon + ), + Some(Area::Polygon { + points: vec![1.1, 1.1, 6.1, 1.1, 3.1, 3.1] + }) + ); } #[test] fn polygon_eight_points_invalid_input() { - assert_eq!(Area::parse("1.1, -1.1, 6.1, -1.1, 1.1, -3.1, 6.1, -3.1.2, 12.1", Shape::Polygon), - Some(Area::Polygon { points: vec![1.1, -1.1, 6.1, -1.1, 1.1, -3.1, 6.1, 0.0] })); + assert_eq!( + Area::parse( + "1.1, -1.1, 6.1, -1.1, 1.1, -3.1, 6.1, -3.1.2, 12.1", + Shape::Polygon + ), + Some(Area::Polygon { + points: vec![1.1, -1.1, 6.1, -1.1, 1.1, -3.1, 6.1, 0.0] + }) + ); } #[test] fn test_hit_test_circle() { - let circ1 = Area::Circle { left: 20.0, top: 10.0, radius: 5.0 }; - assert!(!circ1.hit_test(&Point2D::new(10.0, 20.0))); - let circ2 = Area::Circle { left: 10.0, top: 10.0, radius: 5.0 }; - assert!(circ2.hit_test(&Point2D::new(10.0, 12.0))); + let circ1 = Area::Circle { + left: 20.0, + top: 10.0, + radius: 5.0, + }; + assert!(!circ1.hit_test(&Point2D::new(10.0, 20.0))); + let circ2 = Area::Circle { + left: 10.0, + top: 10.0, + radius: 5.0, + }; + assert!(circ2.hit_test(&Point2D::new(10.0, 12.0))); } #[test] fn test_hit_test_rectangle() { - let rect1 = Area::Rectangle { top_left: (1.0, 7.0), bottom_right: (15.0, 10.0) }; - assert!(!rect1.hit_test(&Point2D::new(10.0, 5.0))); - let rect2 = Area::Rectangle { top_left: (8.0, 10.0), bottom_right: (20.0, 12.0) }; - assert!(rect2.hit_test(&Point2D::new(10.0, 12.0))); + let rect1 = Area::Rectangle { + top_left: (1.0, 7.0), + bottom_right: (15.0, 10.0), + }; + assert!(!rect1.hit_test(&Point2D::new(10.0, 5.0))); + let rect2 = Area::Rectangle { + top_left: (8.0, 10.0), + bottom_right: (20.0, 12.0), + }; + assert!(rect2.hit_test(&Point2D::new(10.0, 12.0))); } #[test] fn test_hit_test_polygon() { - let poly1 = Area::Polygon { points: vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0] }; - assert!(!poly1.hit_test(&Point2D::new(10.0, 5.0))); - let poly2 = Area::Polygon { points: vec![7.0, 7.5, 8.2, 9.0, 11.0, 12.0] }; - assert!(!poly2.hit_test(&Point2D::new(10.0, 5.0))); + let poly1 = Area::Polygon { + points: vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], + }; + assert!(!poly1.hit_test(&Point2D::new(10.0, 5.0))); + let poly2 = Area::Polygon { + points: vec![7.0, 7.5, 8.2, 9.0, 11.0, 12.0], + }; + assert!(!poly2.hit_test(&Point2D::new(10.0, 5.0))); } diff --git a/tests/unit/script/htmlimageelement.rs b/tests/unit/script/htmlimageelement.rs index 796e63c2e2b..6c38bfa83e2 100644 --- a/tests/unit/script/htmlimageelement.rs +++ b/tests/unit/script/htmlimageelement.rs @@ -12,48 +12,104 @@ fn no_value() { #[test] fn width_one_value() { - let first_descriptor = Descriptor { wid: Some(320), den: None }; - let first_imagesource = ImageSource { url: "small-image.jpg".to_string(), descriptor: first_descriptor }; + let first_descriptor = Descriptor { + wid: Some(320), + den: None, + }; + let first_imagesource = ImageSource { + url: "small-image.jpg".to_string(), + descriptor: first_descriptor, + }; let sources = &[first_imagesource]; assert_eq!(parse_a_srcset_attribute("small-image.jpg, 320w"), sources); } #[test] fn width_two_value() { - let first_descriptor = Descriptor { wid: Some(320), den: None }; - let first_imagesource = ImageSource { url: "small-image.jpg".to_string(), descriptor: first_descriptor }; - let second_descriptor = Descriptor { wid: Some(480), den: None }; - let second_imagesource = ImageSource { url: "medium-image.jpg".to_string(), descriptor: second_descriptor }; + let first_descriptor = Descriptor { + wid: Some(320), + den: None, + }; + let first_imagesource = ImageSource { + url: "small-image.jpg".to_string(), + descriptor: first_descriptor, + }; + let second_descriptor = Descriptor { + wid: Some(480), + den: None, + }; + let second_imagesource = ImageSource { + url: "medium-image.jpg".to_string(), + descriptor: second_descriptor, + }; let sources = &[first_imagesource, second_imagesource]; - assert_eq!(parse_a_srcset_attribute("small-image.jpg 320w, medium-image.jpg 480w"), sources); + assert_eq!( + parse_a_srcset_attribute("small-image.jpg 320w, medium-image.jpg 480w"), + sources + ); } #[test] fn width_three_value() { - let first_descriptor = Descriptor { wid: Some(320), den: None }; - let first_imagesource = ImageSource { url: "smallImage.jpg".to_string(), descriptor: first_descriptor }; - let second_descriptor = Descriptor { wid: Some(480), den: None }; - let second_imagesource = ImageSource { url: "mediumImage.jpg".to_string(), descriptor: second_descriptor }; - let third_descriptor = Descriptor { wid: Some(800), den: None }; - let third_imagesource = ImageSource { url: "largeImage.jpg".to_string(), descriptor: third_descriptor }; + let first_descriptor = Descriptor { + wid: Some(320), + den: None, + }; + let first_imagesource = ImageSource { + url: "smallImage.jpg".to_string(), + descriptor: first_descriptor, + }; + let second_descriptor = Descriptor { + wid: Some(480), + den: None, + }; + let second_imagesource = ImageSource { + url: "mediumImage.jpg".to_string(), + descriptor: second_descriptor, + }; + let third_descriptor = Descriptor { + wid: Some(800), + den: None, + }; + let third_imagesource = ImageSource { + url: "largeImage.jpg".to_string(), + descriptor: third_descriptor, + }; let sources = &[first_imagesource, second_imagesource, third_imagesource]; - assert_eq!(parse_a_srcset_attribute("smallImage.jpg 320w, + assert_eq!( + parse_a_srcset_attribute( + "smallImage.jpg 320w, mediumImage.jpg 480w, - largeImage.jpg 800w"), sources); + largeImage.jpg 800w" + ), + sources + ); } #[test] fn density_value() { - let first_descriptor = Descriptor { wid: None, den: Some(1.0) }; - let first_imagesource = ImageSource { url: "small-image.jpg".to_string(), descriptor: first_descriptor }; + let first_descriptor = Descriptor { + wid: None, + den: Some(1.0), + }; + let first_imagesource = ImageSource { + url: "small-image.jpg".to_string(), + descriptor: first_descriptor, + }; let sources = &[first_imagesource]; assert_eq!(parse_a_srcset_attribute("small-image.jpg 1x"), sources); } #[test] fn without_descriptor() { - let first_descriptor = Descriptor { wid: None, den: None }; - let first_imagesource = ImageSource { url: "small-image.jpg".to_string(), descriptor: first_descriptor }; + let first_descriptor = Descriptor { + wid: None, + den: None, + }; + let first_imagesource = ImageSource { + url: "small-image.jpg".to_string(), + descriptor: first_descriptor, + }; let sources = &[first_imagesource]; assert_eq!(parse_a_srcset_attribute("small-image.jpg"), sources); } @@ -62,23 +118,47 @@ fn without_descriptor() { #[test] fn two_descriptor() { let empty_vec = Vec::new(); - assert_eq!(parse_a_srcset_attribute("small-image.jpg 320w 1.1x"), empty_vec); + assert_eq!( + parse_a_srcset_attribute("small-image.jpg 320w 1.1x"), + empty_vec + ); } #[test] fn decimal_descriptor() { - let first_descriptor = Descriptor { wid: None, den: Some(2.2) }; - let first_imagesource = ImageSource { url: "small-image.jpg".to_string(), descriptor: first_descriptor }; + let first_descriptor = Descriptor { + wid: None, + den: Some(2.2), + }; + let first_imagesource = ImageSource { + url: "small-image.jpg".to_string(), + descriptor: first_descriptor, + }; let sources = &[first_imagesource]; assert_eq!(parse_a_srcset_attribute("small-image.jpg 2.2x"), sources); } #[test] fn different_descriptor() { - let first_descriptor = Descriptor { wid: Some(320), den: None }; - let first_imagesource = ImageSource { url: "small-image.jpg".to_string(), descriptor: first_descriptor }; - let second_descriptor = Descriptor { wid: None, den: Some(2.2) }; - let second_imagesource = ImageSource { url: "medium-image.jpg".to_string(), descriptor: second_descriptor }; + let first_descriptor = Descriptor { + wid: Some(320), + den: None, + }; + let first_imagesource = ImageSource { + url: "small-image.jpg".to_string(), + descriptor: first_descriptor, + }; + let second_descriptor = Descriptor { + wid: None, + den: Some(2.2), + }; + let second_imagesource = ImageSource { + url: "medium-image.jpg".to_string(), + descriptor: second_descriptor, + }; let sources = &[first_imagesource, second_imagesource]; - assert_eq!(parse_a_srcset_attribute("small-image.jpg 320w, medium-image.jpg 2.2x"), sources); + assert_eq!( + parse_a_srcset_attribute("small-image.jpg 320w, medium-image.jpg 2.2x"), + sources + ); } diff --git a/tests/unit/script/lib.rs b/tests/unit/script/lib.rs index 157531474d4..0251144dd30 100644 --- a/tests/unit/script/lib.rs +++ b/tests/unit/script/lib.rs @@ -2,19 +2,29 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#[cfg(test)] extern crate euclid; -#[cfg(test)] extern crate keyboard_types; -#[cfg(test)] extern crate script; -#[cfg(test)] extern crate servo_url; - -#[cfg(test)] mod origin; -#[cfg(all(test, target_pointer_width = "64"))] mod size_of; -#[cfg(test)] mod textinput; -#[cfg(test)] mod headers; -#[cfg(test)] mod htmlareaelement; -#[cfg(test)] mod htmlimageelement; -#[cfg(test)] mod timeranges; +#[cfg(test)] +extern crate euclid; +#[cfg(test)] +extern crate keyboard_types; +#[cfg(test)] +extern crate script; +#[cfg(test)] +extern crate servo_url; +#[cfg(test)] +mod headers; +#[cfg(test)] +mod htmlareaelement; +#[cfg(test)] +mod htmlimageelement; +#[cfg(test)] +mod origin; +#[cfg(all(test, target_pointer_width = "64"))] +mod size_of; +#[cfg(test)] +mod textinput; +#[cfg(test)] +mod timeranges; /** ```compile_fail,E0277 diff --git a/tests/unit/script/origin.rs b/tests/unit/script/origin.rs index 526b12bf0f9..dc19a984774 100644 --- a/tests/unit/script/origin.rs +++ b/tests/unit/script/origin.rs @@ -6,29 +6,57 @@ use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl}; #[test] fn same_origin() { - let a = MutableOrigin::new(ServoUrl::parse("http://example.com/a.html").unwrap().origin()); - let b = MutableOrigin::new(ServoUrl::parse("http://example.com/b.html").unwrap().origin()); + let a = MutableOrigin::new( + ServoUrl::parse("http://example.com/a.html") + .unwrap() + .origin(), + ); + let b = MutableOrigin::new( + ServoUrl::parse("http://example.com/b.html") + .unwrap() + .origin(), + ); assert!(a.same_origin(&b)); assert_eq!(a.is_tuple(), true); } #[test] fn identical_origin() { - let a = MutableOrigin::new(ServoUrl::parse("http://example.com/a.html").unwrap().origin()); + let a = MutableOrigin::new( + ServoUrl::parse("http://example.com/a.html") + .unwrap() + .origin(), + ); assert!(a.same_origin(&a)); } #[test] fn cross_origin() { - let a = MutableOrigin::new(ServoUrl::parse("http://example.com/a.html").unwrap().origin()); - let b = MutableOrigin::new(ServoUrl::parse("http://example.org/b.html").unwrap().origin()); + let a = MutableOrigin::new( + ServoUrl::parse("http://example.com/a.html") + .unwrap() + .origin(), + ); + let b = MutableOrigin::new( + ServoUrl::parse("http://example.org/b.html") + .unwrap() + .origin(), + ); assert!(!a.same_origin(&b)); } #[test] fn clone_same_origin() { - let a = MutableOrigin::new(ServoUrl::parse("http://example.com/a.html").unwrap().origin()); - let b = MutableOrigin::new(ServoUrl::parse("http://example.com/b.html").unwrap().origin()); + let a = MutableOrigin::new( + ServoUrl::parse("http://example.com/a.html") + .unwrap() + .origin(), + ); + let b = MutableOrigin::new( + ServoUrl::parse("http://example.com/b.html") + .unwrap() + .origin(), + ); let c = b.clone(); assert!(a.same_origin(&c)); assert!(b.same_origin(&b)); @@ -38,8 +66,16 @@ fn clone_same_origin() { #[test] fn clone_cross_origin() { - let a = MutableOrigin::new(ServoUrl::parse("http://example.com/a.html").unwrap().origin()); - let b = MutableOrigin::new(ServoUrl::parse("http://example.org/b.html").unwrap().origin()); + let a = MutableOrigin::new( + ServoUrl::parse("http://example.com/a.html") + .unwrap() + .origin(), + ); + let b = MutableOrigin::new( + ServoUrl::parse("http://example.org/b.html") + .unwrap() + .origin(), + ); let c = b.clone(); assert!(!a.same_origin(&c)); assert!(b.same_origin(&c)); diff --git a/tests/unit/script/textinput.rs b/tests/unit/script/textinput.rs index 0f4467d81ca..6488542269b 100644 --- a/tests/unit/script/textinput.rs +++ b/tests/unit/script/textinput.rs @@ -13,18 +13,25 @@ use script::test::DOMString; use script::textinput::{TextInput, TextPoint, Selection, Lines, Direction, SelectionDirection}; fn text_input(lines: Lines, s: &str) -> TextInput<DummyClipboardContext> { - TextInput::new(lines, - DOMString::from(s), - DummyClipboardContext::new(""), - None, - None, - SelectionDirection::None) + TextInput::new( + lines, + DOMString::from(s), + DummyClipboardContext::new(""), + None, + None, + SelectionDirection::None, + ) } #[test] fn test_set_content_ignores_max_length() { let mut textinput = TextInput::new( - Lines::Single, DOMString::from(""), DummyClipboardContext::new(""), Some(1), None, SelectionDirection::None + Lines::Single, + DOMString::from(""), + DummyClipboardContext::new(""), + Some(1), + None, + SelectionDirection::None, ); textinput.set_content(DOMString::from("mozilla rocks")); @@ -64,7 +71,7 @@ fn test_textinput_when_inserting_multiple_lines_still_respects_max_length() { DummyClipboardContext::new(""), Some(17), None, - SelectionDirection::None + SelectionDirection::None, ); textinput.adjust_vertical(1, Selection::NotSelected); @@ -74,7 +81,8 @@ fn test_textinput_when_inserting_multiple_lines_still_respects_max_length() { } #[test] -fn test_textinput_when_content_is_already_longer_than_max_length_and_theres_no_selection_dont_insert_anything() { +fn test_textinput_when_content_is_already_longer_than_max_length_and_theres_no_selection_dont_insert_anything( +) { let mut textinput = TextInput::new( Lines::Single, DOMString::from("abc"), @@ -90,7 +98,8 @@ fn test_textinput_when_content_is_already_longer_than_max_length_and_theres_no_s } #[test] -fn test_multi_line_textinput_with_maxlength_doesnt_allow_appending_characters_when_input_spans_lines() { +fn test_multi_line_textinput_with_maxlength_doesnt_allow_appending_characters_when_input_spans_lines( +) { let mut textinput = TextInput::new( Lines::Multiple, DOMString::from("abc\nd"), @@ -106,7 +115,8 @@ fn test_multi_line_textinput_with_maxlength_doesnt_allow_appending_characters_wh } #[test] -fn test_single_line_textinput_with_max_length_doesnt_allow_appending_characters_when_replacing_a_selection() { +fn test_single_line_textinput_with_max_length_doesnt_allow_appending_characters_when_replacing_a_selection( +) { let mut textinput = TextInput::new( Lines::Single, DOMString::from("abcde"), @@ -183,7 +193,8 @@ fn test_single_line_textinput_with_max_length_inside_char() { } #[test] -fn test_single_line_textinput_with_max_length_doesnt_allow_appending_characters_after_max_length_is_reached() { +fn test_single_line_textinput_with_max_length_doesnt_allow_appending_characters_after_max_length_is_reached( +) { let mut textinput = TextInput::new( Lines::Single, DOMString::from("a"), @@ -430,23 +441,39 @@ fn test_navigation_keyboard_shortcuts() { textinput.handle_keydown_aux(Key::ArrowLeft, Modifiers::META, true); assert_eq!(textinput.edit_point().index, 0); // Test that CTRL + ALT + E moves to the end of the current line also. - textinput.handle_keydown_aux(Key::Character("e".to_owned()), Modifiers::CONTROL | Modifiers::ALT, true); + textinput.handle_keydown_aux( + Key::Character("e".to_owned()), + Modifiers::CONTROL | Modifiers::ALT, + true, + ); assert_eq!(textinput.edit_point().index, 11); // Test that CTRL + ALT + A moves to the beginning of the current line also. - textinput.handle_keydown_aux(Key::Character("a".to_owned()), Modifiers::CONTROL | Modifiers::ALT, true); + textinput.handle_keydown_aux( + Key::Character("a".to_owned()), + Modifiers::CONTROL | Modifiers::ALT, + true, + ); assert_eq!(textinput.edit_point().index, 0); // Test that ALT + Right moves to the end of the word. textinput.handle_keydown_aux(Key::ArrowRight, Modifiers::ALT, true); assert_eq!(textinput.edit_point().index, 5); // Test that CTRL + ALT + F moves to the end of the word also. - textinput.handle_keydown_aux(Key::Character("f".to_owned()), Modifiers::CONTROL | Modifiers::ALT, true); + textinput.handle_keydown_aux( + Key::Character("f".to_owned()), + Modifiers::CONTROL | Modifiers::ALT, + true, + ); assert_eq!(textinput.edit_point().index, 11); // Test that ALT + Left moves to the end of the word. textinput.handle_keydown_aux(Key::ArrowLeft, Modifiers::ALT, true); assert_eq!(textinput.edit_point().index, 6); // Test that CTRL + ALT + B moves to the end of the word also. - textinput.handle_keydown_aux(Key::Character("b".to_owned()), Modifiers::CONTROL | Modifiers::ALT, true); + textinput.handle_keydown_aux( + Key::Character("b".to_owned()), + Modifiers::CONTROL | Modifiers::ALT, + true, + ); assert_eq!(textinput.edit_point().index, 0); } @@ -510,12 +537,14 @@ fn test_clipboard_paste() { #[cfg(not(target_os = "macos"))] const MODIFIERS: Modifiers = Modifiers::CONTROL; - let mut textinput = TextInput::new(Lines::Single, - DOMString::from("defg"), - DummyClipboardContext::new("abc"), - None, - None, - SelectionDirection::None); + let mut textinput = TextInput::new( + Lines::Single, + DOMString::from("defg"), + DummyClipboardContext::new("abc"), + None, + None, + SelectionDirection::None, + ); assert_eq!(textinput.get_content(), "defg"); assert_eq!(textinput.edit_point().index, 0); textinput.handle_keydown_aux(Key::Character("v".to_owned()), MODIFIERS, false); @@ -547,7 +576,6 @@ fn test_textinput_cursor_position_correct_after_clearing_selection() { textinput.adjust_horizontal_by_one(Direction::Backward, Selection::NotSelected); assert_eq!(textinput.edit_point().index, 0); - let mut textinput = text_input(Lines::Multiple, "abc\nde\nf"); // Multiline - Forward @@ -576,7 +604,6 @@ fn test_textinput_cursor_position_correct_after_clearing_selection() { assert_eq!(textinput.edit_point().line, 0); } - #[test] fn test_textinput_set_selection_with_direction() { let mut textinput = text_input(Lines::Single, "abcdef"); @@ -592,7 +619,10 @@ fn test_textinput_set_selection_with_direction() { textinput.set_selection_range(2, 6, SelectionDirection::Backward); assert_eq!(textinput.edit_point().line, 0); assert_eq!(textinput.edit_point().index, 2); - assert_eq!(textinput.selection_direction(), SelectionDirection::Backward); + assert_eq!( + textinput.selection_direction(), + SelectionDirection::Backward + ); assert!(textinput.selection_origin().is_some()); assert_eq!(textinput.selection_origin().unwrap().line, 0); @@ -617,7 +647,6 @@ fn test_textinput_set_selection_with_direction() { assert!(textinput.selection_origin().is_some()); assert_eq!(textinput.selection_origin().unwrap().line, 0); assert_eq!(textinput.selection_origin().unwrap().index, 0); - } #[test] @@ -634,19 +663,28 @@ fn test_textinput_unicode_handling() { fn test_selection_bounds() { let mut textinput = text_input(Lines::Single, "abcdef"); - assert_eq!(TextPoint { line: 0, index: 0 }, textinput.selection_origin_or_edit_point()); + assert_eq!( + TextPoint { line: 0, index: 0 }, + textinput.selection_origin_or_edit_point() + ); assert_eq!(TextPoint { line: 0, index: 0 }, textinput.selection_start()); assert_eq!(TextPoint { line: 0, index: 0 }, textinput.selection_end()); textinput.set_selection_range(2, 5, SelectionDirection::Forward); - assert_eq!(TextPoint { line: 0, index: 2 }, textinput.selection_origin_or_edit_point()); + assert_eq!( + TextPoint { line: 0, index: 2 }, + textinput.selection_origin_or_edit_point() + ); assert_eq!(TextPoint { line: 0, index: 2 }, textinput.selection_start()); assert_eq!(TextPoint { line: 0, index: 5 }, textinput.selection_end()); assert_eq!(2, textinput.selection_start_offset()); assert_eq!(5, textinput.selection_end_offset()); textinput.set_selection_range(3, 6, SelectionDirection::Backward); - assert_eq!(TextPoint { line: 0, index: 6 }, textinput.selection_origin_or_edit_point()); + assert_eq!( + TextPoint { line: 0, index: 6 }, + textinput.selection_origin_or_edit_point() + ); assert_eq!(TextPoint { line: 0, index: 3 }, textinput.selection_start()); assert_eq!(TextPoint { line: 0, index: 6 }, textinput.selection_end()); assert_eq!(3, textinput.selection_start_offset()); @@ -654,8 +692,10 @@ fn test_selection_bounds() { textinput = text_input(Lines::Multiple, "\n\n"); textinput.set_selection_range(0, 1, SelectionDirection::Forward); - assert_eq!(TextPoint { line: 0, index: 0 }, textinput.selection_origin_or_edit_point()); + assert_eq!( + TextPoint { line: 0, index: 0 }, + textinput.selection_origin_or_edit_point() + ); assert_eq!(TextPoint { line: 0, index: 0 }, textinput.selection_start()); assert_eq!(TextPoint { line: 1, index: 0 }, textinput.selection_end()); - } diff --git a/tests/unit/script_plugins/lib.rs b/tests/unit/script_plugins/lib.rs index 35a1c0dff11..f27a16f2e32 100644 --- a/tests/unit/script_plugins/lib.rs +++ b/tests/unit/script_plugins/lib.rs @@ -7,13 +7,13 @@ pub mod unrooted_must_root { ``` #![feature(plugin)] #![plugin(script_plugins)] - + #[must_root] struct Foo(i32); #[must_root] struct Bar(Foo); - + fn foo1(_: &Foo) {} fn foo2(_: &()) -> &Foo { unimplemented!() } - + fn main() {} ``` */ @@ -23,10 +23,10 @@ pub mod unrooted_must_root { ```compile_fail #![feature(plugin)] #![plugin(script_plugins)] - + #[must_root] struct Foo(i32); struct Bar(Foo); - + fn main() {} ``` */ @@ -36,11 +36,11 @@ pub mod unrooted_must_root { ```compile_fail #![feature(plugin)] #![plugin(script_plugins)] - + #[must_root] struct Foo(i32); - + fn foo1(_: Foo) {} - + fn main() {} ``` */ @@ -50,11 +50,11 @@ pub mod unrooted_must_root { ```compile_fail #![feature(plugin)] #![plugin(script_plugins)] - + #[must_root] struct Foo(i32); - + fn foo2() -> Foo { unimplemented!() } - + fn main() {} ``` */ diff --git a/tests/unit/style/animated_properties.rs b/tests/unit/style/animated_properties.rs index a884321369f..5eae2be7273 100644 --- a/tests/unit/style/animated_properties.rs +++ b/tests/unit/style/animated_properties.rs @@ -11,53 +11,76 @@ fn interpolate_rgba(from: RGBA, to: RGBA, progress: f64) -> RGBA { let from = from.to_animated_value(); let to = to.to_animated_value(); RGBA::from_animated_value( - from.animate(&to, Procedure::Interpolate { progress }).unwrap(), + from.animate(&to, Procedure::Interpolate { progress }) + .unwrap(), ) } // Color #[test] fn test_rgba_color_interepolation_preserves_transparent() { - assert_eq!(interpolate_rgba(RGBA::transparent(), - RGBA::transparent(), 0.5), - RGBA::transparent()); + assert_eq!( + interpolate_rgba(RGBA::transparent(), RGBA::transparent(), 0.5), + RGBA::transparent() + ); } #[test] fn test_rgba_color_interepolation_alpha() { - assert_eq!(interpolate_rgba(RGBA::new(200, 0, 0, 100), - RGBA::new(0, 200, 0, 200), 0.5), - RGBA::new(67, 133, 0, 150)); + assert_eq!( + interpolate_rgba(RGBA::new(200, 0, 0, 100), RGBA::new(0, 200, 0, 200), 0.5), + RGBA::new(67, 133, 0, 150) + ); } #[test] fn test_rgba_color_interepolation_out_of_range_1() { // Some cubic-bezier functions produce values that are out of range [0, 1]. // Unclamped cases. - assert_eq!(interpolate_rgba(RGBA::from_floats(0.3, 0.0, 0.0, 0.4), - RGBA::from_floats(0.0, 1.0, 0.0, 0.6), -0.5), - RGBA::new(154, 0, 0, 77)); + assert_eq!( + interpolate_rgba( + RGBA::from_floats(0.3, 0.0, 0.0, 0.4), + RGBA::from_floats(0.0, 1.0, 0.0, 0.6), + -0.5 + ), + RGBA::new(154, 0, 0, 77) + ); } #[test] fn test_rgba_color_interepolation_out_of_range_2() { - assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.6), - RGBA::from_floats(0.0, 0.3, 0.0, 0.4), 1.5), - RGBA::new(0, 154, 0, 77)); + assert_eq!( + interpolate_rgba( + RGBA::from_floats(1.0, 0.0, 0.0, 0.6), + RGBA::from_floats(0.0, 0.3, 0.0, 0.4), + 1.5 + ), + RGBA::new(0, 154, 0, 77) + ); } #[test] fn test_rgba_color_interepolation_out_of_range_clamped_1() { - assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.8), - RGBA::from_floats(0.0, 1.0, 0.0, 0.2), -0.5), - RGBA::from_floats(1.0, 0.0, 0.0, 1.0)); + assert_eq!( + interpolate_rgba( + RGBA::from_floats(1.0, 0.0, 0.0, 0.8), + RGBA::from_floats(0.0, 1.0, 0.0, 0.2), + -0.5 + ), + RGBA::from_floats(1.0, 0.0, 0.0, 1.0) + ); } #[test] fn test_rgba_color_interepolation_out_of_range_clamped_2() { - assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.8), - RGBA::from_floats(0.0, 1.0, 0.0, 0.2), 1.5), - RGBA::from_floats(0.0, 0.0, 0.0, 0.0)); + assert_eq!( + interpolate_rgba( + RGBA::from_floats(1.0, 0.0, 0.0, 0.8), + RGBA::from_floats(0.0, 1.0, 0.0, 0.2), + 1.5 + ), + RGBA::from_floats(0.0, 0.0, 0.0, 0.0) + ); } // Transform @@ -65,16 +88,19 @@ fn test_rgba_color_interepolation_out_of_range_clamped_2() { fn test_transform_interpolation_on_translate() { use style::values::computed::{CalcLengthOrPercentage, Length, LengthOrPercentage}; - let from = Transform(vec![ - TransformOperation::Translate3D(LengthOrPercentage::Length(Length::new(0.)), - LengthOrPercentage::Length(Length::new(100.)), - Length::new(25.))]); - let to = Transform(vec![ - TransformOperation::Translate3D(LengthOrPercentage::Length(Length::new(100.)), - LengthOrPercentage::Length(Length::new(0.)), - Length::new(75.))]); + let from = Transform(vec![TransformOperation::Translate3D( + LengthOrPercentage::Length(Length::new(0.)), + LengthOrPercentage::Length(Length::new(100.)), + Length::new(25.), + )]); + let to = Transform(vec![TransformOperation::Translate3D( + LengthOrPercentage::Length(Length::new(100.)), + LengthOrPercentage::Length(Length::new(0.)), + Length::new(75.), + )]); assert_eq!( - from.animate(&to, Procedure::Interpolate { progress: 0.5 }).unwrap(), + from.animate(&to, Procedure::Interpolate { progress: 0.5 }) + .unwrap(), Transform(vec![TransformOperation::Translate3D( LengthOrPercentage::Length(Length::new(50.)), LengthOrPercentage::Length(Length::new(50.)), @@ -87,19 +113,25 @@ fn test_transform_interpolation_on_translate() { LengthOrPercentage::Percentage(Percentage(1.0)), Length::new(25.), )]); - let to = Transform(vec![ - TransformOperation::Translate3D(LengthOrPercentage::Length(Length::new(100.)), - LengthOrPercentage::Length(Length::new(50.)), - Length::new(75.))]); + let to = Transform(vec![TransformOperation::Translate3D( + LengthOrPercentage::Length(Length::new(100.)), + LengthOrPercentage::Length(Length::new(50.)), + Length::new(75.), + )]); assert_eq!( - from.animate(&to, Procedure::Interpolate { progress: 0.5 }).unwrap(), + from.animate(&to, Procedure::Interpolate { progress: 0.5 }) + .unwrap(), Transform(vec![TransformOperation::Translate3D( // calc(50px + 25%) - LengthOrPercentage::Calc(CalcLengthOrPercentage::new(Length::new(50.), - Some(Percentage(0.25)))), + LengthOrPercentage::Calc(CalcLengthOrPercentage::new( + Length::new(50.), + Some(Percentage(0.25)) + )), // calc(25px + 50%) - LengthOrPercentage::Calc(CalcLengthOrPercentage::new(Length::new(25.), - Some(Percentage(0.5)))), + LengthOrPercentage::Calc(CalcLengthOrPercentage::new( + Length::new(25.), + Some(Percentage(0.5)) + )), Length::new(50.), )]) ); @@ -110,7 +142,8 @@ fn test_transform_interpolation_on_scale() { let from = Transform(vec![TransformOperation::Scale3D(1.0, 2.0, 1.0)]); let to = Transform(vec![TransformOperation::Scale3D(2.0, 4.0, 2.0)]); assert_eq!( - from.animate(&to, Procedure::Interpolate { progress: 0.5 }).unwrap(), + from.animate(&to, Procedure::Interpolate { progress: 0.5 }) + .unwrap(), Transform(vec![TransformOperation::Scale3D(1.5, 3.0, 1.5)]) ); } @@ -119,15 +152,27 @@ fn test_transform_interpolation_on_scale() { fn test_transform_interpolation_on_rotate() { use style::values::computed::Angle; - let from = Transform(vec![TransformOperation::Rotate3D(0.0, 0.0, 1.0, - Angle::from_radians(0.0))]); - let to = Transform(vec![TransformOperation::Rotate3D(0.0, 0.0, 1.0, - Angle::from_radians(100.0))]); + let from = Transform(vec![TransformOperation::Rotate3D( + 0.0, + 0.0, + 1.0, + Angle::from_radians(0.0), + )]); + let to = Transform(vec![TransformOperation::Rotate3D( + 0.0, + 0.0, + 1.0, + Angle::from_radians(100.0), + )]); assert_eq!( - from.animate(&to, Procedure::Interpolate { progress: 0.5 }).unwrap(), - Transform(vec![ - TransformOperation::Rotate3D(0.0, 0.0, 1.0, Angle::from_radians(50.0)), - ]) + from.animate(&to, Procedure::Interpolate { progress: 0.5 }) + .unwrap(), + Transform(vec![TransformOperation::Rotate3D( + 0.0, + 0.0, + 1.0, + Angle::from_radians(50.0) + )]) ); } @@ -135,12 +180,17 @@ fn test_transform_interpolation_on_rotate() { fn test_transform_interpolation_on_skew() { use style::values::computed::Angle; - let from = Transform(vec![TransformOperation::Skew(Angle::from_radians(0.0), - Some(Angle::from_radians(100.0)))]); - let to = Transform(vec![TransformOperation::Skew(Angle::from_radians(100.0), - Some(Angle::from_radians(0.0)))]); + let from = Transform(vec![TransformOperation::Skew( + Angle::from_radians(0.0), + Some(Angle::from_radians(100.0)), + )]); + let to = Transform(vec![TransformOperation::Skew( + Angle::from_radians(100.0), + Some(Angle::from_radians(0.0)), + )]); assert_eq!( - from.animate(&to, Procedure::Interpolate { progress: 0.5 }).unwrap(), + from.animate(&to, Procedure::Interpolate { progress: 0.5 }) + .unwrap(), Transform(vec![TransformOperation::Skew( Angle::from_radians(50.0), Some(Angle::from_radians(50.0)), @@ -152,14 +202,20 @@ fn test_transform_interpolation_on_skew() { fn test_transform_interpolation_on_mismatched_lists() { use style::values::computed::{Angle, Length, LengthOrPercentage}; - let from = Transform(vec![TransformOperation::Rotate3D(0.0, 0.0, 1.0, - Angle::from_radians(100.0))]); - let to = Transform(vec![ - TransformOperation::Translate3D(LengthOrPercentage::Length(Length::new(100.)), - LengthOrPercentage::Length(Length::new(0.)), - Length::new(0.))]); + let from = Transform(vec![TransformOperation::Rotate3D( + 0.0, + 0.0, + 1.0, + Angle::from_radians(100.0), + )]); + let to = Transform(vec![TransformOperation::Translate3D( + LengthOrPercentage::Length(Length::new(100.)), + LengthOrPercentage::Length(Length::new(0.)), + Length::new(0.), + )]); assert_eq!( - from.animate(&to, Procedure::Interpolate { progress: 0.5 }).unwrap(), + from.animate(&to, Procedure::Interpolate { progress: 0.5 }) + .unwrap(), Transform(vec![TransformOperation::InterpolateMatrix { from_list: from.clone(), to_list: to.clone(), diff --git a/tests/unit/style/attr.rs b/tests/unit/style/attr.rs index 9fc56ff82bb..c0bcc87d28f 100644 --- a/tests/unit/style/attr.rs +++ b/tests/unit/style/attr.rs @@ -23,7 +23,7 @@ fn test_parse_double() { let value = String::from("432.5e2"); match AttrValue::from_double(value, 0.0) { AttrValue::Double(_, num) => assert_eq!(num, 43250f64), - _ => panic!("expected a double value") + _ => panic!("expected a double value"), } } @@ -32,7 +32,7 @@ fn test_parse_double_negative_prefix() { let value = String::from("-5.6"); match AttrValue::from_double(value, 0.0) { AttrValue::Double(_, num) => assert_eq!(num, -5.6f64), - _ => panic!("expected a double value") + _ => panic!("expected a double value"), } } @@ -41,7 +41,7 @@ fn test_parse_double_positive_prefix() { let value = String::from("+5.6"); match AttrValue::from_double(value, 0.0) { AttrValue::Double(_, num) => assert_eq!(num, 5.6f64), - _ => panic!("expected a double value") + _ => panic!("expected a double value"), } } @@ -50,7 +50,7 @@ fn test_from_limited_i32_should_be_default_when_less_than_0() { let value = String::from("-1"); match AttrValue::from_limited_i32(value, 0) { AttrValue::Int(_, 0) => (), - _ => panic!("expected an IndexSize error") + _ => panic!("expected an IndexSize error"), } } @@ -58,17 +58,15 @@ fn test_from_limited_i32_should_be_default_when_less_than_0() { fn test_from_limited_i32_should_parse_a_uint_when_value_is_0_or_greater() { match AttrValue::from_limited_i32(String::from("1"), 0) { AttrValue::Int(_, 1) => (), - _ => panic!("expected an successful parsing") + _ => panic!("expected an successful parsing"), } } #[test] fn test_from_limited_i32_should_keep_parsed_value_when_not_an_int() { match AttrValue::from_limited_i32(String::from("parsed-value"), 0) { - AttrValue::Int(p, 0) => { - assert_eq!(p, String::from("parsed-value")) - }, - _ => panic!("expected an successful parsing") + AttrValue::Int(p, 0) => assert_eq!(p, String::from("parsed-value")), + _ => panic!("expected an successful parsing"), } } @@ -82,7 +80,13 @@ pub fn test_parse_length() { check("0", LengthOrPercentageOrAuto::Length(Au::from_px(0))); check("0.000%", LengthOrPercentageOrAuto::Percentage(0.0)); check("+5.82%", LengthOrPercentageOrAuto::Percentage(0.0582)); - check("5.82", LengthOrPercentageOrAuto::Length(Au::from_f64_px(5.82))); + check( + "5.82", + LengthOrPercentageOrAuto::Length(Au::from_f64_px(5.82)), + ); check("invalid", LengthOrPercentageOrAuto::Auto); - check("12 followed by invalid", LengthOrPercentageOrAuto::Length(Au::from_px(12))); + check( + "12 followed by invalid", + LengthOrPercentageOrAuto::Length(Au::from_px(12)), + ); } diff --git a/tests/unit/style/custom_properties.rs b/tests/unit/style/custom_properties.rs index aeefe6e19b9..e9b4399b1b7 100644 --- a/tests/unit/style/custom_properties.rs +++ b/tests/unit/style/custom_properties.rs @@ -12,11 +12,17 @@ fn cascade( name_and_value: &[(&str, &str)], inherited: Option<&Arc<CustomPropertiesMap>>, ) -> Option<Arc<CustomPropertiesMap>> { - let values = name_and_value.iter().map(|&(name, value)| { - let mut input = ParserInput::new(value); - let mut parser = Parser::new(&mut input); - (Name::from(name), SpecifiedValue::parse(&mut parser).unwrap()) - }).collect::<Vec<_>>(); + let values = name_and_value + .iter() + .map(|&(name, value)| { + let mut input = ParserInput::new(value); + let mut parser = Parser::new(&mut input); + ( + Name::from(name), + SpecifiedValue::parse(&mut parser).unwrap(), + ) + }) + .collect::<Vec<_>>(); let env = CssEnvironment; let mut builder = CustomPropertiesBuilder::new(inherited, &env); @@ -31,14 +37,11 @@ fn cascade( #[bench] fn cascade_custom_simple(b: &mut Bencher) { b.iter(|| { - let parent = cascade(&[ - ("foo", "10px"), - ("bar", "100px"), - ], None); + let parent = cascade(&[("foo", "10px"), ("bar", "100px")], None); - test::black_box(cascade(&[ - ("baz", "calc(40em + 4px)"), - ("bazz", "calc(30em + 4px)"), - ], parent.as_ref())) + test::black_box(cascade( + &[("baz", "calc(40em + 4px)"), ("bazz", "calc(30em + 4px)")], + parent.as_ref(), + )) }) } diff --git a/tests/unit/style/lib.rs b/tests/unit/style/lib.rs index f9fe10dbaae..a48fc9826ce 100644 --- a/tests/unit/style/lib.rs +++ b/tests/unit/style/lib.rs @@ -8,7 +8,8 @@ extern crate app_units; extern crate cssparser; extern crate euclid; -#[macro_use] extern crate html5ever; +#[macro_use] +extern crate html5ever; extern crate parking_lot; extern crate rayon; extern crate selectors; @@ -17,8 +18,10 @@ extern crate servo_arc; extern crate servo_atoms; extern crate servo_config; extern crate servo_url; -#[macro_use] extern crate size_of_test; -#[macro_use] extern crate style; +#[macro_use] +extern crate size_of_test; +#[macro_use] +extern crate style; extern crate style_traits; extern crate test; diff --git a/tests/unit/style/parsing/animation.rs b/tests/unit/style/parsing/animation.rs index 4984e2035a9..c138a51a1c4 100644 --- a/tests/unit/style/parsing/animation.rs +++ b/tests/unit/style/parsing/animation.rs @@ -14,14 +14,22 @@ use style_traits::ToCss; fn test_animation_name() { use self::animation_name::single_value::SpecifiedValue as SingleValue; let other_name = Atom::from("other-name"); - assert_eq!(parse_longhand!(animation_name, "none"), - animation_name::SpecifiedValue(vec![SingleValue(None)])); - assert_eq!(parse_longhand!(animation_name, "other-name, none, 'other-name', \"other-name\""), - animation_name::SpecifiedValue( - vec![SingleValue(Some(KeyframesName::Ident(CustomIdent(other_name.clone())))), - SingleValue(None), - SingleValue(Some(KeyframesName::QuotedString(other_name.clone()))), - SingleValue(Some(KeyframesName::QuotedString(other_name.clone())))])); + assert_eq!( + parse_longhand!(animation_name, "none"), + animation_name::SpecifiedValue(vec![SingleValue(None)]) + ); + assert_eq!( + parse_longhand!( + animation_name, + "other-name, none, 'other-name', \"other-name\"" + ), + animation_name::SpecifiedValue(vec![ + SingleValue(Some(KeyframesName::Ident(CustomIdent(other_name.clone())))), + SingleValue(None), + SingleValue(Some(KeyframesName::QuotedString(other_name.clone()))), + SingleValue(Some(KeyframesName::QuotedString(other_name.clone()))) + ]) + ); } #[test] diff --git a/tests/unit/style/parsing/background.rs b/tests/unit/style/parsing/background.rs index dd47e4d1a9e..2afb894ecf8 100644 --- a/tests/unit/style/parsing/background.rs +++ b/tests/unit/style/parsing/background.rs @@ -13,72 +13,179 @@ fn background_shorthand_should_parse_all_available_properties_when_specified() { let input = "url(\"http://servo/test.png\") top center / 200px 200px repeat-x fixed padding-box content-box red"; let result = parse(background::parse_value, input).unwrap(); - assert_eq!(result.background_image, parse_longhand!(background_image, "url(\"http://servo/test.png\")")); - assert_eq!(result.background_position_x, parse_longhand!(background_position_x, "center")); - assert_eq!(result.background_position_y, parse_longhand!(background_position_y, "top")); - assert_eq!(result.background_size, parse_longhand!(background_size, "200px 200px")); - assert_eq!(result.background_repeat, parse_longhand!(background_repeat, "repeat-x")); - assert_eq!(result.background_attachment, parse_longhand!(background_attachment, "fixed")); - assert_eq!(result.background_origin, parse_longhand!(background_origin, "padding-box")); - assert_eq!(result.background_clip, parse_longhand!(background_clip, "content-box")); - assert_eq!(result.background_color, parse_longhand!(background_color, "red")); + assert_eq!( + result.background_image, + parse_longhand!(background_image, "url(\"http://servo/test.png\")") + ); + assert_eq!( + result.background_position_x, + parse_longhand!(background_position_x, "center") + ); + assert_eq!( + result.background_position_y, + parse_longhand!(background_position_y, "top") + ); + assert_eq!( + result.background_size, + parse_longhand!(background_size, "200px 200px") + ); + assert_eq!( + result.background_repeat, + parse_longhand!(background_repeat, "repeat-x") + ); + assert_eq!( + result.background_attachment, + parse_longhand!(background_attachment, "fixed") + ); + assert_eq!( + result.background_origin, + parse_longhand!(background_origin, "padding-box") + ); + assert_eq!( + result.background_clip, + parse_longhand!(background_clip, "content-box") + ); + assert_eq!( + result.background_color, + parse_longhand!(background_color, "red") + ); } #[test] fn background_shorthand_should_parse_when_some_fields_set() { let result = parse(background::parse_value, "14px 40px repeat-y").unwrap(); - assert_eq!(result.background_position_x, parse_longhand!(background_position_x, "14px")); - assert_eq!(result.background_position_y, parse_longhand!(background_position_y, "40px")); - assert_eq!(result.background_repeat, parse_longhand!(background_repeat, "repeat-y")); - - let result = parse(background::parse_value, "url(\"http://servo/test.png\") repeat blue").unwrap(); - - assert_eq!(result.background_image, parse_longhand!(background_image, "url(\"http://servo/test.png\")")); - assert_eq!(result.background_repeat, parse_longhand!(background_repeat, "repeat")); - assert_eq!(result.background_color, parse_longhand!(background_color, "blue")); + assert_eq!( + result.background_position_x, + parse_longhand!(background_position_x, "14px") + ); + assert_eq!( + result.background_position_y, + parse_longhand!(background_position_y, "40px") + ); + assert_eq!( + result.background_repeat, + parse_longhand!(background_repeat, "repeat-y") + ); + + let result = parse( + background::parse_value, + "url(\"http://servo/test.png\") repeat blue", + ) + .unwrap(); + + assert_eq!( + result.background_image, + parse_longhand!(background_image, "url(\"http://servo/test.png\")") + ); + assert_eq!( + result.background_repeat, + parse_longhand!(background_repeat, "repeat") + ); + assert_eq!( + result.background_color, + parse_longhand!(background_color, "blue") + ); let result = parse(background::parse_value, "padding-box").unwrap(); - assert_eq!(result.background_origin, parse_longhand!(background_origin, "padding-box")); - assert_eq!(result.background_clip, parse_longhand!(background_clip, "padding-box")); + assert_eq!( + result.background_origin, + parse_longhand!(background_origin, "padding-box") + ); + assert_eq!( + result.background_clip, + parse_longhand!(background_clip, "padding-box") + ); let result = parse(background::parse_value, "url(\"http://servo/test.png\")").unwrap(); - assert_eq!(result.background_image, parse_longhand!(background_image, "url(\"http://servo/test.png\")")); + assert_eq!( + result.background_image, + parse_longhand!(background_image, "url(\"http://servo/test.png\")") + ); } #[test] fn background_shorthand_should_parse_comma_separated_declarations() { - let input = "url(\"http://servo/test.png\") top left no-repeat, url(\"http://servo/test.png\") \ - center / 100% 100% no-repeat, white"; + let input = + "url(\"http://servo/test.png\") top left no-repeat, url(\"http://servo/test.png\") \ + center / 100% 100% no-repeat, white"; let result = parse(background::parse_value, input).unwrap(); - assert_eq!(result.background_image, parse_longhand!(background_image, "url(\"http://servo/test.png\"), \ - url(\"http://servo/test.png\"), none")); - assert_eq!(result.background_position_x, parse_longhand!(background_position_x, "left, center, 0%")); - assert_eq!(result.background_position_y, parse_longhand!(background_position_y, "top, center, 0%")); - assert_eq!(result.background_repeat, parse_longhand!(background_repeat, "no-repeat, no-repeat, repeat")); - assert_eq!(result.background_clip, parse_longhand!(background_clip, "border-box, border-box, border-box")); - assert_eq!(result.background_origin, parse_longhand!(background_origin, "padding-box, padding-box, \ - padding-box")); - assert_eq!(result.background_size, parse_longhand!(background_size, "auto auto, 100% 100%, auto auto")); - assert_eq!(result.background_attachment, parse_longhand!(background_attachment, "scroll, scroll, scroll")); - assert_eq!(result.background_color, parse_longhand!(background_color, "white")); + assert_eq!( + result.background_image, + parse_longhand!( + background_image, + "url(\"http://servo/test.png\"), \ + url(\"http://servo/test.png\"), none" + ) + ); + assert_eq!( + result.background_position_x, + parse_longhand!(background_position_x, "left, center, 0%") + ); + assert_eq!( + result.background_position_y, + parse_longhand!(background_position_y, "top, center, 0%") + ); + assert_eq!( + result.background_repeat, + parse_longhand!(background_repeat, "no-repeat, no-repeat, repeat") + ); + assert_eq!( + result.background_clip, + parse_longhand!(background_clip, "border-box, border-box, border-box") + ); + assert_eq!( + result.background_origin, + parse_longhand!( + background_origin, + "padding-box, padding-box, \ + padding-box" + ) + ); + assert_eq!( + result.background_size, + parse_longhand!(background_size, "auto auto, 100% 100%, auto auto") + ); + assert_eq!( + result.background_attachment, + parse_longhand!(background_attachment, "scroll, scroll, scroll") + ); + assert_eq!( + result.background_color, + parse_longhand!(background_color, "white") + ); } #[test] fn background_shorthand_should_parse_position_and_size_correctly() { let result = parse(background::parse_value, "7px 4px").unwrap(); - assert_eq!(result.background_position_x, parse_longhand!(background_position_x, "7px")); - assert_eq!(result.background_position_y, parse_longhand!(background_position_y, "4px")); + assert_eq!( + result.background_position_x, + parse_longhand!(background_position_x, "7px") + ); + assert_eq!( + result.background_position_y, + parse_longhand!(background_position_y, "4px") + ); let result = parse(background::parse_value, "7px 4px / 30px 20px").unwrap(); - assert_eq!(result.background_position_x, parse_longhand!(background_position_x, "7px")); - assert_eq!(result.background_position_y, parse_longhand!(background_position_y, "4px")); - assert_eq!(result.background_size, parse_longhand!(background_size, "30px 20px")); + assert_eq!( + result.background_position_x, + parse_longhand!(background_position_x, "7px") + ); + assert_eq!( + result.background_position_y, + parse_longhand!(background_position_y, "4px") + ); + assert_eq!( + result.background_size, + parse_longhand!(background_size, "30px 20px") + ); assert!(parse(background::parse_value, "/ 30px 20px").is_err()); @@ -89,16 +196,34 @@ fn background_shorthand_should_parse_position_and_size_correctly() { fn background_shorthand_should_parse_origin_and_clip_correctly() { let result = parse(background::parse_value, "padding-box content-box").unwrap(); - assert_eq!(result.background_origin, parse_longhand!(background_origin, "padding-box")); - assert_eq!(result.background_clip, parse_longhand!(background_clip, "content-box")); + assert_eq!( + result.background_origin, + parse_longhand!(background_origin, "padding-box") + ); + assert_eq!( + result.background_clip, + parse_longhand!(background_clip, "content-box") + ); let result = parse(background::parse_value, "padding-box padding-box").unwrap(); - assert_eq!(result.background_origin, parse_longhand!(background_origin, "padding-box")); - assert_eq!(result.background_clip, parse_longhand!(background_clip, "padding-box")); + assert_eq!( + result.background_origin, + parse_longhand!(background_origin, "padding-box") + ); + assert_eq!( + result.background_clip, + parse_longhand!(background_clip, "padding-box") + ); let result = parse(background::parse_value, "padding-box").unwrap(); - assert_eq!(result.background_origin, parse_longhand!(background_origin, "padding-box")); - assert_eq!(result.background_clip, parse_longhand!(background_clip, "padding-box")); + assert_eq!( + result.background_origin, + parse_longhand!(background_origin, "padding-box") + ); + assert_eq!( + result.background_clip, + parse_longhand!(background_clip, "padding-box") + ); } diff --git a/tests/unit/style/parsing/border.rs b/tests/unit/style/parsing/border.rs index 0eadbec4f31..635e3c60a71 100644 --- a/tests/unit/style/parsing/border.rs +++ b/tests/unit/style/parsing/border.rs @@ -13,31 +13,60 @@ use style_traits::ToCss; macro_rules! assert_longhand { ($parsed_shorthand: expr, $prop: ident, $value_string: expr) => { - assert_eq!($parsed_shorthand.$prop, parse_longhand!($prop, $value_string).maybe_boxed()) - } + assert_eq!( + $parsed_shorthand.$prop, + parse_longhand!($prop, $value_string).maybe_boxed() + ) + }; } macro_rules! assert_initial { ($parsed_shorthand: expr, $prop: ident) => { - assert_eq!($parsed_shorthand.$prop, $prop::get_initial_specified_value().maybe_boxed()) - } + assert_eq!( + $parsed_shorthand.$prop, + $prop::get_initial_specified_value().maybe_boxed() + ) + }; } macro_rules! assert_border_radius_values { ($input:expr; $tlw:expr, $trw:expr, $brw:expr, $blw:expr ; $tlh:expr, $trh:expr, $brh:expr, $blh:expr) => { let input = parse(BorderRadius::parse, $input) - .expect(&format!("Failed parsing {} as border radius", - $input)); - assert_eq!(::style_traits::ToCss::to_css_string(&input.top_left.0.width()), $tlw); - assert_eq!(::style_traits::ToCss::to_css_string(&input.top_right.0.width()), $trw); - assert_eq!(::style_traits::ToCss::to_css_string(&input.bottom_right.0.width()), $brw); - assert_eq!(::style_traits::ToCss::to_css_string(&input.bottom_left.0.width()), $blw); - assert_eq!(::style_traits::ToCss::to_css_string(&input.top_left.0.height()), $tlh); - assert_eq!(::style_traits::ToCss::to_css_string(&input.top_right.0.height()), $trh); - assert_eq!(::style_traits::ToCss::to_css_string(&input.bottom_right.0.height()), $brh); - assert_eq!(::style_traits::ToCss::to_css_string(&input.bottom_left.0.height()), $blh); - } + .expect(&format!("Failed parsing {} as border radius", $input)); + assert_eq!( + ::style_traits::ToCss::to_css_string(&input.top_left.0.width()), + $tlw + ); + assert_eq!( + ::style_traits::ToCss::to_css_string(&input.top_right.0.width()), + $trw + ); + assert_eq!( + ::style_traits::ToCss::to_css_string(&input.bottom_right.0.width()), + $brw + ); + assert_eq!( + ::style_traits::ToCss::to_css_string(&input.bottom_left.0.width()), + $blw + ); + assert_eq!( + ::style_traits::ToCss::to_css_string(&input.top_left.0.height()), + $tlh + ); + assert_eq!( + ::style_traits::ToCss::to_css_string(&input.top_right.0.height()), + $trh + ); + assert_eq!( + ::style_traits::ToCss::to_css_string(&input.bottom_right.0.height()), + $brh + ); + assert_eq!( + ::style_traits::ToCss::to_css_string(&input.bottom_left.0.height()), + $blh + ); + }; } #[test] diff --git a/tests/unit/style/parsing/effects.rs b/tests/unit/style/parsing/effects.rs index 79fd1937e52..9e1836d6667 100644 --- a/tests/unit/style/parsing/effects.rs +++ b/tests/unit/style/parsing/effects.rs @@ -16,18 +16,26 @@ fn test_clip() { assert_roundtrip_with_context!(clip::parse, "rect(auto, auto, auto, auto)"); // Non-standard syntax - assert_roundtrip_with_context!(clip::parse, - "rect(1px 2px 3px 4px)", - "rect(1px, 2px, 3px, 4px)"); - assert_roundtrip_with_context!(clip::parse, - "rect(auto 2px 3px auto)", - "rect(auto, 2px, 3px, auto)"); - assert_roundtrip_with_context!(clip::parse, - "rect(1px auto auto 4px)", - "rect(1px, auto, auto, 4px)"); - assert_roundtrip_with_context!(clip::parse, - "rect(auto auto auto auto)", - "rect(auto, auto, auto, auto)"); + assert_roundtrip_with_context!( + clip::parse, + "rect(1px 2px 3px 4px)", + "rect(1px, 2px, 3px, 4px)" + ); + assert_roundtrip_with_context!( + clip::parse, + "rect(auto 2px 3px auto)", + "rect(auto, 2px, 3px, auto)" + ); + assert_roundtrip_with_context!( + clip::parse, + "rect(1px auto auto 4px)", + "rect(1px, auto, auto, 4px)" + ); + assert_roundtrip_with_context!( + clip::parse, + "rect(auto auto auto auto)", + "rect(auto, auto, auto, auto)" + ); } #[test] @@ -85,7 +93,7 @@ fn test_parse_factor() { #[test] fn blur_radius_should_not_accept_negavite_values() { use style::properties::longhands::box_shadow; - assert!(parse(box_shadow::parse, "1px 1px -1px").is_err());// for -ve values - assert!(parse(box_shadow::parse, "1px 1px 0").is_ok());// for zero - assert!(parse(box_shadow::parse, "1px 1px 1px").is_ok());// for +ve value + assert!(parse(box_shadow::parse, "1px 1px -1px").is_err()); // for -ve values + assert!(parse(box_shadow::parse, "1px 1px 0").is_ok()); // for zero + assert!(parse(box_shadow::parse, "1px 1px 1px").is_ok()); // for +ve value } diff --git a/tests/unit/style/parsing/image.rs b/tests/unit/style/parsing/image.rs index e171cd29ca8..bbc83b5e070 100644 --- a/tests/unit/style/parsing/image.rs +++ b/tests/unit/style/parsing/image.rs @@ -33,72 +33,122 @@ fn test_linear_gradient() { #[test] fn test_radial_gradient() { // Parsing with all values - assert_roundtrip_with_context!(Image::parse, "radial-gradient(circle closest-side at 20px 30px, red, green)"); - assert_roundtrip_with_context!(Image::parse, "radial-gradient(ellipse closest-side at 20px 30px, red, green)", - "radial-gradient(closest-side at 20px 30px, red, green)"); - assert_roundtrip_with_context!(Image::parse, "radial-gradient(closest-side circle at 20px 30px, red, green)", - "radial-gradient(circle closest-side at 20px 30px, red, green)"); - assert_roundtrip_with_context!(Image::parse, "radial-gradient(closest-side ellipse at 20px 30px, red, green)", - "radial-gradient(closest-side at 20px 30px, red, green)"); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(circle closest-side at 20px 30px, red, green)" + ); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(ellipse closest-side at 20px 30px, red, green)", + "radial-gradient(closest-side at 20px 30px, red, green)" + ); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(closest-side circle at 20px 30px, red, green)", + "radial-gradient(circle closest-side at 20px 30px, red, green)" + ); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(closest-side ellipse at 20px 30px, red, green)", + "radial-gradient(closest-side at 20px 30px, red, green)" + ); // Parsing with <shape-keyword> and <size> reversed - assert_roundtrip_with_context!(Image::parse, "radial-gradient(closest-side circle at 20px 30px, red, green)", - "radial-gradient(circle closest-side at 20px 30px, red, green)"); - assert_roundtrip_with_context!(Image::parse, "radial-gradient(closest-corner ellipse at 20px 30px, red, green)", - "radial-gradient(closest-corner at 20px 30px, red, green)"); - assert_roundtrip_with_context!(Image::parse, "radial-gradient(30px circle, red, green)", - "radial-gradient(30px at center center, red, green)"); - assert_roundtrip_with_context!(Image::parse, "radial-gradient(30px 40px ellipse, red, green)", - "radial-gradient(30px 40px at center center, red, green)"); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(closest-side circle at 20px 30px, red, green)", + "radial-gradient(circle closest-side at 20px 30px, red, green)" + ); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(closest-corner ellipse at 20px 30px, red, green)", + "radial-gradient(closest-corner at 20px 30px, red, green)" + ); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(30px circle, red, green)", + "radial-gradient(30px at center center, red, green)" + ); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(30px 40px ellipse, red, green)", + "radial-gradient(30px 40px at center center, red, green)" + ); // Parsing without <size> - assert_roundtrip_with_context!(Image::parse, - "radial-gradient(circle, red, green)", - "radial-gradient(circle at center center, red, green)"); - assert_roundtrip_with_context!(Image::parse, - "radial-gradient(ellipse, red, green)", - "radial-gradient(at center center, red, green)"); - assert_roundtrip_with_context!(Image::parse, - "radial-gradient(circle at 20px 30px, red, green)"); - assert_roundtrip_with_context!(Image::parse, - "radial-gradient(ellipse at 20px 30px, red, green)", - "radial-gradient(at 20px 30px, red, green)"); - + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(circle, red, green)", + "radial-gradient(circle at center center, red, green)" + ); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(ellipse, red, green)", + "radial-gradient(at center center, red, green)" + ); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(circle at 20px 30px, red, green)" + ); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(ellipse at 20px 30px, red, green)", + "radial-gradient(at 20px 30px, red, green)" + ); // Parsing without <shape-keyword> - assert_roundtrip_with_context!(Image::parse, - "radial-gradient(20px at 20px 30px, red, green)"); - assert_roundtrip_with_context!(Image::parse, - "radial-gradient(20px 30px at left center, red, green)"); - assert_roundtrip_with_context!(Image::parse, - "radial-gradient(closest-side at center, red, green)", - "radial-gradient(closest-side at center center, red, green)"); - assert_roundtrip_with_context!(Image::parse, - "radial-gradient(20px, red, green)", - "radial-gradient(20px at center center, red, green)"); - assert_roundtrip_with_context!(Image::parse, - "radial-gradient(20px 30px, red, green)", - "radial-gradient(20px 30px at center center, red, green)"); - assert_roundtrip_with_context!(Image::parse, - "radial-gradient(closest-side, red, green)", - "radial-gradient(closest-side at center center, red, green)"); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(20px at 20px 30px, red, green)" + ); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(20px 30px at left center, red, green)" + ); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(closest-side at center, red, green)", + "radial-gradient(closest-side at center center, red, green)" + ); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(20px, red, green)", + "radial-gradient(20px at center center, red, green)" + ); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(20px 30px, red, green)", + "radial-gradient(20px 30px at center center, red, green)" + ); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(closest-side, red, green)", + "radial-gradient(closest-side at center center, red, green)" + ); // Parsing without <shape-keyword> and <size> - assert_roundtrip_with_context!(Image::parse, - "radial-gradient(at center, red, green)", - "radial-gradient(at center center, red, green)"); - assert_roundtrip_with_context!(Image::parse, - "radial-gradient(at center bottom, red, green)"); - assert_roundtrip_with_context!(Image::parse, - "radial-gradient(at 40px 50px, red, green)"); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(at center, red, green)", + "radial-gradient(at center center, red, green)" + ); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(at center bottom, red, green)" + ); + assert_roundtrip_with_context!(Image::parse, "radial-gradient(at 40px 50px, red, green)"); // Parsing with just color stops - assert_roundtrip_with_context!(Image::parse, - "radial-gradient(red, green)", - "radial-gradient(at center center, red, green)"); + assert_roundtrip_with_context!( + Image::parse, + "radial-gradient(red, green)", + "radial-gradient(at center center, red, green)" + ); // Parsing repeating radial gradient - assert_roundtrip_with_context!(Image::parse, - "repeating-radial-gradient(red, green)", - "repeating-radial-gradient(at center center, red, green)"); + assert_roundtrip_with_context!( + Image::parse, + "repeating-radial-gradient(red, green)", + "repeating-radial-gradient(at center center, red, green)" + ); } diff --git a/tests/unit/style/parsing/inherited_text.rs b/tests/unit/style/parsing/inherited_text.rs index 85b99a85fc7..6f923887c4d 100644 --- a/tests/unit/style/parsing/inherited_text.rs +++ b/tests/unit/style/parsing/inherited_text.rs @@ -11,7 +11,9 @@ fn negative_letter_spacing_should_parse_properly() { use style::values::specified::length::{Length, NoCalcLength, FontRelativeLength}; let negative_value = parse_longhand!(letter_spacing, "-0.5em"); - let expected = Spacing::Value(Length::NoCalc(NoCalcLength::FontRelative(FontRelativeLength::Em(-0.5)))); + let expected = Spacing::Value(Length::NoCalc(NoCalcLength::FontRelative( + FontRelativeLength::Em(-0.5), + ))); assert_eq!(negative_value, expected); } @@ -21,9 +23,9 @@ fn negative_word_spacing_should_parse_properly() { use style::values::specified::length::{NoCalcLength, LengthOrPercentage, FontRelativeLength}; let negative_value = parse_longhand!(word_spacing, "-0.5em"); - let expected = Spacing::Value(LengthOrPercentage::Length( - NoCalcLength::FontRelative(FontRelativeLength::Em(-0.5)) - )); + let expected = Spacing::Value(LengthOrPercentage::Length(NoCalcLength::FontRelative( + FontRelativeLength::Em(-0.5), + ))); assert_eq!(negative_value, expected); } diff --git a/tests/unit/style/parsing/mod.rs b/tests/unit/style/parsing/mod.rs index 6f76b2efea6..a801b3d6605 100644 --- a/tests/unit/style/parsing/mod.rs +++ b/tests/unit/style/parsing/mod.rs @@ -11,13 +11,17 @@ use style::stylesheets::{CssRuleType, Origin}; use style_traits::{ParsingMode, ParseError}; fn parse<T, F>(f: F, s: &'static str) -> Result<T, ParseError<'static>> -where F: for<'t> Fn(&ParserContext, &mut Parser<'static, 't>) -> Result<T, ParseError<'static>> { +where + F: for<'t> Fn(&ParserContext, &mut Parser<'static, 't>) -> Result<T, ParseError<'static>>, +{ let mut input = ParserInput::new(s); parse_input(f, &mut input) } fn parse_input<'i: 't, 't, T, F>(f: F, input: &'t mut ParserInput<'i>) -> Result<T, ParseError<'i>> -where F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>> { +where + F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>>, +{ let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new( Origin::Author, @@ -33,14 +37,24 @@ where F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>> { } fn parse_entirely<T, F>(f: F, s: &'static str) -> Result<T, ParseError<'static>> -where F: for<'t> Fn(&ParserContext, &mut Parser<'static, 't>) -> Result<T, ParseError<'static>> { +where + F: for<'t> Fn(&ParserContext, &mut Parser<'static, 't>) -> Result<T, ParseError<'static>>, +{ let mut input = ParserInput::new(s); parse_entirely_input(f, &mut input) } -fn parse_entirely_input<'i: 't, 't, T, F>(f: F, input: &'t mut ParserInput<'i>) -> Result<T, ParseError<'i>> -where F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>> { - parse_input(|context, parser| parser.parse_entirely(|p| f(context, p)), input) +fn parse_entirely_input<'i: 't, 't, T, F>( + f: F, + input: &'t mut ParserInput<'i>, +) -> Result<T, ParseError<'i>> +where + F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>>, +{ + parse_input( + |context, parser| parser.parse_entirely(|p| f(context, p)), + input, + ) } // This is a macro so that the file/line information @@ -51,24 +65,31 @@ macro_rules! assert_roundtrip_with_context { }; ($fun:expr, $input:expr, $output:expr) => {{ let mut input = ::cssparser::ParserInput::new($input); - let serialized = super::parse_input(|context, i| { - let parsed = $fun(context, i) - .expect(&format!("Failed to parse {}", $input)); - let serialized = ToCss::to_css_string(&parsed); - assert_eq!(serialized, $output); - Ok(serialized) - }, &mut input).unwrap(); + let serialized = super::parse_input( + |context, i| { + let parsed = $fun(context, i).expect(&format!("Failed to parse {}", $input)); + let serialized = ToCss::to_css_string(&parsed); + assert_eq!(serialized, $output); + Ok(serialized) + }, + &mut input, + ) + .unwrap(); let mut input = ::cssparser::ParserInput::new(&serialized); - let unwrapped = super::parse_input(|context, i| { - let re_parsed = $fun(context, i) - .expect(&format!("Failed to parse serialization {}", $input)); - let re_serialized = ToCss::to_css_string(&re_parsed); - assert_eq!(serialized, re_serialized); - Ok(()) - }, &mut input).unwrap(); + let unwrapped = super::parse_input( + |context, i| { + let re_parsed = + $fun(context, i).expect(&format!("Failed to parse serialization {}", $input)); + let re_serialized = ToCss::to_css_string(&re_parsed); + assert_eq!(serialized, re_serialized); + Ok(()) + }, + &mut input, + ) + .unwrap(); unwrapped - }} + }}; } macro_rules! assert_roundtrip { @@ -78,34 +99,37 @@ macro_rules! assert_roundtrip { ($fun:expr, $input:expr, $output:expr) => { let mut input = ParserInput::new($input); let mut parser = Parser::new(&mut input); - let parsed = $fun(&mut parser) - .expect(&format!("Failed to parse {}", $input)); + let parsed = $fun(&mut parser).expect(&format!("Failed to parse {}", $input)); let serialized = ToCss::to_css_string(&parsed); assert_eq!(serialized, $output); let mut input = ParserInput::new(&serialized); let mut parser = Parser::new(&mut input); - let re_parsed = $fun(&mut parser) - .expect(&format!("Failed to parse serialization {}", $input)); + let re_parsed = + $fun(&mut parser).expect(&format!("Failed to parse serialization {}", $input)); let re_serialized = ToCss::to_css_string(&re_parsed); assert_eq!(serialized, re_serialized) - } + }; } macro_rules! assert_parser_exhausted { ($fun:expr, $string:expr, $should_exhausted:expr) => {{ - parse(|context, input| { - let parsed = $fun(context, input); - assert_eq!(parsed.is_ok(), true); - assert_eq!(input.is_exhausted(), $should_exhausted); - Ok(()) - }, $string).unwrap() - }} + parse( + |context, input| { + let parsed = $fun(context, input); + assert_eq!(parsed.is_ok(), true); + assert_eq!(input.is_exhausted(), $should_exhausted); + Ok(()) + }, + $string, + ) + .unwrap() + }}; } macro_rules! parse_longhand { ($name:ident, $s:expr) => { - parse($name::parse, $s).unwrap() + parse($name::parse, $s).unwrap() }; } diff --git a/tests/unit/style/parsing/position.rs b/tests/unit/style/parsing/position.rs index 5494f6c9c12..d97e79cbc64 100644 --- a/tests/unit/style/parsing/position.rs +++ b/tests/unit/style/parsing/position.rs @@ -143,4 +143,3 @@ fn test_vertical_position() { assert!(parse(VerticalPosition::parse, "y-start").is_err()); assert!(parse(VerticalPosition::parse, "y-end").is_err()); } - diff --git a/tests/unit/style/parsing/selectors.rs b/tests/unit/style/parsing/selectors.rs index 5ace20370d4..8fbfbfc4f24 100644 --- a/tests/unit/style/parsing/selectors.rs +++ b/tests/unit/style/parsing/selectors.rs @@ -8,7 +8,9 @@ use style::selector_parser::{SelectorImpl, SelectorParser}; use style::stylesheets::{Origin, Namespaces}; use style_traits::ParseError; -fn parse_selector<'i, 't>(input: &mut Parser<'i, 't>) -> Result<SelectorList<SelectorImpl>, ParseError<'i>> { +fn parse_selector<'i, 't>( + input: &mut Parser<'i, 't>, +) -> Result<SelectorList<SelectorImpl>, ParseError<'i>> { let mut ns = Namespaces::default(); ns.prefixes.insert("svg".into(), ns!(svg)); let parser = SelectorParser { @@ -24,7 +26,10 @@ fn test_selectors() { assert_roundtrip!(parse_selector, "div"); assert_roundtrip!(parse_selector, "svg|circle"); assert_roundtrip!(parse_selector, "p:before", "p::before"); - assert_roundtrip!(parse_selector, "[border=\"0\"]:-servo-nonzero-border ~ ::-servo-details-summary"); + assert_roundtrip!( + parse_selector, + "[border=\"0\"]:-servo-nonzero-border ~ ::-servo-details-summary" + ); assert_roundtrip!(parse_selector, "* > *"); assert_roundtrip!(parse_selector, "*|* + *", "* + *"); } diff --git a/tests/unit/style/parsing/supports.rs b/tests/unit/style/parsing/supports.rs index 573be52d767..285db477af1 100644 --- a/tests/unit/style/parsing/supports.rs +++ b/tests/unit/style/parsing/supports.rs @@ -10,7 +10,10 @@ use style_traits::ToCss; fn test_supports_condition() { assert_roundtrip!(SupportsCondition::parse, "(margin: 1px)"); assert_roundtrip!(SupportsCondition::parse, "not (--be: to be)"); - assert_roundtrip!(SupportsCondition::parse, "(color: blue) and future-extension(4)"); + assert_roundtrip!( + SupportsCondition::parse, + "(color: blue) and future-extension(4)" + ); assert_roundtrip!(SupportsCondition::parse, "future-\\1 extension(4)"); assert_roundtrip!(SupportsCondition::parse, "((test))"); } diff --git a/tests/unit/style/parsing/transition_timing_function.rs b/tests/unit/style/parsing/transition_timing_function.rs index dab50b34275..46af0a5f7c3 100644 --- a/tests/unit/style/parsing/transition_timing_function.rs +++ b/tests/unit/style/parsing/transition_timing_function.rs @@ -8,14 +8,41 @@ use style_traits::ToCss; #[test] fn test_cubic_bezier() { - assert_roundtrip_with_context!(transition_timing_function::parse, "cubic-bezier(0, 0, 0, 0)"); - assert_roundtrip_with_context!(transition_timing_function::parse, "cubic-bezier(0.25, 0, 0.5, 0)"); - assert_roundtrip_with_context!(transition_timing_function::parse, "cubic-bezier(1, 1, 1, 1)"); + assert_roundtrip_with_context!( + transition_timing_function::parse, + "cubic-bezier(0, 0, 0, 0)" + ); + assert_roundtrip_with_context!( + transition_timing_function::parse, + "cubic-bezier(0.25, 0, 0.5, 0)" + ); + assert_roundtrip_with_context!( + transition_timing_function::parse, + "cubic-bezier(1, 1, 1, 1)" + ); // p1x and p2x values must be in range [0, 1] - assert!(parse(transition_timing_function::parse, "cubic-bezier(-1, 0, 0, 0").is_err()); - assert!(parse(transition_timing_function::parse, "cubic-bezier(0, 0, -1, 0").is_err()); - assert!(parse(transition_timing_function::parse, "cubic-bezier(-1, 0, -1, 0").is_err()); + assert!( + parse( + transition_timing_function::parse, + "cubic-bezier(-1, 0, 0, 0" + ) + .is_err() + ); + assert!( + parse( + transition_timing_function::parse, + "cubic-bezier(0, 0, -1, 0" + ) + .is_err() + ); + assert!( + parse( + transition_timing_function::parse, + "cubic-bezier(-1, 0, -1, 0" + ) + .is_err() + ); assert!(parse(transition_timing_function::parse, "cubic-bezier(2, 0, 0, 0").is_err()); assert!(parse(transition_timing_function::parse, "cubic-bezier(0, 0, 2, 0").is_err()); @@ -27,7 +54,11 @@ fn test_steps() { assert_roundtrip_with_context!(transition_timing_function::parse, "steps(1)"); assert_roundtrip_with_context!(transition_timing_function::parse, "steps( 1)", "steps(1)"); assert_roundtrip_with_context!(transition_timing_function::parse, "steps(1, start)"); - assert_roundtrip_with_context!(transition_timing_function::parse, "steps(2, end) ", "steps(2)"); + assert_roundtrip_with_context!( + transition_timing_function::parse, + "steps(2, end) ", + "steps(2)" + ); // Step interval value must be an integer greater than 0 assert!(parse(transition_timing_function::parse, "steps(0)").is_err()); diff --git a/tests/unit/style/properties/mod.rs b/tests/unit/style/properties/mod.rs index 5210b663168..0ceaf7c02e5 100644 --- a/tests/unit/style/properties/mod.rs +++ b/tests/unit/style/properties/mod.rs @@ -10,10 +10,7 @@ use style_traits::{ParsingMode, ParseError}; fn parse<T, F>(f: F, s: &'static str) -> Result<T, ParseError<'static>> where - F: for<'t> Fn( - &ParserContext, - &mut Parser<'static, 't>, - ) -> Result<T, ParseError<'static>> + F: for<'t> Fn(&ParserContext, &mut Parser<'static, 't>) -> Result<T, ParseError<'static>>, { let mut input = ParserInput::new(s); parse_input(f, &mut input) @@ -42,24 +39,31 @@ macro_rules! assert_roundtrip_with_context { assert_roundtrip_with_context!($fun, $string, $string); }; ($fun:expr, $input:expr, $output:expr) => {{ - let serialized = parse(|context, i| { - let parsed = $fun(context, i) - .expect(&format!("Failed to parse {}", $input)); - let serialized = ToCss::to_css_string(&parsed); - assert_eq!(serialized, $output); - Ok(serialized) - }, $input).unwrap(); + let serialized = parse( + |context, i| { + let parsed = $fun(context, i).expect(&format!("Failed to parse {}", $input)); + let serialized = ToCss::to_css_string(&parsed); + assert_eq!(serialized, $output); + Ok(serialized) + }, + $input, + ) + .unwrap(); let mut input = ::cssparser::ParserInput::new(&serialized); - let unwrapped = parse_input(|context, i| { - let re_parsed = $fun(context, i) - .expect(&format!("Failed to parse serialization {}", $input)); - let re_serialized = ToCss::to_css_string(&re_parsed); - assert_eq!(serialized, re_serialized); - Ok(()) - }, &mut input).unwrap(); + let unwrapped = parse_input( + |context, i| { + let re_parsed = + $fun(context, i).expect(&format!("Failed to parse serialization {}", $input)); + let re_serialized = ToCss::to_css_string(&re_parsed); + assert_eq!(serialized, re_serialized); + Ok(()) + }, + &mut input, + ) + .unwrap(); unwrapped - }} + }}; } mod scaffolding; diff --git a/tests/unit/style/properties/scaffolding.rs b/tests/unit/style/properties/scaffolding.rs index faa727ff613..56fa88165ef 100644 --- a/tests/unit/style/properties/scaffolding.rs +++ b/tests/unit/style/properties/scaffolding.rs @@ -10,13 +10,24 @@ use std::process::Command; #[test] fn properties_list_json() { - let top = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap()).join("..").join("..").join(".."); - let json = top.join("target").join("doc").join("servo").join("css-properties.json"); + let top = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap()) + .join("..") + .join("..") + .join(".."); + let json = top + .join("target") + .join("doc") + .join("servo") + .join("css-properties.json"); if json.exists() { remove_file(&json).unwrap() } let python = env::var("PYTHON").ok().unwrap_or_else(find_python); - let script = top.join("components").join("style").join("properties").join("build.py"); + let script = top + .join("components") + .join("style") + .join("properties") + .join("build.py"); let status = Command::new(python) .arg(&script) .arg("servo") @@ -34,11 +45,19 @@ fn properties_list_json() { #[cfg(windows)] fn find_python() -> String { - if Command::new("python2.7.exe").arg("--version").output().is_ok() { + if Command::new("python2.7.exe") + .arg("--version") + .output() + .is_ok() + { return "python2.7.exe".to_owned(); } - if Command::new("python27.exe").arg("--version").output().is_ok() { + if Command::new("python27.exe") + .arg("--version") + .output() + .is_ok() + { return "python27.exe".to_owned(); } @@ -51,9 +70,16 @@ fn find_python() -> String { #[cfg(not(windows))] fn find_python() -> String { - if Command::new("python2.7").arg("--version").output().unwrap().status.success() { + if Command::new("python2.7") + .arg("--version") + .output() + .unwrap() + .status + .success() + { "python2.7" } else { "python" - }.to_owned() + } + .to_owned() } diff --git a/tests/unit/style/properties/serialization.rs b/tests/unit/style/properties/serialization.rs index 5c520ccc79d..cf37bcc0ca9 100644 --- a/tests/unit/style/properties/serialization.rs +++ b/tests/unit/style/properties/serialization.rs @@ -32,28 +32,36 @@ fn property_declaration_block_should_serialize_correctly() { use style::properties::longhands::overflow_x::SpecifiedValue as OverflowValue; let declarations = vec![ - (PropertyDeclaration::Width( - LengthOrPercentageOrAuto::Length(NoCalcLength::from_px(70f32))), - Importance::Normal), - - (PropertyDeclaration::MinHeight( - LengthOrPercentage::Length(NoCalcLength::from_px(20f32))), - Importance::Normal), - - (PropertyDeclaration::Height( - LengthOrPercentageOrAuto::Length(NoCalcLength::from_px(20f32))), - Importance::Important), - - (PropertyDeclaration::Display(Display::InlineBlock), - Importance::Normal), - - (PropertyDeclaration::OverflowX( - OverflowValue::Auto), - Importance::Normal), - - (PropertyDeclaration::OverflowY( - OverflowValue::Auto), - Importance::Normal), + ( + PropertyDeclaration::Width(LengthOrPercentageOrAuto::Length(NoCalcLength::from_px( + 70f32, + ))), + Importance::Normal, + ), + ( + PropertyDeclaration::MinHeight(LengthOrPercentage::Length(NoCalcLength::from_px( + 20f32, + ))), + Importance::Normal, + ), + ( + PropertyDeclaration::Height(LengthOrPercentageOrAuto::Length(NoCalcLength::from_px( + 20f32, + ))), + Importance::Important, + ), + ( + PropertyDeclaration::Display(Display::InlineBlock), + Importance::Normal, + ), + ( + PropertyDeclaration::OverflowX(OverflowValue::Auto), + Importance::Normal, + ), + ( + PropertyDeclaration::OverflowY(OverflowValue::Auto), + Importance::Normal, + ), ]; let block = block_from(declarations); @@ -147,62 +155,65 @@ mod shorthand_serialization { #[test] fn different_longhands_should_serialize_to_long_form() { - let mut properties = Vec::new(); + let mut properties = Vec::new(); - let solid = BorderStyle::Solid; + let solid = BorderStyle::Solid; - properties.push(PropertyDeclaration::BorderTopStyle(solid.clone())); - properties.push(PropertyDeclaration::BorderRightStyle(solid.clone())); - properties.push(PropertyDeclaration::BorderBottomStyle(solid.clone())); - properties.push(PropertyDeclaration::BorderLeftStyle(solid.clone())); + properties.push(PropertyDeclaration::BorderTopStyle(solid.clone())); + properties.push(PropertyDeclaration::BorderRightStyle(solid.clone())); + properties.push(PropertyDeclaration::BorderBottomStyle(solid.clone())); + properties.push(PropertyDeclaration::BorderLeftStyle(solid.clone())); - let px_30 = BorderSideWidth::Length(Length::from_px(30f32)); - let px_10 = BorderSideWidth::Length(Length::from_px(10f32)); + let px_30 = BorderSideWidth::Length(Length::from_px(30f32)); + let px_10 = BorderSideWidth::Length(Length::from_px(10f32)); - properties.push(PropertyDeclaration::BorderTopWidth(px_30.clone())); - properties.push(PropertyDeclaration::BorderRightWidth(px_30.clone())); - properties.push(PropertyDeclaration::BorderBottomWidth(px_30.clone())); - properties.push(PropertyDeclaration::BorderLeftWidth(px_10.clone())); + properties.push(PropertyDeclaration::BorderTopWidth(px_30.clone())); + properties.push(PropertyDeclaration::BorderRightWidth(px_30.clone())); + properties.push(PropertyDeclaration::BorderBottomWidth(px_30.clone())); + properties.push(PropertyDeclaration::BorderLeftWidth(px_10.clone())); - let blue = Color::rgba(RGBA::new(0, 0, 255, 255)); + let blue = Color::rgba(RGBA::new(0, 0, 255, 255)); - properties.push(PropertyDeclaration::BorderTopColor(blue.clone())); - properties.push(PropertyDeclaration::BorderRightColor(blue.clone())); - properties.push(PropertyDeclaration::BorderBottomColor(blue.clone())); - properties.push(PropertyDeclaration::BorderLeftColor(blue.clone())); + properties.push(PropertyDeclaration::BorderTopColor(blue.clone())); + properties.push(PropertyDeclaration::BorderRightColor(blue.clone())); + properties.push(PropertyDeclaration::BorderBottomColor(blue.clone())); + properties.push(PropertyDeclaration::BorderLeftColor(blue.clone())); - let serialization = shorthand_properties_to_string(properties); - assert_eq!(serialization, + let serialization = shorthand_properties_to_string(properties); + assert_eq!(serialization, "border-style: solid; border-width: 30px 30px 30px 10px; border-color: rgb(0, 0, 255);"); } #[test] fn same_longhands_should_serialize_correctly() { - let mut properties = Vec::new(); + let mut properties = Vec::new(); - let solid = BorderStyle::Solid; + let solid = BorderStyle::Solid; - properties.push(PropertyDeclaration::BorderTopStyle(solid.clone())); - properties.push(PropertyDeclaration::BorderRightStyle(solid.clone())); - properties.push(PropertyDeclaration::BorderBottomStyle(solid.clone())); - properties.push(PropertyDeclaration::BorderLeftStyle(solid.clone())); + properties.push(PropertyDeclaration::BorderTopStyle(solid.clone())); + properties.push(PropertyDeclaration::BorderRightStyle(solid.clone())); + properties.push(PropertyDeclaration::BorderBottomStyle(solid.clone())); + properties.push(PropertyDeclaration::BorderLeftStyle(solid.clone())); - let px_30 = BorderSideWidth::Length(Length::from_px(30f32)); + let px_30 = BorderSideWidth::Length(Length::from_px(30f32)); - properties.push(PropertyDeclaration::BorderTopWidth(px_30.clone())); - properties.push(PropertyDeclaration::BorderRightWidth(px_30.clone())); - properties.push(PropertyDeclaration::BorderBottomWidth(px_30.clone())); - properties.push(PropertyDeclaration::BorderLeftWidth(px_30.clone())); + properties.push(PropertyDeclaration::BorderTopWidth(px_30.clone())); + properties.push(PropertyDeclaration::BorderRightWidth(px_30.clone())); + properties.push(PropertyDeclaration::BorderBottomWidth(px_30.clone())); + properties.push(PropertyDeclaration::BorderLeftWidth(px_30.clone())); - let blue = Color::rgba(RGBA::new(0, 0, 255, 255)); + let blue = Color::rgba(RGBA::new(0, 0, 255, 255)); - properties.push(PropertyDeclaration::BorderTopColor(blue.clone())); - properties.push(PropertyDeclaration::BorderRightColor(blue.clone())); - properties.push(PropertyDeclaration::BorderBottomColor(blue.clone())); - properties.push(PropertyDeclaration::BorderLeftColor(blue.clone())); + properties.push(PropertyDeclaration::BorderTopColor(blue.clone())); + properties.push(PropertyDeclaration::BorderRightColor(blue.clone())); + properties.push(PropertyDeclaration::BorderBottomColor(blue.clone())); + properties.push(PropertyDeclaration::BorderLeftColor(blue.clone())); - let serialization = shorthand_properties_to_string(properties); - assert_eq!(serialization, "border-style: solid; border-width: 30px; border-color: rgb(0, 0, 255);"); + let serialization = shorthand_properties_to_string(properties); + assert_eq!( + serialization, + "border-style: solid; border-width: 30px; border-color: rgb(0, 0, 255);" + ); } #[test] @@ -274,7 +285,10 @@ mod shorthand_serialization { let serialization = shorthand_properties_to_string(properties); // TODO: Make the rgb test show border-color as blue red instead of below tuples - assert_eq!(serialization, "border-color: rgb(0, 0, 255) rgb(255, 0, 0);"); + assert_eq!( + serialization, + "border-color: rgb(0, 0, 255) rgb(255, 0, 0);" + ); } #[test] @@ -297,41 +311,42 @@ mod shorthand_serialization { #[test] fn border_radius_should_serialize_correctly() { let mut properties = Vec::new(); - properties.push(PropertyDeclaration::BorderTopLeftRadius(Box::new(BorderCornerRadius::new( - Percentage::new(0.01).into(), Percentage::new(0.05).into() - )))); - properties.push(PropertyDeclaration::BorderTopRightRadius(Box::new(BorderCornerRadius::new( - Percentage::new(0.02).into(), Percentage::new(0.06).into() - )))); - properties.push(PropertyDeclaration::BorderBottomRightRadius(Box::new(BorderCornerRadius::new( - Percentage::new(0.03).into(), Percentage::new(0.07).into() - )))); - properties.push(PropertyDeclaration::BorderBottomLeftRadius(Box::new(BorderCornerRadius::new( - Percentage::new(0.04).into(), Percentage::new(0.08).into() - )))); + properties.push(PropertyDeclaration::BorderTopLeftRadius(Box::new( + BorderCornerRadius::new(Percentage::new(0.01).into(), Percentage::new(0.05).into()), + ))); + properties.push(PropertyDeclaration::BorderTopRightRadius(Box::new( + BorderCornerRadius::new(Percentage::new(0.02).into(), Percentage::new(0.06).into()), + ))); + properties.push(PropertyDeclaration::BorderBottomRightRadius(Box::new( + BorderCornerRadius::new(Percentage::new(0.03).into(), Percentage::new(0.07).into()), + ))); + properties.push(PropertyDeclaration::BorderBottomLeftRadius(Box::new( + BorderCornerRadius::new(Percentage::new(0.04).into(), Percentage::new(0.08).into()), + ))); let serialization = shorthand_properties_to_string(properties); assert_eq!(serialization, "border-radius: 1% 2% 3% 4% / 5% 6% 7% 8%;"); } } - mod border_shorthands { use super::*; #[test] fn border_top_and_color() { let mut properties = Vec::new(); - properties.push(PropertyDeclaration::BorderTopWidth(BorderSideWidth::Length(Length::from_px(1.)))); + properties.push(PropertyDeclaration::BorderTopWidth( + BorderSideWidth::Length(Length::from_px(1.)), + )); properties.push(PropertyDeclaration::BorderTopStyle(BorderStyle::Solid)); let c = Color::Numeric { parsed: RGBA::new(255, 0, 0, 255), - authored: Some("green".to_string().into_boxed_str()) + authored: Some("green".to_string().into_boxed_str()), }; properties.push(PropertyDeclaration::BorderTopColor(c)); let c = Color::Numeric { parsed: RGBA::new(0, 255, 0, 255), - authored: Some("red".to_string().into_boxed_str()) + authored: Some("red".to_string().into_boxed_str()), }; properties.push(PropertyDeclaration::BorderTopColor(c.clone())); properties.push(PropertyDeclaration::BorderBottomColor(c.clone())); @@ -339,31 +354,39 @@ mod shorthand_serialization { properties.push(PropertyDeclaration::BorderRightColor(c.clone())); let serialization = shorthand_properties_to_string(properties); - assert_eq!(serialization, "border-top: 1px solid red; border-color: red;"); + assert_eq!( + serialization, + "border-top: 1px solid red; border-color: red;" + ); } #[test] fn border_color_and_top() { let mut properties = Vec::new(); - let c = Color::Numeric { + let c = Color::Numeric { parsed: RGBA::new(0, 255, 0, 255), - authored: Some("red".to_string().into_boxed_str()) + authored: Some("red".to_string().into_boxed_str()), }; properties.push(PropertyDeclaration::BorderTopColor(c.clone())); properties.push(PropertyDeclaration::BorderBottomColor(c.clone())); properties.push(PropertyDeclaration::BorderLeftColor(c.clone())); properties.push(PropertyDeclaration::BorderRightColor(c.clone())); - properties.push(PropertyDeclaration::BorderTopWidth(BorderSideWidth::Length(Length::from_px(1.)))); + properties.push(PropertyDeclaration::BorderTopWidth( + BorderSideWidth::Length(Length::from_px(1.)), + )); properties.push(PropertyDeclaration::BorderTopStyle(BorderStyle::Solid)); let c = Color::Numeric { parsed: RGBA::new(255, 0, 0, 255), - authored: Some("green".to_string().into_boxed_str()) + authored: Some("green".to_string().into_boxed_str()), }; properties.push(PropertyDeclaration::BorderTopColor(c)); let serialization = shorthand_properties_to_string(properties); - assert_eq!(serialization, "border-color: green red red; border-top: 1px solid green;"); + assert_eq!( + serialization, + "border-color: green red red; border-top: 1px solid green;" + ); } // we can use border-top as a base to test out the different combinations @@ -386,9 +409,11 @@ mod shorthand_serialization { } fn get_border_property_values() -> (BorderSideWidth, BorderStyle, Color) { - (BorderSideWidth::Length(Length::from_px(4f32)), - BorderStyle::Solid, - Color::currentcolor()) + ( + BorderSideWidth::Length(Length::from_px(4f32)), + BorderStyle::Solid, + Color::currentcolor(), + ) } #[test] @@ -445,13 +470,14 @@ mod shorthand_serialization { // the ‘border’ shorthand resets ‘border-image’ to its initial value. To verify the // serialization of 'border' shorthand, we need to set 'border-image' as well. let block_text = "\ - border-top: 4px solid; \ - border-right: 4px solid; \ - border-bottom: 4px solid; \ - border-left: 4px solid; \ - border-image: none;"; + border-top: 4px solid; \ + border-right: 4px solid; \ + border-bottom: 4px solid; \ + border-left: 4px solid; \ + border-image: none;"; - let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); + let block = + parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); let serialization = block.to_css_string(); @@ -483,7 +509,10 @@ mod shorthand_serialization { properties.push(PropertyDeclaration::ListStyleType(style_type)); let serialization = shorthand_properties_to_string(properties); - assert_eq!(serialization, "list-style: inside url(\"http://servo/test.png\") disc;"); + assert_eq!( + serialization, + "list-style: inside url(\"http://servo/test.png\") disc;" + ); } } @@ -493,65 +522,68 @@ mod shorthand_serialization { #[test] fn background_should_serialize_all_available_properties_when_specified() { let block_text = "\ - background-color: rgb(255, 0, 0); \ - background-image: url(\"http://servo/test.png\"); \ - background-repeat: repeat-x; \ - background-attachment: scroll; \ - background-size: 70px 50px; \ - background-position-x: 7px; \ - background-position-y: bottom 4px; \ - background-origin: border-box; \ - background-clip: padding-box;"; - - let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); + background-color: rgb(255, 0, 0); \ + background-image: url(\"http://servo/test.png\"); \ + background-repeat: repeat-x; \ + background-attachment: scroll; \ + background-size: 70px 50px; \ + background-position-x: 7px; \ + background-position-y: bottom 4px; \ + background-origin: border-box; \ + background-clip: padding-box;"; + + let block = + parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); let serialization = block.to_css_string(); assert_eq!( serialization, "background: rgb(255, 0, 0) url(\"http://servo/test.png\") repeat-x \ - scroll left 7px bottom 4px / 70px 50px border-box padding-box;" + scroll left 7px bottom 4px / 70px 50px border-box padding-box;" ); } #[test] fn background_should_combine_origin_and_clip_properties_when_equal() { let block_text = "\ - background-color: rgb(255, 0, 0); \ - background-image: url(\"http://servo/test.png\"); \ - background-repeat: repeat-x; \ - background-attachment: scroll; \ - background-size: 70px 50px; \ - background-position-x: 7px; \ - background-position-y: 4px; \ - background-origin: padding-box; \ - background-clip: padding-box;"; - - let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); + background-color: rgb(255, 0, 0); \ + background-image: url(\"http://servo/test.png\"); \ + background-repeat: repeat-x; \ + background-attachment: scroll; \ + background-size: 70px 50px; \ + background-position-x: 7px; \ + background-position-y: 4px; \ + background-origin: padding-box; \ + background-clip: padding-box;"; + + let block = + parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); let serialization = block.to_css_string(); assert_eq!( serialization, "background: rgb(255, 0, 0) url(\"http://servo/test.png\") repeat-x \ - scroll 7px 4px / 70px 50px padding-box;" + scroll 7px 4px / 70px 50px padding-box;" ); } #[test] fn serialize_multiple_backgrounds() { let block_text = "\ - background-color: rgb(0, 0, 255); \ - background-image: url(\"http://servo/test.png\"), none; \ - background-repeat: repeat-x, repeat-y; \ - background-attachment: scroll, scroll; \ - background-size: 70px 50px, 20px 30px; \ - background-position-x: 7px, 70px; \ - background-position-y: 4px, 40px; \ - background-origin: border-box, padding-box; \ - background-clip: padding-box, padding-box;"; - - let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); + background-color: rgb(0, 0, 255); \ + background-image: url(\"http://servo/test.png\"), none; \ + background-repeat: repeat-x, repeat-y; \ + background-attachment: scroll, scroll; \ + background-size: 70px 50px, 20px 30px; \ + background-position-x: 7px, 70px; \ + background-position-y: 4px, 40px; \ + background-origin: border-box, padding-box; \ + background-clip: padding-box, padding-box;"; + + let block = + parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); let serialization = block.to_css_string(); @@ -573,16 +605,17 @@ mod shorthand_serialization { // multiple backgrounds. // Below background-origin only has one value. let block_text = "\ - background-color: rgb(0, 0, 255); \ - background-image: url(\"http://servo/test.png\"), none; \ - background-repeat: repeat-x, repeat-y; \ - background-attachment: scroll, scroll; \ - background-size: 70px 50px, 20px 30px; \ - background-position: 7px 4px, 5px 6px; \ - background-origin: border-box; \ - background-clip: padding-box, padding-box;"; - - let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); + background-color: rgb(0, 0, 255); \ + background-image: url(\"http://servo/test.png\"), none; \ + background-repeat: repeat-x, repeat-y; \ + background-attachment: scroll, scroll; \ + background-size: 70px 50px, 20px 30px; \ + background-position: 7px 4px, 5px 6px; \ + background-origin: border-box; \ + background-clip: padding-box, padding-box;"; + + let block = + parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); let serialization = block.to_css_string(); @@ -594,18 +627,20 @@ mod shorthand_serialization { // If there is any longhand consisted of both keyword and position, // the shorthand result should be the 4-value format. let block_text = "\ - background-position-x: 30px;\ - background-position-y: bottom 20px;"; - let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); + background-position-x: 30px;\ + background-position-y: bottom 20px;"; + let block = + parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); let serialization = block.to_css_string(); assert_eq!(serialization, "background-position: left 30px bottom 20px;"); // If there is no longhand consisted of both keyword and position, // the shorthand result should be the 2-value format. let block_text = "\ - background-position-x: center;\ - background-position-y: 20px;"; - let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); + background-position-x: center;\ + background-position-y: 20px;"; + let block = + parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); let serialization = block.to_css_string(); assert_eq!(serialization, "background-position: center 20px;"); } @@ -628,41 +663,48 @@ mod shorthand_serialization { #[test] fn serialize_single_animation() { let block_text = "\ - animation-name: bounce;\ - animation-duration: 1s;\ - animation-timing-function: ease-in;\ - animation-delay: 0s;\ - animation-direction: normal;\ - animation-fill-mode: forwards;\ - animation-iteration-count: infinite;\ - animation-play-state: paused;"; - - let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); + animation-name: bounce;\ + animation-duration: 1s;\ + animation-timing-function: ease-in;\ + animation-delay: 0s;\ + animation-direction: normal;\ + animation-fill-mode: forwards;\ + animation-iteration-count: infinite;\ + animation-play-state: paused;"; + + let block = + parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); let serialization = block.to_css_string(); - assert_eq!(serialization, "animation: 1s ease-in 0s infinite normal forwards paused bounce;") + assert_eq!( + serialization, + "animation: 1s ease-in 0s infinite normal forwards paused bounce;" + ) } #[test] fn serialize_multiple_animations() { let block_text = "\ - animation-name: bounce, roll;\ - animation-duration: 1s, 0.2s;\ - animation-timing-function: ease-in, linear;\ - animation-delay: 0s, 1s;\ - animation-direction: normal, reverse;\ - animation-fill-mode: forwards, backwards;\ - animation-iteration-count: infinite, 2;\ - animation-play-state: paused, running;"; + animation-name: bounce, roll;\ + animation-duration: 1s, 0.2s;\ + animation-timing-function: ease-in, linear;\ + animation-delay: 0s, 1s;\ + animation-direction: normal, reverse;\ + animation-fill-mode: forwards, backwards;\ + animation-iteration-count: infinite, 2;\ + animation-play-state: paused, running;"; - let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); + let block = + parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); let serialization = block.to_css_string(); - assert_eq!(serialization, - "animation: 1s ease-in 0s infinite normal forwards paused bounce, \ - 0.2s linear 1s 2 reverse backwards running roll;"); + assert_eq!( + serialization, + "animation: 1s ease-in 0s infinite normal forwards paused bounce, \ + 0.2s linear 1s 2 reverse backwards running roll;" + ); } #[test] @@ -673,16 +715,17 @@ mod shorthand_serialization { // lists have the same length (this affects background, transition and animation). // https://github.com/servo/servo/issues/15398 ) let block_text = "\ - animation-name: bounce, roll, flip, jump; \ - animation-duration: 1s, 0.2s; \ - animation-timing-function: ease-in, linear; \ - animation-delay: 0s, 1s, 0.5s; \ - animation-direction: normal; \ - animation-fill-mode: forwards, backwards; \ - animation-iteration-count: infinite, 2; \ - animation-play-state: paused, running;"; + animation-name: bounce, roll, flip, jump; \ + animation-duration: 1s, 0.2s; \ + animation-timing-function: ease-in, linear; \ + animation-delay: 0s, 1s, 0.5s; \ + animation-direction: normal; \ + animation-fill-mode: forwards, backwards; \ + animation-iteration-count: infinite, 2; \ + animation-play-state: paused, running;"; - let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); + let block = + parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); let serialization = block.to_css_string(); @@ -699,7 +742,8 @@ mod shorthand_serialization { animation-iteration-count: infinite, 2; \ animation-play-state: paused, running;"; - let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); + let block = + parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); let serialization = block.to_css_string(); @@ -712,7 +756,8 @@ mod shorthand_serialization { #[test] fn css_wide_keywords_should_be_parsed() { let block_text = "--a:inherit;"; - let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); + let block = + parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); let serialization = block.to_css_string(); assert_eq!(serialization, "--a: inherit;"); @@ -721,7 +766,8 @@ mod shorthand_serialization { #[test] fn non_keyword_custom_property_should_be_unparsed() { let block_text = "--main-color: #06c;"; - let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); + let block = + parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap(); let serialization = block.to_css_string(); assert_eq!(serialization, block_text); @@ -751,7 +797,8 @@ mod shorthand_serialization { let shadow_decl = BoxShadowList(vec![shadow_val]); properties.push(PropertyDeclaration::BoxShadow(shadow_decl)); let shadow_css = "box-shadow: 1px 2px 3px 4px;"; - let shadow = parse(|c, i| Ok(parse_property_declaration_list(c, i)), shadow_css).unwrap(); + let shadow = + parse(|c, i| Ok(parse_property_declaration_list(c, i)), shadow_css).unwrap(); assert_eq!(shadow.to_css_string(), shadow_css); } diff --git a/tests/unit/style/rule_tree/bench.rs b/tests/unit/style/rule_tree/bench.rs index c1ea58f5248..4172431356e 100644 --- a/tests/unit/style/rule_tree/bench.rs +++ b/tests/unit/style/rule_tree/bench.rs @@ -18,11 +18,14 @@ use test::{self, Bencher}; struct ErrorringErrorReporter; impl ParseErrorReporter for ErrorringErrorReporter { - fn report_error(&self, - url: &ServoUrl, - location: SourceLocation, - error: ContextualParseError) { - panic!("CSS error: {}\t\n{}:{} {}", url.as_str(), location.line, location.column, error); + fn report_error(&self, url: &ServoUrl, location: SourceLocation, error: ContextualParseError) { + panic!( + "CSS error: {}\t\n{}:{} {}", + url.as_str(), + location.line, + location.column, + error + ); } } @@ -38,9 +41,10 @@ impl<'a> Drop for AutoGCRuleTree<'a> { fn drop(&mut self) { unsafe { self.0.gc(); - assert!(::std::thread::panicking() || - !self.0.root().has_children_for_testing(), - "No rule nodes other than the root shall remain!"); + assert!( + ::std::thread::panicking() || !self.0.root().has_children_for_testing(), + "No rule nodes other than the root shall remain!" + ); } } } @@ -49,41 +53,51 @@ fn parse_rules(css: &str) -> Vec<(StyleSource, CascadeLevel)> { let lock = SharedRwLock::new(); let media = Arc::new(lock.wrap(MediaList::empty())); - let s = Stylesheet::from_str(css, - ServoUrl::parse("http://localhost").unwrap(), - Origin::Author, - media, - lock, - None, - Some(&ErrorringErrorReporter), - QuirksMode::NoQuirks, - 0); + let s = Stylesheet::from_str( + css, + ServoUrl::parse("http://localhost").unwrap(), + Origin::Author, + media, + lock, + None, + Some(&ErrorringErrorReporter), + QuirksMode::NoQuirks, + 0, + ); let guard = s.shared_lock.read(); let rules = s.contents.rules.read_with(&guard); - rules.0.iter().filter_map(|rule| { - match *rule { + rules + .0 + .iter() + .filter_map(|rule| match *rule { CssRule::Style(ref style_rule) => Some(( StyleSource::from_rule(style_rule.clone()), CascadeLevel::UserNormal, )), _ => None, - } - }).collect() + }) + .collect() } fn test_insertion(rule_tree: &RuleTree, rules: Vec<(StyleSource, CascadeLevel)>) -> StrongRuleNode { rule_tree.insert_ordered_rules(rules.into_iter()) } -fn test_insertion_style_attribute(rule_tree: &RuleTree, rules: &[(StyleSource, CascadeLevel)], - shared_lock: &SharedRwLock) - -> StrongRuleNode { +fn test_insertion_style_attribute( + rule_tree: &RuleTree, + rules: &[(StyleSource, CascadeLevel)], + shared_lock: &SharedRwLock, +) -> StrongRuleNode { let mut rules = rules.to_vec(); - rules.push((StyleSource::from_declarations(Arc::new(shared_lock.wrap(PropertyDeclarationBlock::with_one( - PropertyDeclaration::Display( - longhands::display::SpecifiedValue::Block), - Importance::Normal - )))), CascadeLevel::UserNormal)); + rules.push(( + StyleSource::from_declarations(Arc::new(shared_lock.wrap( + PropertyDeclarationBlock::with_one( + PropertyDeclaration::Display(longhands::display::SpecifiedValue::Block), + Importance::Normal, + ), + ))), + CascadeLevel::UserNormal, + )); test_insertion(rule_tree, rules) } @@ -95,7 +109,8 @@ fn bench_insertion_basic(b: &mut Bencher) { let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ - .baz { display: block; }"); + .baz { display: block; }", + ); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); @@ -114,7 +129,8 @@ fn bench_insertion_basic_per_element(b: &mut Bencher) { let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ - .baz { display: block; }"); + .baz { display: block; }", + ); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); @@ -134,14 +150,19 @@ fn bench_expensive_insertion(b: &mut Bencher) { let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ - .baz { display: block; }"); + .baz { display: block; }", + ); let shared_lock = SharedRwLock::new(); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); for _ in 0..(4000 + 400) { - test::black_box(test_insertion_style_attribute(&r, &rules_matched, &shared_lock)); + test::black_box(test_insertion_style_attribute( + &r, + &rules_matched, + &shared_lock, + )); } }); } @@ -154,7 +175,8 @@ fn bench_insertion_basic_parallel(b: &mut Bencher) { let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ - .baz { display: block; }"); + .baz { display: block; }", + ); b.iter(|| { let _gc = AutoGCRuleTree::new(&r); @@ -163,13 +185,11 @@ fn bench_insertion_basic_parallel(b: &mut Bencher) { for _ in 0..4 { s.spawn(|s| { for _ in 0..1000 { - test::black_box(test_insertion(&r, - rules_matched.clone())); + test::black_box(test_insertion(&r, rules_matched.clone())); } s.spawn(|_| { for _ in 0..100 { - test::black_box(test_insertion(&r, - rules_matched.clone())); + test::black_box(test_insertion(&r, rules_matched.clone())); } }) }) @@ -186,7 +206,8 @@ fn bench_expensive_insertion_parallel(b: &mut Bencher) { let rules_matched = parse_rules( ".foo { width: 200px; } \ .bar { height: 500px; } \ - .baz { display: block; }"); + .baz { display: block; }", + ); let shared_lock = SharedRwLock::new(); b.iter(|| { @@ -196,15 +217,19 @@ fn bench_expensive_insertion_parallel(b: &mut Bencher) { for _ in 0..4 { s.spawn(|s| { for _ in 0..1000 { - test::black_box(test_insertion_style_attribute(&r, - &rules_matched, - &shared_lock)); + test::black_box(test_insertion_style_attribute( + &r, + &rules_matched, + &shared_lock, + )); } s.spawn(|_| { for _ in 0..100 { - test::black_box(test_insertion_style_attribute(&r, - &rules_matched, - &shared_lock)); + test::black_box(test_insertion_style_attribute( + &r, + &rules_matched, + &shared_lock, + )); } }) }) diff --git a/tests/unit/style/size_of.rs b/tests/unit/style/size_of.rs index 1078074fa58..60c0b1c75e4 100644 --- a/tests/unit/style/size_of.rs +++ b/tests/unit/style/size_of.rs @@ -8,16 +8,44 @@ use style::properties; size_of_test!(test_size_of_dependency, Dependency, 16); -size_of_test!(test_size_of_property_declaration, properties::PropertyDeclaration, 32); +size_of_test!( + test_size_of_property_declaration, + properties::PropertyDeclaration, + 32 +); // This is huge, but we allocate it on the stack and then never move it, // we only pass `&mut SourcePropertyDeclaration` references around. -size_of_test!(test_size_of_parsed_declaration, properties::SourcePropertyDeclaration, 568); +size_of_test!( + test_size_of_parsed_declaration, + properties::SourcePropertyDeclaration, + 568 +); -size_of_test!(test_size_of_selector_parse_error_kind, SelectorParseErrorKind, 40); -size_of_test!(test_size_of_style_parse_error_kind, ::style_traits::StyleParseErrorKind, 56); -size_of_test!(test_size_of_value_parse_error_kind, ::style_traits::ValueParseErrorKind, 40); +size_of_test!( + test_size_of_selector_parse_error_kind, + SelectorParseErrorKind, + 40 +); +size_of_test!( + test_size_of_style_parse_error_kind, + ::style_traits::StyleParseErrorKind, + 56 +); +size_of_test!( + test_size_of_value_parse_error_kind, + ::style_traits::ValueParseErrorKind, + 40 +); size_of_test!(test_size_of_selector_parse_error, SelectorParseError, 56); -size_of_test!(test_size_of_style_traits_parse_error, ::style_traits::ParseError, 72); -size_of_test!(test_size_of_value_parse_error, ::style_traits::ValueParseError, 56); +size_of_test!( + test_size_of_style_traits_parse_error, + ::style_traits::ParseError, + 72 +); +size_of_test!( + test_size_of_value_parse_error, + ::style_traits::ValueParseError, + 56 +); diff --git a/tests/unit/style/str.rs b/tests/unit/style/str.rs index 154cf894158..78a870dced0 100644 --- a/tests/unit/style/str.rs +++ b/tests/unit/style/str.rs @@ -7,7 +7,11 @@ use style::str::{split_html_space_chars, str_join, starts_with_ignore_ascii_case #[test] pub fn split_html_space_chars_whitespace() { assert!(split_html_space_chars("").collect::<Vec<_>>().is_empty()); - assert!(split_html_space_chars("\u{0020}\u{0009}\u{000a}\u{000c}\u{000d}").collect::<Vec<_>>().is_empty()); + assert!( + split_html_space_chars("\u{0020}\u{0009}\u{000a}\u{000c}\u{000d}") + .collect::<Vec<_>>() + .is_empty() + ); } #[test] diff --git a/tests/unit/style/stylesheets.rs b/tests/unit/style/stylesheets.rs index 17c6e493db6..74a2c18e94b 100644 --- a/tests/unit/style/stylesheets.rs +++ b/tests/unit/style/stylesheets.rs @@ -31,7 +31,9 @@ use style::values::specified::{LengthOrPercentageOrAuto, PositionComponent}; use style::values::specified::TimingFunction; pub fn block_from<I>(iterable: I) -> PropertyDeclarationBlock -where I: IntoIterator<Item=(PropertyDeclaration, Importance)> { +where + I: IntoIterator<Item = (PropertyDeclaration, Importance)>, +{ let mut block = PropertyDeclarationBlock::new(); for (d, i) in iterable { block.push(d, i); @@ -69,8 +71,17 @@ fn test_parse_stylesheet() { let url = ServoUrl::parse("about::test").unwrap(); let lock = SharedRwLock::new(); let media = Arc::new(lock.wrap(MediaList::empty())); - let stylesheet = Stylesheet::from_str(css, url.clone(), Origin::UserAgent, media, lock, - None, None, QuirksMode::NoQuirks, 0); + let stylesheet = Stylesheet::from_str( + css, + url.clone(), + Origin::UserAgent, + media, + lock, + None, + None, + QuirksMode::NoQuirks, + 0, + ); let mut namespaces = Namespaces::default(); namespaces.default = Some(ns!(html)); let expected = Stylesheet { @@ -79,180 +90,245 @@ fn test_parse_stylesheet() { namespaces: RwLock::new(namespaces), url_data: RwLock::new(url), quirks_mode: QuirksMode::NoQuirks, - rules: CssRules::new(vec![ - CssRule::Namespace(Arc::new(stylesheet.shared_lock.wrap(NamespaceRule { - prefix: None, - url: NsAtom::from("http://www.w3.org/1999/xhtml"), - source_location: SourceLocation { - line: 1, - column: 19, - }, - }))), - CssRule::Style(Arc::new(stylesheet.shared_lock.wrap(StyleRule { - selectors: SelectorList::from_vec(vec!( - Selector::from_vec(vec!( - Component::DefaultNamespace(NsAtom::from("http://www.w3.org/1999/xhtml")), - Component::LocalName(LocalName { - name: local_name!("input"), - lower_name: local_name!("input"), - }), - Component::AttributeInNoNamespace { - local_name: local_name!("type"), - operator: AttrSelectorOperator::Equal, - value: "hidden".to_owned(), - case_sensitivity: ParsedCaseSensitivity::AsciiCaseInsensitive, - never_matches: false, - } - ), (0 << 20) + (1 << 10) + (1 << 0)) - )), - block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![ - ( - PropertyDeclaration::Display(longhands::display::SpecifiedValue::None), - Importance::Important, - ), - ( - PropertyDeclaration::Custom(CustomDeclaration { - name: Atom::from("a"), - value: CustomDeclarationValue::CSSWideKeyword(CSSWideKeyword::Inherit), - }), - Importance::Important, - ), - ]))), - source_location: SourceLocation { - line: 3, - column: 9, - }, - }))), - CssRule::Style(Arc::new(stylesheet.shared_lock.wrap(StyleRule { - selectors: SelectorList::from_vec(vec!( - Selector::from_vec(vec!( - Component::DefaultNamespace(NsAtom::from("http://www.w3.org/1999/xhtml")), + rules: CssRules::new( + vec![ + CssRule::Namespace(Arc::new(stylesheet.shared_lock.wrap(NamespaceRule { + prefix: None, + url: NsAtom::from("http://www.w3.org/1999/xhtml"), + source_location: SourceLocation { + line: 1, + column: 19, + }, + }))), + CssRule::Style(Arc::new(stylesheet.shared_lock.wrap(StyleRule { + selectors: SelectorList::from_vec(vec![Selector::from_vec( + vec![ + Component::DefaultNamespace(NsAtom::from( + "http://www.w3.org/1999/xhtml", + )), Component::LocalName(LocalName { - name: local_name!("html"), - lower_name: local_name!("html"), + name: local_name!("input"), + lower_name: local_name!("input"), }), - ), (0 << 20) + (0 << 10) + (1 << 0)), - Selector::from_vec(vec!( - Component::DefaultNamespace(NsAtom::from("http://www.w3.org/1999/xhtml")), - Component::LocalName(LocalName { - name: local_name!("body"), - lower_name: local_name!("body"), - }) - ), (0 << 20) + (0 << 10) + (1 << 0) - ), - )), - block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![ - (PropertyDeclaration::Display(longhands::display::SpecifiedValue::Block), - Importance::Normal), - ]))), - source_location: SourceLocation { - line: 11, - column: 9, - }, - }))), - CssRule::Style(Arc::new(stylesheet.shared_lock.wrap(StyleRule { - selectors: SelectorList::from_vec(vec!( - Selector::from_vec(vec!( - Component::DefaultNamespace(NsAtom::from("http://www.w3.org/1999/xhtml")), - Component::ID(Atom::from("d1")), - Component::Combinator(Combinator::Child), - Component::DefaultNamespace(NsAtom::from("http://www.w3.org/1999/xhtml")), - Component::Class(Atom::from("ok")) - ), (1 << 20) + (1 << 10) + (0 << 0)) - )), - block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![ - (PropertyDeclaration::BackgroundColor( - longhands::background_color::SpecifiedValue::Numeric { - authored: Some("blue".to_owned().into_boxed_str()), - parsed: cssparser::RGBA::new(0, 0, 255, 255), - } - ), - Importance::Normal), - (PropertyDeclaration::BackgroundPositionX( - longhands::background_position_x::SpecifiedValue( - vec![PositionComponent::zero()])), - Importance::Normal), - (PropertyDeclaration::BackgroundPositionY( - longhands::background_position_y::SpecifiedValue( - vec![PositionComponent::zero()])), - Importance::Normal), - (PropertyDeclaration::BackgroundRepeat( - longhands::background_repeat::SpecifiedValue( - vec![longhands::background_repeat::single_value - ::get_initial_specified_value()])), - Importance::Normal), - (PropertyDeclaration::BackgroundAttachment( - longhands::background_attachment::SpecifiedValue( - vec![longhands::background_attachment::single_value - ::get_initial_specified_value()])), - Importance::Normal), - (PropertyDeclaration::BackgroundImage( - longhands::background_image::SpecifiedValue( - vec![longhands::background_image::single_value - ::get_initial_specified_value()])), - Importance::Normal), - (PropertyDeclaration::BackgroundSize( - longhands::background_size::SpecifiedValue( - vec![longhands::background_size::single_value - ::get_initial_specified_value()])), - Importance::Normal), - (PropertyDeclaration::BackgroundOrigin( - longhands::background_origin::SpecifiedValue( - vec![longhands::background_origin::single_value - ::get_initial_specified_value()])), - Importance::Normal), - (PropertyDeclaration::BackgroundClip( - longhands::background_clip::SpecifiedValue( - vec![longhands::background_clip::single_value - ::get_initial_specified_value()])), - Importance::Normal), - ]))), - source_location: SourceLocation { - line: 15, - column: 9, - }, - }))), - CssRule::Keyframes(Arc::new(stylesheet.shared_lock.wrap(KeyframesRule { - name: KeyframesName::Ident(CustomIdent("foo".into())), - keyframes: vec![ - Arc::new(stylesheet.shared_lock.wrap(Keyframe { - selector: KeyframeSelector::new_for_unit_testing( - vec![KeyframePercentage::new(0.)]), - block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![ - (PropertyDeclaration::Width( - LengthOrPercentageOrAuto::Percentage(Percentage(0.))), - Importance::Normal), - ]))), - source_location: SourceLocation { - line: 17, - column: 13, - }, - })), - Arc::new(stylesheet.shared_lock.wrap(Keyframe { - selector: KeyframeSelector::new_for_unit_testing( - vec![KeyframePercentage::new(1.)]), - block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![ - (PropertyDeclaration::Width( - LengthOrPercentageOrAuto::Percentage(Percentage(1.))), - Importance::Normal), - (PropertyDeclaration::AnimationTimingFunction( - animation_timing_function::SpecifiedValue( - vec![TimingFunction::ease()])), - Importance::Normal), - ]))), - source_location: SourceLocation { - line: 18, - column: 13, - }, - })), - ], - vendor_prefix: None, - source_location: SourceLocation { - line: 16, - column: 19, - }, - }))) - ], &stylesheet.shared_lock), + Component::AttributeInNoNamespace { + local_name: local_name!("type"), + operator: AttrSelectorOperator::Equal, + value: "hidden".to_owned(), + case_sensitivity: ParsedCaseSensitivity::AsciiCaseInsensitive, + never_matches: false, + }, + ], + (0 << 20) + (1 << 10) + (1 << 0), + )]), + block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![ + ( + PropertyDeclaration::Display( + longhands::display::SpecifiedValue::None, + ), + Importance::Important, + ), + ( + PropertyDeclaration::Custom(CustomDeclaration { + name: Atom::from("a"), + value: CustomDeclarationValue::CSSWideKeyword( + CSSWideKeyword::Inherit, + ), + }), + Importance::Important, + ), + ]))), + source_location: SourceLocation { line: 3, column: 9 }, + }))), + CssRule::Style(Arc::new(stylesheet.shared_lock.wrap(StyleRule { + selectors: SelectorList::from_vec(vec![ + Selector::from_vec( + vec![ + Component::DefaultNamespace(NsAtom::from( + "http://www.w3.org/1999/xhtml", + )), + Component::LocalName(LocalName { + name: local_name!("html"), + lower_name: local_name!("html"), + }), + ], + (0 << 20) + (0 << 10) + (1 << 0), + ), + Selector::from_vec( + vec![ + Component::DefaultNamespace(NsAtom::from( + "http://www.w3.org/1999/xhtml", + )), + Component::LocalName(LocalName { + name: local_name!("body"), + lower_name: local_name!("body"), + }), + ], + (0 << 20) + (0 << 10) + (1 << 0), + ), + ]), + block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![( + PropertyDeclaration::Display(longhands::display::SpecifiedValue::Block), + Importance::Normal, + )]))), + source_location: SourceLocation { + line: 11, + column: 9, + }, + }))), + CssRule::Style(Arc::new(stylesheet.shared_lock.wrap(StyleRule { + selectors: SelectorList::from_vec(vec![Selector::from_vec( + vec![ + Component::DefaultNamespace(NsAtom::from( + "http://www.w3.org/1999/xhtml", + )), + Component::ID(Atom::from("d1")), + Component::Combinator(Combinator::Child), + Component::DefaultNamespace(NsAtom::from( + "http://www.w3.org/1999/xhtml", + )), + Component::Class(Atom::from("ok")), + ], + (1 << 20) + (1 << 10) + (0 << 0), + )]), + block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![ + ( + PropertyDeclaration::BackgroundColor( + longhands::background_color::SpecifiedValue::Numeric { + authored: Some("blue".to_owned().into_boxed_str()), + parsed: cssparser::RGBA::new(0, 0, 255, 255), + }, + ), + Importance::Normal, + ), + ( + PropertyDeclaration::BackgroundPositionX( + longhands::background_position_x::SpecifiedValue(vec![ + PositionComponent::zero(), + ]), + ), + Importance::Normal, + ), + ( + PropertyDeclaration::BackgroundPositionY( + longhands::background_position_y::SpecifiedValue(vec![ + PositionComponent::zero(), + ]), + ), + Importance::Normal, + ), + ( + PropertyDeclaration::BackgroundRepeat( + longhands::background_repeat::SpecifiedValue( + vec![longhands::background_repeat::single_value + ::get_initial_specified_value()], + ), + ), + Importance::Normal, + ), + ( + PropertyDeclaration::BackgroundAttachment( + longhands::background_attachment::SpecifiedValue( + vec![longhands::background_attachment::single_value + ::get_initial_specified_value()], + ), + ), + Importance::Normal, + ), + ( + PropertyDeclaration::BackgroundImage( + longhands::background_image::SpecifiedValue( + vec![longhands::background_image::single_value + ::get_initial_specified_value()], + ), + ), + Importance::Normal, + ), + ( + PropertyDeclaration::BackgroundSize( + longhands::background_size::SpecifiedValue( + vec![longhands::background_size::single_value + ::get_initial_specified_value()], + ), + ), + Importance::Normal, + ), + ( + PropertyDeclaration::BackgroundOrigin( + longhands::background_origin::SpecifiedValue( + vec![longhands::background_origin::single_value + ::get_initial_specified_value()], + ), + ), + Importance::Normal, + ), + ( + PropertyDeclaration::BackgroundClip( + longhands::background_clip::SpecifiedValue( + vec![longhands::background_clip::single_value + ::get_initial_specified_value()], + ), + ), + Importance::Normal, + ), + ]))), + source_location: SourceLocation { + line: 15, + column: 9, + }, + }))), + CssRule::Keyframes(Arc::new(stylesheet.shared_lock.wrap(KeyframesRule { + name: KeyframesName::Ident(CustomIdent("foo".into())), + keyframes: vec![ + Arc::new(stylesheet.shared_lock.wrap(Keyframe { + selector: KeyframeSelector::new_for_unit_testing(vec![ + KeyframePercentage::new(0.), + ]), + block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![( + PropertyDeclaration::Width( + LengthOrPercentageOrAuto::Percentage(Percentage(0.)), + ), + Importance::Normal, + )]))), + source_location: SourceLocation { + line: 17, + column: 13, + }, + })), + Arc::new(stylesheet.shared_lock.wrap(Keyframe { + selector: KeyframeSelector::new_for_unit_testing(vec![ + KeyframePercentage::new(1.), + ]), + block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![ + ( + PropertyDeclaration::Width( + LengthOrPercentageOrAuto::Percentage(Percentage(1.)), + ), + Importance::Normal, + ), + ( + PropertyDeclaration::AnimationTimingFunction( + animation_timing_function::SpecifiedValue(vec![ + TimingFunction::ease(), + ]), + ), + Importance::Normal, + ), + ]))), + source_location: SourceLocation { + line: 18, + column: 13, + }, + })), + ], + vendor_prefix: None, + source_location: SourceLocation { + line: 16, + column: 19, + }, + }))), + ], + &stylesheet.shared_lock, + ), source_map_url: RwLock::new(None), source_url: RwLock::new(None), }, @@ -266,10 +342,10 @@ fn test_parse_stylesheet() { #[derive(Debug)] struct CSSError { - pub url : ServoUrl, + pub url: ServoUrl, pub line: u32, pub column: u32, - pub message: String + pub message: String, } struct TestingErrorReporter { @@ -285,11 +361,21 @@ impl TestingErrorReporter { fn assert_messages_contain(&self, expected_errors: &[(u32, u32, &str)]) { let errors = self.errors.borrow(); - for (i, (error, &(line, column, message))) in errors.iter().zip(expected_errors).enumerate() { - assert_eq!((error.line, error.column), (line, column), - "line/column numbers of the {}th error: {:?}", i + 1, error.message); - assert!(error.message.contains(message), - "{:?} does not contain {:?}", error.message, message); + for (i, (error, &(line, column, message))) in errors.iter().zip(expected_errors).enumerate() + { + assert_eq!( + (error.line, error.column), + (line, column), + "line/column numbers of the {}th error: {:?}", + i + 1, + error.message + ); + assert!( + error.message.contains(message), + "{:?} does not contain {:?}", + error.message, + message + ); } if errors.len() < expected_errors.len() { panic!("Missing errors: {:#?}", &expected_errors[errors.len()..]); @@ -301,22 +387,16 @@ impl TestingErrorReporter { } impl ParseErrorReporter for TestingErrorReporter { - fn report_error(&self, - url: &ServoUrl, - location: SourceLocation, - error: ContextualParseError) { - self.errors.borrow_mut().push( - CSSError{ - url: url.clone(), - line: location.line, - column: location.column, - message: error.to_string(), - } - ) + fn report_error(&self, url: &ServoUrl, location: SourceLocation, error: ContextualParseError) { + self.errors.borrow_mut().push(CSSError { + url: url.clone(), + line: location.line, + column: location.column, + message: error.to_string(), + }) } } - #[test] fn test_report_error_stylesheet() { PREFS.set("layout.viewport.enabled", PrefValue::Boolean(true)); @@ -342,29 +422,50 @@ fn test_report_error_stylesheet() { let lock = SharedRwLock::new(); let media = Arc::new(lock.wrap(MediaList::empty())); - Stylesheet::from_str(css, url.clone(), Origin::UserAgent, media, lock, - None, Some(&error_reporter), QuirksMode::NoQuirks, 5); + Stylesheet::from_str( + css, + url.clone(), + Origin::UserAgent, + media, + lock, + None, + Some(&error_reporter), + QuirksMode::NoQuirks, + 5, + ); error_reporter.assert_messages_contain(&[ - (8, 18, "Unsupported property declaration: 'display: invalid;'"), - (9, 27, "Unsupported property declaration: 'background-image:"), // FIXME: column should be around 56 + ( + 8, + 18, + "Unsupported property declaration: 'display: invalid;'", + ), + ( + 9, + 27, + "Unsupported property declaration: 'background-image:", + ), // FIXME: column should be around 56 (10, 17, "Unsupported property declaration: 'invalid: true;'"), (12, 28, "Invalid media rule"), (13, 30, "Unsupported @font-face descriptor declaration"), - // When @counter-style is supported, this should be replaced with two errors (14, 19, "Invalid rule: '@counter-style "), - // When @font-feature-values is supported, this should be replaced with two errors (15, 25, "Invalid rule: '@font-feature-values "), - (16, 13, "Invalid rule: '@invalid'"), (17, 29, "Invalid rule: '@invalid'"), - (18, 34, "Invalid rule: '@supports "), (19, 26, "Invalid keyframe rule: 'from invalid '"), - (19, 52, "Unsupported keyframe property declaration: 'margin: 0 invalid 0;'"), - (20, 29, "Unsupported @viewport descriptor declaration: 'width: 320px invalid auto;'"), + ( + 19, + 52, + "Unsupported keyframe property declaration: 'margin: 0 invalid 0;'", + ), + ( + 20, + 29, + "Unsupported @viewport descriptor declaration: 'width: 320px invalid auto;'", + ), ]); assert_eq!(error_reporter.errors.borrow()[0].url, url); @@ -384,28 +485,50 @@ fn test_no_report_unrecognized_vendor_properties() { let lock = SharedRwLock::new(); let media = Arc::new(lock.wrap(MediaList::empty())); - Stylesheet::from_str(css, url, Origin::UserAgent, media, lock, - None, Some(&error_reporter), QuirksMode::NoQuirks, 0); + Stylesheet::from_str( + css, + url, + Origin::UserAgent, + media, + lock, + None, + Some(&error_reporter), + QuirksMode::NoQuirks, + 0, + ); - error_reporter.assert_messages_contain(&[ - (4, 31, "Unsupported property declaration: '-moz-background-color: red;'"), - ]); + error_reporter.assert_messages_contain(&[( + 4, + 31, + "Unsupported property declaration: '-moz-background-color: red;'", + )]); } #[test] fn test_source_map_url() { let tests = vec![ ("", None), - ("/*# sourceMappingURL=something */", Some("something".to_string())), + ( + "/*# sourceMappingURL=something */", + Some("something".to_string()), + ), ]; for test in tests { let url = ServoUrl::parse("about::test").unwrap(); let lock = SharedRwLock::new(); let media = Arc::new(lock.wrap(MediaList::empty())); - let stylesheet = Stylesheet::from_str(test.0, url.clone(), Origin::UserAgent, media, lock, - None, None, QuirksMode::NoQuirks, - 0); + let stylesheet = Stylesheet::from_str( + test.0, + url.clone(), + Origin::UserAgent, + media, + lock, + None, + None, + QuirksMode::NoQuirks, + 0, + ); let url_opt = stylesheet.contents.source_map_url.read(); assert_eq!(*url_opt, test.1); } @@ -422,9 +545,17 @@ fn test_source_url() { let url = ServoUrl::parse("about::test").unwrap(); let lock = SharedRwLock::new(); let media = Arc::new(lock.wrap(MediaList::empty())); - let stylesheet = Stylesheet::from_str(test.0, url.clone(), Origin::UserAgent, media, lock, - None, None, QuirksMode::NoQuirks, - 0); + let stylesheet = Stylesheet::from_str( + test.0, + url.clone(), + Origin::UserAgent, + media, + lock, + None, + None, + QuirksMode::NoQuirks, + 0, + ); let url_opt = stylesheet.contents.source_url.read(); assert_eq!(*url_opt, test.1); } diff --git a/tests/unit/style/stylist.rs b/tests/unit/style/stylist.rs index 01446cddcc1..80d017611b7 100644 --- a/tests/unit/style/stylist.rs +++ b/tests/unit/style/stylist.rs @@ -24,37 +24,55 @@ use style::thread_state::{self, ThreadState}; /// Each sublist of the result contains the Rules for one StyleRule. fn get_mock_rules(css_selectors: &[&str]) -> (Vec<Vec<Rule>>, SharedRwLock) { let shared_lock = SharedRwLock::new(); - (css_selectors.iter().enumerate().map(|(i, selectors)| { - let selectors = SelectorParser::parse_author_origin_no_namespace(selectors).unwrap(); - - let locked = Arc::new(shared_lock.wrap(StyleRule { - selectors: selectors, - block: Arc::new(shared_lock.wrap(PropertyDeclarationBlock::with_one( - PropertyDeclaration::Display( - longhands::display::SpecifiedValue::Block), - Importance::Normal - ))), - source_location: SourceLocation { - line: 0, - column: 0, - }, - })); - - let guard = shared_lock.read(); - let rule = locked.read_with(&guard); - rule.selectors.0.iter().map(|s| { - Rule::new(s.clone(), AncestorHashes::new(s, QuirksMode::NoQuirks), locked.clone(), i as u32) - }).collect() - }).collect(), shared_lock) + ( + css_selectors + .iter() + .enumerate() + .map(|(i, selectors)| { + let selectors = + SelectorParser::parse_author_origin_no_namespace(selectors).unwrap(); + + let locked = Arc::new(shared_lock.wrap(StyleRule { + selectors: selectors, + block: Arc::new(shared_lock.wrap(PropertyDeclarationBlock::with_one( + PropertyDeclaration::Display(longhands::display::SpecifiedValue::Block), + Importance::Normal, + ))), + source_location: SourceLocation { line: 0, column: 0 }, + })); + + let guard = shared_lock.read(); + let rule = locked.read_with(&guard); + rule.selectors + .0 + .iter() + .map(|s| { + Rule::new( + s.clone(), + AncestorHashes::new(s, QuirksMode::NoQuirks), + locked.clone(), + i as u32, + ) + }) + .collect() + }) + .collect(), + shared_lock, + ) } fn parse_selectors(selectors: &[&str]) -> Vec<Selector<SelectorImpl>> { - selectors.iter() - .map(|x| SelectorParser::parse_author_origin_no_namespace(x).unwrap().0 - .into_iter() - .nth(0) - .unwrap()) - .collect() + selectors + .iter() + .map(|x| { + SelectorParser::parse_author_origin_no_namespace(x) + .unwrap() + .0 + .into_iter() + .nth(0) + .unwrap() + }) + .collect() } #[test] @@ -65,14 +83,13 @@ fn test_revalidation_selectors() { "div:not(.foo)", "div span", "div > span", - // ID selectors. "#foo1", "#foo2::before", "#foo3 > span", "#foo1 > span", // FIXME(bz): This one should not be a - // revalidation selector, since #foo1 should be in the - // rule hash. + // revalidation selector, since #foo1 should be in the + // rule hash. // Attribute selectors. "div[foo]", @@ -84,7 +101,6 @@ fn test_revalidation_selectors() { "div[foo $= \"bar\"]", "div[foo *= \"bar\"]", "*|div[foo][bar = \"baz\"]", - // Non-state-based pseudo-classes. "div:empty", "div:first-child", @@ -97,7 +113,6 @@ fn test_revalidation_selectors() { "div:first-of-type", "div:last-of-type", "div:only-of-type", - // Note: it would be nice to test :moz-any and the various other non-TS // pseudo classes supported by gecko, but we don't have access to those // in these unit tests. :-( @@ -105,18 +120,17 @@ fn test_revalidation_selectors() { // Sibling combinators. "span + div", "span ~ div", - // Selectors in the ancestor chain (needed for cousin sharing). "p:first-child span", - ]).into_iter() - .filter(|s| needs_revalidation_for_testing(&s)) - .collect::<Vec<_>>(); + ]) + .into_iter() + .filter(|s| needs_revalidation_for_testing(&s)) + .collect::<Vec<_>>(); let reference = parse_selectors(&[ // ID selectors. "#foo3 > span", "#foo1 > span", - // Attribute selectors. "div[foo]", "div:not([foo])", @@ -127,7 +141,6 @@ fn test_revalidation_selectors() { "div[foo $= \"bar\"]", "div[foo *= \"bar\"]", "*|div[foo][bar = \"baz\"]", - // Non-state-based pseudo-classes. "div:empty", "div:first-child", @@ -140,15 +153,14 @@ fn test_revalidation_selectors() { "div:first-of-type", "div:last-of-type", "div:only-of-type", - // Sibling combinators. "span + div", "span ~ div", - // Selectors in the ancestor chain (needed for cousin sharing). "p:first-child span", - ]).into_iter() - .collect::<Vec<_>>(); + ]) + .into_iter() + .collect::<Vec<_>>(); assert_eq!(test.len(), reference.len()); for (t, r) in test.into_iter().zip(reference.into_iter()) { @@ -161,25 +173,52 @@ fn test_rule_ordering_same_specificity() { let (rules_list, _) = get_mock_rules(&["a.intro", "img.sidebar"]); let a = &rules_list[0][0]; let b = &rules_list[1][0]; - assert!((a.specificity(), a.source_order) < ((b.specificity(), b.source_order)), - "The rule that comes later should win."); + assert!( + (a.specificity(), a.source_order) < ((b.specificity(), b.source_order)), + "The rule that comes later should win." + ); } #[test] fn test_insert() { let (rules_list, _) = get_mock_rules(&[".intro.foo", "#top"]); let mut selector_map = SelectorMap::new(); - selector_map.insert(rules_list[1][0].clone(), QuirksMode::NoQuirks) - .expect("OOM"); - assert_eq!(1, selector_map.id_hash.get(&Atom::from("top"), QuirksMode::NoQuirks).unwrap()[0].source_order); - selector_map.insert(rules_list[0][0].clone(), QuirksMode::NoQuirks) - .expect("OOM"); - assert_eq!(0, selector_map.class_hash.get(&Atom::from("foo"), QuirksMode::NoQuirks).unwrap()[0].source_order); - assert!(selector_map.class_hash.get(&Atom::from("intro"), QuirksMode::NoQuirks).is_none()); + selector_map + .insert(rules_list[1][0].clone(), QuirksMode::NoQuirks) + .expect("OOM"); + assert_eq!( + 1, + selector_map + .id_hash + .get(&Atom::from("top"), QuirksMode::NoQuirks) + .unwrap()[0] + .source_order + ); + selector_map + .insert(rules_list[0][0].clone(), QuirksMode::NoQuirks) + .expect("OOM"); + assert_eq!( + 0, + selector_map + .class_hash + .get(&Atom::from("foo"), QuirksMode::NoQuirks) + .unwrap()[0] + .source_order + ); + assert!( + selector_map + .class_hash + .get(&Atom::from("intro"), QuirksMode::NoQuirks) + .is_none() + ); } fn mock_stylist() -> Stylist { - let device = Device::new(MediaType::screen(), TypedSize2D::new(0f32, 0f32), TypedScale::new(1.0)); + let device = Device::new( + MediaType::screen(), + TypedSize2D::new(0f32, 0f32), + TypedScale::new(1.0), + ); Stylist::new(device, QuirksMode::NoQuirks) } diff --git a/tests/unit/style/viewport.rs b/tests/unit/style/viewport.rs index a8d01651c3d..2ad0c773c0a 100644 --- a/tests/unit/style/viewport.rs +++ b/tests/unit/style/viewport.rs @@ -34,15 +34,14 @@ macro_rules! stylesheet { None, None, QuirksMode::NoQuirks, - 0 + 0, )) - } + }; } -fn test_viewport_rule<F>(css: &str, - device: &Device, - callback: F) - where F: Fn(&Vec<ViewportDescriptorDeclaration>, &str) +fn test_viewport_rule<F>(css: &str, device: &Device, callback: F) +where + F: Fn(&Vec<ViewportDescriptorDeclaration>, &str), { PREFS.set("layout.viewport.enabled", PrefValue::Boolean(true)); let stylesheet = stylesheet!(css, Author); @@ -55,7 +54,8 @@ fn test_viewport_rule<F>(css: &str, } fn test_meta_viewport<F>(meta: &str, callback: F) - where F: Fn(&Vec<ViewportDescriptorDeclaration>, &str) +where + F: Fn(&Vec<ViewportDescriptorDeclaration>, &str), { if let Some(mut rule) = ViewportRule::from_meta(meta) { // from_meta uses a hash-map to collect the declarations, so we need to @@ -74,29 +74,46 @@ fn test_meta_viewport<F>(meta: &str, callback: F) macro_rules! assert_decl_len { ($declarations:ident == 1) => { - assert_eq!($declarations.len(), 1, - "expected 1 declaration; have {}: {:?})", - $declarations.len(), $declarations) + assert_eq!( + $declarations.len(), + 1, + "expected 1 declaration; have {}: {:?})", + $declarations.len(), + $declarations + ) }; ($declarations:ident == $len:expr) => { - assert_eq!($declarations.len(), $len, - "expected {} declarations; have {}: {:?})", - $len, $declarations.len(), $declarations) - } + assert_eq!( + $declarations.len(), + $len, + "expected {} declarations; have {}: {:?})", + $len, + $declarations.len(), + $declarations + ) + }; } macro_rules! viewport_length { ($value:expr, px) => { - ViewportLength::Specified(LengthOrPercentageOrAuto::Length(NoCalcLength::from_px($value))) + ViewportLength::Specified(LengthOrPercentageOrAuto::Length(NoCalcLength::from_px( + $value, + ))) }; ($value:expr, vw) => { - ViewportLength::Specified(LengthOrPercentageOrAuto::Length(ViewportPercentage(Vw($value)))) - } + ViewportLength::Specified(LengthOrPercentageOrAuto::Length(ViewportPercentage(Vw( + $value, + )))) + }; } #[test] fn empty_viewport_rule() { - let device = Device::new(MediaType::screen(), TypedSize2D::new(800., 600.), TypedScale::new(1.0)); + let device = Device::new( + MediaType::screen(), + TypedSize2D::new(800., 600.), + TypedScale::new(1.0), + ); test_viewport_rule("@viewport {}", &device, |declarations, css| { println!("{}", css); @@ -119,35 +136,77 @@ macro_rules! assert_decl_eq { #[test] fn simple_viewport_rules() { - let device = Device::new(MediaType::screen(), TypedSize2D::new(800., 600.), TypedScale::new(1.0)); + let device = Device::new( + MediaType::screen(), + TypedSize2D::new(800., 600.), + TypedScale::new(1.0), + ); - test_viewport_rule("@viewport { width: auto; height: auto;\ - zoom: auto; min-zoom: 0; max-zoom: 200%;\ - user-zoom: zoom; orientation: auto; }", - &device, |declarations, css| { - println!("{}", css); - assert_decl_len!(declarations == 9); - assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::Specified(Auto)); - assert_decl_eq!(&declarations[1], Author, MaxWidth: ViewportLength::Specified(Auto)); - assert_decl_eq!(&declarations[2], Author, MinHeight: ViewportLength::Specified(Auto)); - assert_decl_eq!(&declarations[3], Author, MaxHeight: ViewportLength::Specified(Auto)); - assert_decl_eq!(&declarations[4], Author, Zoom: Zoom::Auto); - assert_decl_eq!(&declarations[5], Author, MinZoom: Zoom::Number(0.)); - assert_decl_eq!(&declarations[6], Author, MaxZoom: Zoom::Percentage(2.)); - assert_decl_eq!(&declarations[7], Author, UserZoom: UserZoom::Zoom); - assert_decl_eq!(&declarations[8], Author, Orientation: Orientation::Auto); - }); + test_viewport_rule( + "@viewport { width: auto; height: auto;\ + zoom: auto; min-zoom: 0; max-zoom: 200%;\ + user-zoom: zoom; orientation: auto; }", + &device, + |declarations, css| { + println!("{}", css); + assert_decl_len!(declarations == 9); + assert_decl_eq!( + &declarations[0], + Author, + MinWidth: ViewportLength::Specified(Auto) + ); + assert_decl_eq!( + &declarations[1], + Author, + MaxWidth: ViewportLength::Specified(Auto) + ); + assert_decl_eq!( + &declarations[2], + Author, + MinHeight: ViewportLength::Specified(Auto) + ); + assert_decl_eq!( + &declarations[3], + Author, + MaxHeight: ViewportLength::Specified(Auto) + ); + assert_decl_eq!(&declarations[4], Author, Zoom: Zoom::Auto); + assert_decl_eq!(&declarations[5], Author, MinZoom: Zoom::Number(0.)); + assert_decl_eq!(&declarations[6], Author, MaxZoom: Zoom::Percentage(2.)); + assert_decl_eq!(&declarations[7], Author, UserZoom: UserZoom::Zoom); + assert_decl_eq!(&declarations[8], Author, Orientation: Orientation::Auto); + }, + ); - test_viewport_rule("@viewport { min-width: 200px; max-width: auto;\ - min-height: 200px; max-height: auto; }", - &device, |declarations, css| { - println!("{}", css); - assert_decl_len!(declarations == 4); - assert_decl_eq!(&declarations[0], Author, MinWidth: viewport_length!(200., px)); - assert_decl_eq!(&declarations[1], Author, MaxWidth: ViewportLength::Specified(Auto)); - assert_decl_eq!(&declarations[2], Author, MinHeight: viewport_length!(200., px)); - assert_decl_eq!(&declarations[3], Author, MaxHeight: ViewportLength::Specified(Auto)); - }); + test_viewport_rule( + "@viewport { min-width: 200px; max-width: auto;\ + min-height: 200px; max-height: auto; }", + &device, + |declarations, css| { + println!("{}", css); + assert_decl_len!(declarations == 4); + assert_decl_eq!( + &declarations[0], + Author, + MinWidth: viewport_length!(200., px) + ); + assert_decl_eq!( + &declarations[1], + Author, + MaxWidth: ViewportLength::Specified(Auto) + ); + assert_decl_eq!( + &declarations[2], + Author, + MinHeight: viewport_length!(200., px) + ); + assert_decl_eq!( + &declarations[3], + Author, + MaxHeight: ViewportLength::Specified(Auto) + ); + }, + ); } #[test] @@ -155,129 +214,278 @@ fn simple_meta_viewport_contents() { test_meta_viewport("width=500, height=600", |declarations, meta| { println!("{}", meta); assert_decl_len!(declarations == 4); - assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::ExtendToZoom); - assert_decl_eq!(&declarations[1], Author, MaxWidth: viewport_length!(500., px)); - assert_decl_eq!(&declarations[2], Author, MinHeight: ViewportLength::ExtendToZoom); - assert_decl_eq!(&declarations[3], Author, MaxHeight: viewport_length!(600., px)); + assert_decl_eq!( + &declarations[0], + Author, + MinWidth: ViewportLength::ExtendToZoom + ); + assert_decl_eq!( + &declarations[1], + Author, + MaxWidth: viewport_length!(500., px) + ); + assert_decl_eq!( + &declarations[2], + Author, + MinHeight: ViewportLength::ExtendToZoom + ); + assert_decl_eq!( + &declarations[3], + Author, + MaxHeight: viewport_length!(600., px) + ); }); test_meta_viewport("initial-scale=1.0", |declarations, meta| { println!("{}", meta); assert_decl_len!(declarations == 3); - assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::ExtendToZoom); - assert_decl_eq!(&declarations[1], Author, MaxWidth: ViewportLength::ExtendToZoom); + assert_decl_eq!( + &declarations[0], + Author, + MinWidth: ViewportLength::ExtendToZoom + ); + assert_decl_eq!( + &declarations[1], + Author, + MaxWidth: ViewportLength::ExtendToZoom + ); assert_decl_eq!(&declarations[2], Author, Zoom: Zoom::Number(1.)); }); - test_meta_viewport("initial-scale=2.0, height=device-width", |declarations, meta| { - println!("{}", meta); - assert_decl_len!(declarations == 5); - assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::Specified(Auto)); - assert_decl_eq!(&declarations[1], Author, MaxWidth: ViewportLength::Specified(Auto)); - assert_decl_eq!(&declarations[2], Author, MinHeight: ViewportLength::ExtendToZoom); - assert_decl_eq!(&declarations[3], Author, MaxHeight: viewport_length!(100., vw)); - assert_decl_eq!(&declarations[4], Author, Zoom: Zoom::Number(2.)); - }); + test_meta_viewport( + "initial-scale=2.0, height=device-width", + |declarations, meta| { + println!("{}", meta); + assert_decl_len!(declarations == 5); + assert_decl_eq!( + &declarations[0], + Author, + MinWidth: ViewportLength::Specified(Auto) + ); + assert_decl_eq!( + &declarations[1], + Author, + MaxWidth: ViewportLength::Specified(Auto) + ); + assert_decl_eq!( + &declarations[2], + Author, + MinHeight: ViewportLength::ExtendToZoom + ); + assert_decl_eq!( + &declarations[3], + Author, + MaxHeight: viewport_length!(100., vw) + ); + assert_decl_eq!(&declarations[4], Author, Zoom: Zoom::Number(2.)); + }, + ); - test_meta_viewport("width=480, initial-scale=2.0, user-scalable=1", |declarations, meta| { - println!("{}", meta); - assert_decl_len!(declarations == 4); - assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::ExtendToZoom); - assert_decl_eq!(&declarations[1], Author, MaxWidth: viewport_length!(480., px)); - assert_decl_eq!(&declarations[2], Author, Zoom: Zoom::Number(2.)); - assert_decl_eq!(&declarations[3], Author, UserZoom: UserZoom::Zoom); - }); + test_meta_viewport( + "width=480, initial-scale=2.0, user-scalable=1", + |declarations, meta| { + println!("{}", meta); + assert_decl_len!(declarations == 4); + assert_decl_eq!( + &declarations[0], + Author, + MinWidth: ViewportLength::ExtendToZoom + ); + assert_decl_eq!( + &declarations[1], + Author, + MaxWidth: viewport_length!(480., px) + ); + assert_decl_eq!(&declarations[2], Author, Zoom: Zoom::Number(2.)); + assert_decl_eq!(&declarations[3], Author, UserZoom: UserZoom::Zoom); + }, + ); } #[test] fn cascading_within_viewport_rule() { - let device = Device::new(MediaType::screen(), TypedSize2D::new(800., 600.), TypedScale::new(1.0)); + let device = Device::new( + MediaType::screen(), + TypedSize2D::new(800., 600.), + TypedScale::new(1.0), + ); // normal order of appearance - test_viewport_rule("@viewport { min-width: 200px; min-width: auto; }", - &device, |declarations, css| { - println!("{}", css); - assert_decl_len!(declarations == 1); - assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::Specified(Auto)); - }); + test_viewport_rule( + "@viewport { min-width: 200px; min-width: auto; }", + &device, + |declarations, css| { + println!("{}", css); + assert_decl_len!(declarations == 1); + assert_decl_eq!( + &declarations[0], + Author, + MinWidth: ViewportLength::Specified(Auto) + ); + }, + ); // !important order of appearance - test_viewport_rule("@viewport { min-width: 200px !important; min-width: auto !important; }", - &device, |declarations, css| { - println!("{}", css); - assert_decl_len!(declarations == 1); - assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::Specified(Auto), !important); - }); + test_viewport_rule( + "@viewport { min-width: 200px !important; min-width: auto !important; }", + &device, + |declarations, css| { + println!("{}", css); + assert_decl_len!(declarations == 1); + assert_decl_eq!( + &declarations[0], + Author, + MinWidth: ViewportLength::Specified(Auto), + !important + ); + }, + ); // !important vs normal - test_viewport_rule("@viewport { min-width: auto !important; min-width: 200px; }", - &device, |declarations, css| { - println!("{}", css); - assert_decl_len!(declarations == 1); - assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::Specified(Auto), !important); - }); + test_viewport_rule( + "@viewport { min-width: auto !important; min-width: 200px; }", + &device, + |declarations, css| { + println!("{}", css); + assert_decl_len!(declarations == 1); + assert_decl_eq!( + &declarations[0], + Author, + MinWidth: ViewportLength::Specified(Auto), + !important + ); + }, + ); // normal longhands vs normal shorthand - test_viewport_rule("@viewport { min-width: 200px; max-width: 200px; width: auto; }", - &device, |declarations, css| { - println!("{}", css); - assert_decl_len!(declarations == 2); - assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::Specified(Auto)); - assert_decl_eq!(&declarations[1], Author, MaxWidth: ViewportLength::Specified(Auto)); - }); + test_viewport_rule( + "@viewport { min-width: 200px; max-width: 200px; width: auto; }", + &device, + |declarations, css| { + println!("{}", css); + assert_decl_len!(declarations == 2); + assert_decl_eq!( + &declarations[0], + Author, + MinWidth: ViewportLength::Specified(Auto) + ); + assert_decl_eq!( + &declarations[1], + Author, + MaxWidth: ViewportLength::Specified(Auto) + ); + }, + ); // normal shorthand vs normal longhands - test_viewport_rule("@viewport { width: 200px; min-width: auto; max-width: auto; }", - &device, |declarations, css| { - println!("{}", css); - assert_decl_len!(declarations == 2); - assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::Specified(Auto)); - assert_decl_eq!(&declarations[1], Author, MaxWidth: ViewportLength::Specified(Auto)); - }); + test_viewport_rule( + "@viewport { width: 200px; min-width: auto; max-width: auto; }", + &device, + |declarations, css| { + println!("{}", css); + assert_decl_len!(declarations == 2); + assert_decl_eq!( + &declarations[0], + Author, + MinWidth: ViewportLength::Specified(Auto) + ); + assert_decl_eq!( + &declarations[1], + Author, + MaxWidth: ViewportLength::Specified(Auto) + ); + }, + ); // one !important longhand vs normal shorthand - test_viewport_rule("@viewport { min-width: auto !important; width: 200px; }", - &device, |declarations, css| { - println!("{}", css); - assert_decl_len!(declarations == 2); - assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::Specified(Auto), !important); - assert_decl_eq!(&declarations[1], Author, MaxWidth: viewport_length!(200., px)); - }); + test_viewport_rule( + "@viewport { min-width: auto !important; width: 200px; }", + &device, + |declarations, css| { + println!("{}", css); + assert_decl_len!(declarations == 2); + assert_decl_eq!( + &declarations[0], + Author, + MinWidth: ViewportLength::Specified(Auto), + !important + ); + assert_decl_eq!( + &declarations[1], + Author, + MaxWidth: viewport_length!(200., px) + ); + }, + ); // both !important longhands vs normal shorthand - test_viewport_rule("@viewport { min-width: auto !important; max-width: auto !important; width: 200px; }", - &device, |declarations, css| { - println!("{}", css); - assert_decl_len!(declarations == 2); - assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::Specified(Auto), !important); - assert_decl_eq!(&declarations[1], Author, MaxWidth: ViewportLength::Specified(Auto), !important); - }); + test_viewport_rule( + "@viewport { min-width: auto !important; max-width: auto !important; width: 200px; }", + &device, + |declarations, css| { + println!("{}", css); + assert_decl_len!(declarations == 2); + assert_decl_eq!( + &declarations[0], + Author, + MinWidth: ViewportLength::Specified(Auto), + !important + ); + assert_decl_eq!( + &declarations[1], + Author, + MaxWidth: ViewportLength::Specified(Auto), + !important + ); + }, + ); } #[test] fn multiple_stylesheets_cascading() { PREFS.set("layout.viewport.enabled", PrefValue::Boolean(true)); - let device = Device::new(MediaType::screen(), TypedSize2D::new(800., 600.), TypedScale::new(1.0)); + let device = Device::new( + MediaType::screen(), + TypedSize2D::new(800., 600.), + TypedScale::new(1.0), + ); let shared_lock = SharedRwLock::new(); let stylesheets = vec![ - stylesheet!("@viewport { min-width: 100px; min-height: 100px; zoom: 1; }", - UserAgent, - shared_lock.clone()), - stylesheet!("@viewport { min-width: 200px; min-height: 200px; }", - User, shared_lock.clone()), - stylesheet!("@viewport { min-width: 300px; }", - Author, shared_lock.clone()) + stylesheet!( + "@viewport { min-width: 100px; min-height: 100px; zoom: 1; }", + UserAgent, + shared_lock.clone() + ), + stylesheet!( + "@viewport { min-width: 200px; min-height: 200px; }", + User, + shared_lock.clone() + ), + stylesheet!( + "@viewport { min-width: 300px; }", + Author, + shared_lock.clone() + ), ]; let declarations = Cascade::from_stylesheets( stylesheets.iter().map(|s| (&**s, Origin::Author)), &StylesheetGuards::same(&shared_lock.read()), &device, - ).finish(); + ) + .finish(); assert_decl_len!(declarations == 3); assert_decl_eq!(&declarations[0], UserAgent, Zoom: Zoom::Number(1.)); - assert_decl_eq!(&declarations[1], User, MinHeight: viewport_length!(200., px)); - assert_decl_eq!(&declarations[2], Author, MinWidth: viewport_length!(300., px)); + assert_decl_eq!( + &declarations[1], + User, + MinHeight: viewport_length!(200., px) + ); + assert_decl_eq!( + &declarations[2], + Author, + MinWidth: viewport_length!(300., px) + ); let stylesheets = vec![ stylesheet!("@viewport { min-width: 100px !important; }", @@ -291,10 +499,21 @@ fn multiple_stylesheets_cascading() { stylesheets.iter().map(|s| (&**s, Origin::Author)), &StylesheetGuards::same(&shared_lock.read()), &device, - ).finish(); + ) + .finish(); assert_decl_len!(declarations == 3); - assert_decl_eq!(&declarations[0], UserAgent, MinWidth: viewport_length!(100., px), !important); - assert_decl_eq!(&declarations[1], User, MinHeight: viewport_length!(200., px), !important); + assert_decl_eq!( + &declarations[0], + UserAgent, + MinWidth: viewport_length!(100., px), + !important + ); + assert_decl_eq!( + &declarations[1], + User, + MinHeight: viewport_length!(200., px), + !important + ); assert_decl_eq!(&declarations[2], Author, Zoom: Zoom::Number(3.), !important); } @@ -314,70 +533,81 @@ fn constrain_viewport() { macro_rules! from_css { ($css:expr) => { &ViewportRule::parse(&context, &mut Parser::new(&mut $css)).unwrap() - } + }; } let initial_viewport = TypedSize2D::new(800., 600.); let device = Device::new(MediaType::screen(), initial_viewport, TypedScale::new(1.0)); let mut input = ParserInput::new(""); - assert_eq!(ViewportConstraints::maybe_new(&device, from_css!(input), QuirksMode::NoQuirks), None); + assert_eq!( + ViewportConstraints::maybe_new(&device, from_css!(input), QuirksMode::NoQuirks), + None + ); let mut input = ParserInput::new("width: 320px auto"); - assert_eq!(ViewportConstraints::maybe_new(&device, from_css!(input), QuirksMode::NoQuirks), - Some(ViewportConstraints { - size: initial_viewport, - - initial_zoom: PinchZoomFactor::new(1.), - min_zoom: None, - max_zoom: None, - - user_zoom: UserZoom::Zoom, - orientation: Orientation::Auto - })); + assert_eq!( + ViewportConstraints::maybe_new(&device, from_css!(input), QuirksMode::NoQuirks), + Some(ViewportConstraints { + size: initial_viewport, + + initial_zoom: PinchZoomFactor::new(1.), + min_zoom: None, + max_zoom: None, + + user_zoom: UserZoom::Zoom, + orientation: Orientation::Auto + }) + ); let mut input = ParserInput::new("width: 320px auto"); - assert_eq!(ViewportConstraints::maybe_new(&device, from_css!(input), QuirksMode::NoQuirks), - Some(ViewportConstraints { - size: initial_viewport, - - initial_zoom: PinchZoomFactor::new(1.), - min_zoom: None, - max_zoom: None, - - user_zoom: UserZoom::Zoom, - orientation: Orientation::Auto - })); - - let mut input = ParserInput::new("width: 800px; height: 600px;\ - zoom: 1;\ - user-zoom: zoom;\ - orientation: auto;"); - assert_eq!(ViewportConstraints::maybe_new(&device, - from_css!(input), - QuirksMode::NoQuirks), - Some(ViewportConstraints { - size: initial_viewport, - - initial_zoom: PinchZoomFactor::new(1.), - min_zoom: None, - max_zoom: None, - - user_zoom: UserZoom::Zoom, - orientation: Orientation::Auto - })); + assert_eq!( + ViewportConstraints::maybe_new(&device, from_css!(input), QuirksMode::NoQuirks), + Some(ViewportConstraints { + size: initial_viewport, + + initial_zoom: PinchZoomFactor::new(1.), + min_zoom: None, + max_zoom: None, + + user_zoom: UserZoom::Zoom, + orientation: Orientation::Auto + }) + ); + + let mut input = ParserInput::new( + "width: 800px; height: 600px;\ + zoom: 1;\ + user-zoom: zoom;\ + orientation: auto;", + ); + assert_eq!( + ViewportConstraints::maybe_new(&device, from_css!(input), QuirksMode::NoQuirks), + Some(ViewportConstraints { + size: initial_viewport, + + initial_zoom: PinchZoomFactor::new(1.), + min_zoom: None, + max_zoom: None, + + user_zoom: UserZoom::Zoom, + orientation: Orientation::Auto + }) + ); let initial_viewport = TypedSize2D::new(200., 150.); let device = Device::new(MediaType::screen(), initial_viewport, TypedScale::new(1.0)); let mut input = ParserInput::new("width: 320px auto"); - assert_eq!(ViewportConstraints::maybe_new(&device, from_css!(input), QuirksMode::NoQuirks), - Some(ViewportConstraints { - size: TypedSize2D::new(320., 240.), - - initial_zoom: PinchZoomFactor::new(1.), - min_zoom: None, - max_zoom: None, - - user_zoom: UserZoom::Zoom, - orientation: Orientation::Auto - })); + assert_eq!( + ViewportConstraints::maybe_new(&device, from_css!(input), QuirksMode::NoQuirks), + Some(ViewportConstraints { + size: TypedSize2D::new(320., 240.), + + initial_zoom: PinchZoomFactor::new(1.), + min_zoom: None, + max_zoom: None, + + user_zoom: UserZoom::Zoom, + orientation: Orientation::Auto + }) + ); } |