diff --git a/.travis.yml b/.travis.yml index ae7c802ea8c..659e2ad4b5e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,6 +4,9 @@ matrix: fast_finish: true include: - sudo: false + before_install: + - curl https://sh.rustup.rs -sSf | sh -s -- --default-toolchain none -y + - source ~/.profile script: - ./mach test-tidy --no-progress --all - ./mach test-tidy --no-progress --self-test diff --git a/components/allocator/lib.rs b/components/allocator/lib.rs index 59596ce8e8d..963ff5f759b 100644 --- a/components/allocator/lib.rs +++ b/components/allocator/lib.rs @@ -23,38 +23,30 @@ mod platform { /// Memory allocation APIs compatible with libc pub mod libc_compat { - pub use super::ffi::{malloc, realloc, free}; + pub use super::ffi::{free, malloc, realloc}; } pub struct Allocator; // 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 { @@ -106,8 +98,8 @@ mod platform { mod platform { extern crate kernel32; - pub use std::alloc::System as Allocator; use self::kernel32::{GetProcessHeap, HeapSize, HeapValidate}; + pub use std::alloc::System as Allocator; use std::os::raw::c_void; /// Get the size of a heap block. diff --git a/components/atoms/build.rs b/components/atoms/build.rs index 309e111dbd7..245440b06e5 100644 --- a/components/atoms/build.rs +++ b/components/atoms/build.rs @@ -6,7 +6,7 @@ extern crate string_cache_codegen; use std::env; use std::fs::File; -use std::io::{BufReader, BufRead}; +use std::io::{BufRead, BufReader}; use std::path::Path; fn main() { diff --git a/components/bluetooth/lib.rs b/components/bluetooth/lib.rs index 300927d440f..8d9f7bd0af5 100644 --- a/components/bluetooth/lib.rs +++ b/components/bluetooth/lib.rs @@ -16,11 +16,13 @@ extern crate uuid; pub mod test; +use bluetooth_traits::blocklist::{uuid_is_blocklisted, Blocklist}; +use bluetooth_traits::scanfilter::{ + BluetoothScanfilter, BluetoothScanfilterSequence, RequestDeviceoptions, +}; use bluetooth_traits::{BluetoothCharacteristicMsg, BluetoothDescriptorMsg, BluetoothServiceMsg}; use bluetooth_traits::{BluetoothDeviceMsg, BluetoothRequest, BluetoothResponse, GATTType}; use bluetooth_traits::{BluetoothError, BluetoothResponseResult, BluetoothResult}; -use bluetooth_traits::blocklist::{uuid_is_blocklisted, Blocklist}; -use bluetooth_traits::scanfilter::{BluetoothScanfilter, BluetoothScanfilterSequence, RequestDeviceoptions}; use device::bluetooth::{BluetoothAdapter, BluetoothDevice, BluetoothGATTCharacteristic}; use device::bluetooth::{BluetoothGATTDescriptor, BluetoothGATTService}; use embedder_traits::{EmbedderMsg, EmbedderProxy}; @@ -74,7 +76,8 @@ impl BluetoothThreadFactory for IpcSender { BluetoothAdapter::init() } else { BluetoothAdapter::init_mock() - }.ok(); + } + .ok(); thread::Builder::new() .name("BluetoothThread".to_owned()) .spawn(move || { @@ -465,8 +468,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 +561,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..6138bbdb35e 100644 --- a/components/bluetooth/test.rs +++ b/components/bluetooth/test.rs @@ -4,10 +4,12 @@ use crate::BluetoothManager; use device::bluetooth::{BluetoothAdapter, BluetoothDevice}; -use device::bluetooth::{BluetoothGATTCharacteristic, BluetoothGATTDescriptor, BluetoothGATTService}; +use device::bluetooth::{ + BluetoothGATTCharacteristic, BluetoothGATTDescriptor, BluetoothGATTService, +}; use std::borrow::ToOwned; use std::cell::RefCell; -use std::collections::{HashSet, HashMap}; +use std::collections::{HashMap, HashSet}; use std::error::Error; use std::string::String; use uuid::Uuid; @@ -294,14 +296,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..97e2dee4800 100644 --- a/components/canvas/canvas_data.rs +++ b/components/canvas/canvas_data.rs @@ -3,14 +3,16 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use azure::azure::AzFloat; +use azure::azure_hl::SurfacePattern; use azure::azure_hl::{AntialiasMode, CapStyle, CompositionOp, JoinStyle}; -use azure::azure_hl::{BackendType, DrawOptions, DrawTarget, Pattern, StrokeOptions, SurfaceFormat}; +use azure::azure_hl::{ + BackendType, DrawOptions, DrawTarget, Pattern, StrokeOptions, SurfaceFormat, +}; use azure::azure_hl::{Color, ColorPattern, DrawSurfaceOptions, Filter, PathBuilder}; use azure::azure_hl::{ExtendMode, GradientStop, LinearGradientPattern, RadialGradientPattern}; -use azure::azure_hl::SurfacePattern; use canvas_traits::canvas::*; use cssparser::RGBA; -use euclid::{Transform2D, Point2D, Vector2D, Rect, Size2D}; +use euclid::{Point2D, Rect, Size2D, Transform2D, Vector2D}; use ipc_channel::ipc::IpcSender; use num_traits::ToPrimitive; use pixels; @@ -39,7 +41,7 @@ impl<'a> CanvasData<'a> { size: Size2D, 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 +65,7 @@ impl<'a> CanvasData<'a> { image_size: Size2D, dest_rect: Rect, source_rect: Rect, - 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 +77,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 +113,10 @@ impl<'a> CanvasData<'a> { } pub fn fill_text(&self, text: String, x: f64, y: f64, max_width: Option) { - 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) { @@ -111,7 +124,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 +133,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 +170,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 +220,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 +232,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 +249,7 @@ impl<'a> CanvasData<'a> { x: f64, y: f64, _fill_rule: FillRule, - chan: IpcSender + chan: IpcSender, ) { let path = self.path_builder.finish(); let result = path.contains_point(x, y, &self.state.transform); @@ -227,19 +266,22 @@ impl<'a> CanvasData<'a> { } pub fn rect(&self, rect: &Rect) { - 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, - endpoint: &Point2D - ) { + pub fn quadratic_curve_to(&self, cp: &Point2D, endpoint: &Point2D) { self.path_builder.quadratic_curve_to(cp, endpoint) } @@ -247,7 +289,7 @@ impl<'a> CanvasData<'a> { &self, cp1: &Point2D, cp2: &Point2D, - endpoint: &Point2D + endpoint: &Point2D, ) { self.path_builder.bezier_curve_to(cp1, cp2, endpoint) } @@ -258,17 +300,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, - cp2: &Point2D, - radius: AzFloat - ) { + pub fn arc_to(&self, cp1: &Point2D, cp2: &Point2D, radius: AzFloat) { let cp0 = self.path_builder.get_current_point(); let cp1 = *cp1; let cp2 = *cp2; @@ -314,9 +352,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 +374,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 +425,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) -> DrawTarget { @@ -398,7 +454,13 @@ impl<'a> CanvasData<'a> { #[allow(unsafe_code)] pub fn send_pixels(&mut self, chan: IpcSender>) { - 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 +476,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 +486,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 +513,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 +548,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) -> 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 +569,26 @@ impl<'a> CanvasData<'a> { } fn draw_with_shadow(&self, rect: &Rect, 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 +597,19 @@ impl<'a> CanvasData<'a> { #[allow(unsafe_code)] pub fn read_pixels(&self, read_rect: Rect, canvas_size: Size2D) -> Vec { 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 +648,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 +686,10 @@ fn write_image( dest_rect: Rect, 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 +704,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 +729,7 @@ pub trait PointToi32 { impl PointToi32 for Point2D { fn to_i32(&self) -> Point2D { - 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 +739,7 @@ pub trait SizeToi32 { impl SizeToi32 for Size2D { fn to_i32(&self) -> Size2D { - 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 +750,24 @@ pub trait RectToi32 { impl RectToi32 for Rect { fn to_i32(&self) -> Rect { - 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 { - 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 +779,13 @@ impl ToAzureStyle for Rect { type Target = Rect; fn to_azure_style(self) -> Rect { - 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 +815,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 +835,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 +876,49 @@ impl ToAzurePattern for FillOrStrokeStyle { Pattern::Color(ColorPattern::new(color.to_azure_style())) }, FillOrStrokeStyle::LinearGradient(ref linear_gradient_style) => { - let gradient_stops: Vec = linear_gradient_style.stops.iter().map(|s| { - GradientStop { + let gradient_stops: Vec = 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 = radial_gradient_style.stops.iter().map(|s| { - GradientStop { + let gradient_stops: Vec = 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 +937,7 @@ impl ToAzurePattern for FillOrStrokeStyle { surface_style.repeat_y, &Transform2D::identity(), )) - } + }, }) } } @@ -831,9 +946,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>, 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 { let (sender, receiver) = ipc::channel::().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, 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..077ea3b7f9f 100644 --- a/components/canvas/gl_context.rs +++ b/components/canvas/gl_context.rs @@ -2,16 +2,18 @@ * 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/. */ -use canvas_traits::webgl::{WebGLCommand, WebGLVersion, WebGLCommandBacktrace}; -use compositing::compositor_thread::{CompositorProxy, self}; +use super::webgl_thread::{GLState, WebGLImpl}; +use canvas_traits::webgl::{WebGLCommand, WebGLCommandBacktrace, WebGLVersion}; +use compositing::compositor_thread::{self, CompositorProxy}; use euclid::Size2D; use gleam::gl; -use offscreen_gl_context::{ColorAttachmentType, GLContext, GLContextAttributes, GLContextDispatcher}; +use offscreen_gl_context::{ + ColorAttachmentType, GLContext, GLContextAttributes, GLContextDispatcher, +}; use offscreen_gl_context::{GLLimits, GLVersion}; use offscreen_gl_context::{NativeGLContext, NativeGLContextHandle, NativeGLContextMethods}; use offscreen_gl_context::{OSMesaContext, OSMesaContextHandle}; use std::sync::{Arc, Mutex}; -use super::webgl_thread::{WebGLImpl, GLState}; /// The GLContextFactory is used to create shared GL contexts with the main thread GL context. /// Currently, shared textures are used to render WebGL textures into the WR compositor. @@ -48,7 +50,7 @@ impl GLContextFactory { &self, webgl_version: WebGLVersion, size: Size2D, - attributes: GLContextAttributes + attributes: GLContextAttributes, ) -> Result { Ok(match *self { GLContextFactory::Native(ref handle, ref dispatcher) => { @@ -63,7 +65,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 +77,7 @@ impl GLContextFactory { Some(handle), None, )?) - } + }, }) } @@ -84,7 +86,7 @@ impl GLContextFactory { &self, webgl_version: WebGLVersion, size: Size2D, - attributes: GLContextAttributes + attributes: GLContextAttributes, ) -> Result { Ok(match *self { GLContextFactory::Native(..) => { @@ -98,7 +100,7 @@ impl GLContextFactory { None, None, )?) - } + }, GLContextFactory::OSMesa(_) => { GLContextWrapper::OSMesa(GLContext::new_shared_with_dispatcher( // FIXME(nox): Why are those i32 values? @@ -110,7 +112,7 @@ impl GLContextFactory { None, None, )?) - } + }, }) } @@ -122,7 +124,6 @@ impl GLContextFactory { } } - /// GLContextWrapper used to abstract NativeGLContext and OSMesaContext types pub enum GLContextWrapper { Native(GLContext), @@ -134,10 +135,10 @@ impl GLContextWrapper { match *self { GLContextWrapper::Native(ref ctx) => { ctx.make_current().unwrap(); - } + }, GLContextWrapper::OSMesa(ref ctx) => { ctx.make_current().unwrap(); - } + }, } } @@ -145,10 +146,10 @@ impl GLContextWrapper { match *self { GLContextWrapper::Native(ref ctx) => { ctx.unbind().unwrap(); - } + }, GLContextWrapper::OSMesa(ref ctx) => { ctx.unbind().unwrap(); - } + }, } } @@ -156,26 +157,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 +181,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 +212,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 +225,7 @@ impl GLContextWrapper { /// It's used in Windows to allow WGL GLContext sharing. #[derive(Clone)] pub struct MainThreadDispatcher { - compositor_proxy: Arc> + compositor_proxy: Arc>, } impl MainThreadDispatcher { @@ -234,6 +237,9 @@ impl MainThreadDispatcher { } impl GLContextDispatcher for MainThreadDispatcher { fn dispatch(&self, f: Box) { - 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_mode/inprocess.rs b/components/canvas/webgl_mode/inprocess.rs index c7b1756aa32..1f7ade4eb56 100644 --- a/components/canvas/webgl_mode/inprocess.rs +++ b/components/canvas/webgl_mode/inprocess.rs @@ -2,10 +2,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use canvas_traits::webgl::webgl_channel; +use canvas_traits::webgl::DOMToTextureCommand; use canvas_traits::webgl::{WebGLChan, WebGLContextId, WebGLMsg, WebGLPipeline, WebGLReceiver}; use canvas_traits::webgl::{WebGLSender, WebVRCommand, WebVRRenderHandler}; -use canvas_traits::webgl::DOMToTextureCommand; -use canvas_traits::webgl::webgl_channel; use crate::gl_context::GLContextFactory; use crate::webgl_thread::{WebGLExternalImageApi, WebGLExternalImageHandler, WebGLThread}; use euclid::Size2D; diff --git a/components/canvas/webgl_thread.rs b/components/canvas/webgl_thread.rs index 96233d1c410..e47bfffdbcc 100644 --- a/components/canvas/webgl_thread.rs +++ b/components/canvas/webgl_thread.rs @@ -2,6 +2,7 @@ * 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/. */ +use super::gl_context::{GLContextFactory, GLContextWrapper}; use canvas_traits::webgl::*; use euclid::Size2D; use fnv::FnvHashMap; @@ -9,7 +10,6 @@ use gleam::gl; use offscreen_gl_context::{GLContext, GLContextAttributes, GLLimits, NativeGLContextMethods}; use pixels; use std::thread; -use super::gl_context::{GLContextFactory, GLContextWrapper}; use webrender; use webrender_api; @@ -92,21 +92,21 @@ impl WebGLThread { ) -> WebGLSender { let (sender, receiver) = webgl_channel::().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 WebGLThread { 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); + 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); - } + // 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(); + 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 WebGLThread { }, WebGLMsg::Exit => { return true; - } + }, } false @@ -177,7 +183,11 @@ impl WebGLThread { 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 WebGLThread { 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, 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, 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 WebGLThread { // 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 WebGLThread { // 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 WebGLThread { 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 WebGLThread { 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 WebGLThread { // 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 WebGLThread { /// 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) { + fn handle_update_wr_image( + &mut self, + context_id: WebGLContextId, + sender: WebGLSender, + ) { let info = self.cached_context_info.get_mut(&context_id).unwrap(); let webrender_api = &self.webrender_api; @@ -353,25 +386,29 @@ impl WebGLThread { 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 WebGLThread { 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 WebGLThread { 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 WebGLThread { 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 WebGLThread { 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 WebGLThread { } /// 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, - bound_id: &mut Option) -> Option<&'a GLContextData> { + fn make_current_if_needed<'a>( + context_id: WebGLContextId, + contexts: &'a FnvHashMap, + bound_id: &mut Option, + ) -> Option<&'a GLContextData> { let data = contexts.get(&context_id); if let Some(data) = data { @@ -452,9 +510,8 @@ impl WebGLThread { fn make_current_if_needed_mut<'a>( context_id: WebGLContextId, contexts: &'a mut FnvHashMap, - bound_id: &mut Option) - -> Option<&'a mut GLContextData> - { + bound_id: &mut Option, + ) -> Option<&'a mut GLContextData> { let data = contexts.get_mut(&context_id); if let Some(ref data) = data { @@ -468,10 +525,12 @@ impl WebGLThread { } /// Creates a `webrender_api::ImageKey` that uses shared textures. - fn create_wr_external_image(webrender_api: &webrender_api::RenderApi, - size: Size2D, - alpha: bool, - context_id: WebGLContextId) -> webrender_api::ImageKey { + fn create_wr_external_image( + webrender_api: &webrender_api::RenderApi, + size: Size2D, + 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 WebGLThread { } /// Updates a `webrender_api::ImageKey` that uses shared textures. - fn update_wr_external_image(webrender_api: &webrender_api::RenderApi, - size: Size2D, - alpha: bool, - context_id: WebGLContextId, - image_key: webrender_api::ImageKey) { + fn update_wr_external_image( + webrender_api: &webrender_api::RenderApi, + size: Size2D, + 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 WebGLThread { } /// Creates a `webrender_api::ImageKey` that uses raw pixels. - fn create_wr_readback_image(webrender_api: &webrender_api::RenderApi, - size: Size2D, - alpha: bool, - data: Vec) -> webrender_api::ImageKey { + fn create_wr_readback_image( + webrender_api: &webrender_api::RenderApi, + size: Size2D, + alpha: bool, + data: Vec, + ) -> webrender_api::ImageKey { let descriptor = Self::image_descriptor(size, alpha); let data = webrender_api::ImageData::new(data); @@ -514,11 +577,13 @@ impl WebGLThread { } /// Updates a `webrender_api::ImageKey` that uses raw pixels. - fn update_wr_readback_image(webrender_api: &webrender_api::RenderApi, - size: Size2D, - alpha: bool, - image_key: webrender_api::ImageKey, - data: Vec) { + fn update_wr_readback_image( + webrender_api: &webrender_api::RenderApi, + size: Size2D, + alpha: bool, + image_key: webrender_api::ImageKey, + data: Vec, + ) { let descriptor = Self::image_descriptor(size, alpha); let data = webrender_api::ImageData::new(data); @@ -556,18 +621,22 @@ impl WebGLThread { 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 WebGLThread { 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::().ok()).unwrap_or(1); - let minor = values.next().and_then(|v| v.parse::().ok()).unwrap_or(20); + let major = values + .next() + .and_then(|v| v.parse::().ok()) + .unwrap_or(1); + let minor = values + .next() + .and_then(|v| v.parse::().ok()) + .unwrap_or(20); - WebGLSLVersion { - major, - minor, - } + WebGLSLVersion { major, minor } } } @@ -632,38 +704,30 @@ pub struct WebGLExternalImageHandler { impl WebGLExternalImageHandler { pub fn new(handler: T) -> Self { - Self { - handler: handler - } + Self { handler: handler } } } impl webrender::ExternalImageHandler for WebGLExternalImageHandler { /// 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::>().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::>() + .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::>().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::>() + .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 + chan: &WebGLSender, ) { 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 - ) { + fn get_renderbuffer_parameter(gl: &gl::Gl, target: u32, pname: u32, chan: &WebGLSender) { 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) { let log = gl.get_shader_info_log(shader_id.get()); chan.send(log).unwrap(); @@ -1491,20 +1633,22 @@ impl WebGLImpl { } #[inline] - fn bind_framebuffer(gl: &gl::Gl, - target: u32, - request: WebGLFramebufferBindingRequest, - ctx: &GLContext) { + fn bind_framebuffer( + gl: &gl::Gl, + target: u32, + request: WebGLFramebufferBindingRequest, + ctx: &GLContext, + ) { 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..3c28943a830 100644 --- a/components/canvas_traits/canvas.rs +++ b/components/canvas_traits/canvas.rs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; -use euclid::{Transform2D, Point2D, Rect, Size2D}; +use euclid::{Point2D, Rect, Size2D, Transform2D}; use ipc_channel::ipc::{IpcBytesReceiver, IpcBytesSender, IpcSender}; use serde_bytes::ByteBuf; use std::default::Default; @@ -22,7 +22,12 @@ pub struct CanvasId(pub u64); #[derive(Deserialize, Serialize)] pub enum CanvasMsg { Canvas2d(Canvas2dMsg, CanvasId), - Create(IpcSender, Size2D, webrender_api::RenderApiSender, bool), + Create( + IpcSender, + Size2D, + webrender_api::RenderApiSender, + bool, + ), FromLayout(FromLayoutMsg, CanvasId), FromScript(FromScriptMsg, CanvasId), Recreate(Size2D, CanvasId), @@ -40,8 +45,7 @@ pub enum Canvas2dMsg { Arc(Point2D, f32, f32, f32, bool), ArcTo(Point2D, Point2D, f32), DrawImage(Option, Size2D, Rect, Rect, bool), - DrawImageInOther( - CanvasId, Size2D, Rect, Rect, bool), + DrawImageInOther(CanvasId, Size2D, Rect, Rect, bool), BeginPath, BezierCurveTo(Point2D, Point2D, Point2D), ClearRect(Rect), @@ -99,12 +103,17 @@ pub struct LinearGradientStyle { pub y0: f64, pub x1: f64, pub y1: f64, - pub stops: Vec + pub stops: Vec, } impl LinearGradientStyle { - pub fn new(x0: f64, y0: f64, x1: f64, y1: f64, stops: Vec) - -> LinearGradientStyle { + pub fn new( + x0: f64, + y0: f64, + x1: f64, + y1: f64, + stops: Vec, + ) -> 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 + pub stops: Vec, } impl RadialGradientStyle { - pub fn new(x0: f64, y0: f64, r0: f64, x1: f64, y1: f64, r1: f64, stops: Vec) - -> RadialGradientStyle { + pub fn new( + x0: f64, + y0: f64, + r0: f64, + x1: f64, + y1: f64, + r1: f64, + stops: Vec, + ) -> 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 { 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 { 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..dce9c441e1c 100644 --- a/components/canvas_traits/webgl.rs +++ b/components/canvas_traits/webgl.rs @@ -11,18 +11,18 @@ use std::borrow::Cow; use std::num::NonZeroU32; use webrender_api::{DocumentId, ImageKey, PipelineId}; -/// Sender type used in WebGLCommands. -pub use crate::webgl_channel::WebGLSender; +/// Helper function that creates a WebGL channel (WebGLSender, WebGLReceiver) to be used in WebGLCommands. +pub use crate::webgl_channel::webgl_channel; +/// Entry point channel type used for sending WebGLMsg messages to the WebGL renderer. +pub use crate::webgl_channel::WebGLChan; +/// Entry point type used in a Script Pipeline to get the WebGLChan to be used in that thread. +pub use crate::webgl_channel::WebGLPipeline; /// Receiver type used in WebGLCommands. pub use crate::webgl_channel::WebGLReceiver; /// Result type for send()/recv() calls in in WebGLCommands. pub use crate::webgl_channel::WebGLSendResult; -/// Helper function that creates a WebGL channel (WebGLSender, WebGLReceiver) to be used in WebGLCommands. -pub use crate::webgl_channel::webgl_channel; -/// Entry point type used in a Script Pipeline to get the WebGLChan to be used in that thread. -pub use crate::webgl_channel::WebGLPipeline; -/// Entry point channel type used for sending WebGLMsg messages to the WebGL renderer. -pub use crate::webgl_channel::WebGLChan; +/// Sender type used in WebGLCommands. +pub use crate::webgl_channel::WebGLSender; #[derive(Clone, Debug, Deserialize, Serialize)] pub struct WebGLCommandBacktrace { @@ -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, sender: WebGLSender>, ) -> 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) -> 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), 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), 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(deserializer: D) -> Result - 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(&self, serializer: S) -> Result - 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), + Attach( + WebGLContextId, + WebGLTextureId, + DocumentId, + PipelineId, + Size2D, + ), /// 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..fd8dc7e5824 100644 --- a/components/channel/lib.rs +++ b/components/channel/lib.rs @@ -15,46 +15,45 @@ pub use crossbeam_channel::*; use ipc_channel::ipc::IpcReceiver; use ipc_channel::router::ROUTER; use serde::{Deserialize, Serialize}; -use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; - +use std::sync::Arc; pub fn route_ipc_receiver_to_new_servo_receiver(ipc_receiver: IpcReceiver) -> Receiver 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::().unwrap())) - }), + Box::new(move |message| drop(servo_sender.send(message.to::().unwrap()))), ); servo_receiver } -pub fn route_ipc_receiver_to_new_servo_sender(ipc_receiver: IpcReceiver, servo_sender: Sender) -where - T: for<'de> Deserialize<'de> + Serialize + Send + 'static +pub fn route_ipc_receiver_to_new_servo_sender( + ipc_receiver: IpcReceiver, + servo_sender: Sender, +) 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::().unwrap())) - }), + Box::new(move |message| drop(servo_sender.send(message.to::().unwrap()))), ) } pub fn channel() -> (Sender, Receiver) { let (base_sender, base_receiver) = crossbeam_channel::unbounded::(); 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 { @@ -78,7 +77,10 @@ impl Clone for Receiver { } impl Receiver { - pub fn new(receiver: crossbeam_channel::Receiver, is_disconnected: Arc) -> Receiver { + pub fn new( + receiver: crossbeam_channel::Receiver, + is_disconnected: Arc, + ) -> Receiver { Receiver { receiver, is_disconnected, @@ -134,7 +136,10 @@ impl Clone for Sender { } impl Sender { - pub fn new(sender: crossbeam_channel::Sender, is_disconnected: Arc) -> Sender { + pub fn new( + sender: crossbeam_channel::Sender, + is_disconnected: Arc, + ) -> Sender { 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..c3974c7fd01 100644 --- a/components/compositing/compositor.rs +++ b/components/compositing/compositor.rs @@ -2,15 +2,17 @@ * 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/. */ -use crate::CompositionPipeline; -use crate::SendableFrameTree; use crate::compositor_thread::{CompositorProxy, CompositorReceiver}; use crate::compositor_thread::{InitialCompositorState, Msg}; #[cfg(feature = "gleam")] use crate::gl; -use crate::touch::{TouchHandler, TouchAction}; -use crate::windowing::{self, EmbedderCoordinates, MouseWindowEvent, WebRenderDebugOption, WindowMethods}; -use euclid::{TypedPoint2D, TypedVector2D, TypedScale}; +use crate::touch::{TouchAction, TouchHandler}; +use crate::windowing::{ + self, EmbedderCoordinates, MouseWindowEvent, WebRenderDebugOption, WindowMethods, +}; +use crate::CompositionPipeline; +use crate::SendableFrameTree; +use euclid::{TypedPoint2D, TypedScale, TypedVector2D}; use gfx_traits::Epoch; #[cfg(feature = "gleam")] use image::{DynamicImage, ImageFormat}; @@ -20,23 +22,23 @@ use msg::constellation_msg::{PipelineId, PipelineIndex, PipelineNamespaceId}; use net_traits::image::base::Image; #[cfg(feature = "gleam")] use net_traits::image::base::PixelFormat; -use profile_traits::time::{self as profile_time, ProfilerCategory, profile}; +use profile_traits::time::{self as profile_time, profile, ProfilerCategory}; +use script_traits::CompositorEvent::{MouseButtonEvent, MouseMoveEvent, TouchEvent}; use script_traits::{AnimationState, AnimationTickType, ConstellationMsg, LayoutControlMsg}; use script_traits::{MouseButton, MouseEventType, ScrollState, TouchEventType, TouchId}; use script_traits::{UntrustedNodeAddress, WindowSizeData, WindowSizeType}; -use script_traits::CompositorEvent::{MouseMoveEvent, MouseButtonEvent, TouchEvent}; use servo_channel::Sender; use servo_config::opts; use servo_geometry::DeviceIndependentPixel; use std::collections::HashMap; use std::env; -use std::fs::{File, create_dir_all}; +use std::fs::{create_dir_all, File}; use std::io::Write; use std::num::NonZeroU32; use std::rc::Rc; -use style_traits::{CSSPixel, DevicePixel, PinchZoomFactor}; use style_traits::cursor::CursorKind; use style_traits::viewport::ViewportConstraints; +use style_traits::{CSSPixel, DevicePixel, PinchZoomFactor}; use time::{now, precise_time_ns, precise_time_s}; use webrender; use webrender_api::{self, DeviceIntPoint, DevicePoint, HitTestFlags, HitTestResult}; @@ -498,7 +500,10 @@ impl IOCompositor { (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 +844,7 @@ impl IOCompositor { &mut self, delta: ScrollLocation, cursor: DeviceIntPoint, - phase: TouchEventType + phase: TouchEventType, ) { match phase { TouchEventType::Move => self.on_scroll_window_event(delta, cursor), @@ -852,11 +857,7 @@ impl IOCompositor { } } - 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 +1156,19 @@ impl IOCompositor { 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 +1260,7 @@ impl IOCompositor { 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 +1450,8 @@ impl IOCompositor { 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/compositing/compositor_thread.rs b/components/compositing/compositor_thread.rs index 3203c7aa290..a897f141fed 100644 --- a/components/compositing/compositor_thread.rs +++ b/components/compositing/compositor_thread.rs @@ -4,8 +4,8 @@ //! Communication with the compositor thread. -use crate::SendableFrameTree; use crate::compositor::CompositingReason; +use crate::SendableFrameTree; use embedder_traits::EventLoopWaker; use gfx_traits::Epoch; use ipc_channel::ipc::IpcSender; diff --git a/components/compositing/lib.rs b/components/compositing/lib.rs index 8b9e30c0d46..c631f39275e 100644 --- a/components/compositing/lib.rs +++ b/components/compositing/lib.rs @@ -29,10 +29,10 @@ extern crate time; extern crate webrender; extern crate webrender_api; -pub use crate::compositor_thread::CompositorProxy; pub use crate::compositor::IOCompositor; pub use crate::compositor::RenderNotifier; pub use crate::compositor::ShutdownState; +pub use crate::compositor_thread::CompositorProxy; use euclid::TypedSize2D; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; diff --git a/components/compositing/touch.rs b/components/compositing/touch.rs index 28a2588a91f..227758ddd11 100644 --- a/components/compositing/touch.rs +++ b/components/compositing/touch.rs @@ -2,10 +2,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use euclid::{TypedPoint2D, TypedVector2D}; -use euclid::TypedScale; -use script_traits::{EventResult, TouchId}; use self::TouchState::*; +use euclid::TypedScale; +use euclid::{TypedPoint2D, TypedVector2D}; +use script_traits::{EventResult, TouchId}; use style_traits::DevicePixel; /// Minimum number of `DeviceIndependentPixel` to begin touch scrolling. diff --git a/components/compositing/windowing.rs b/components/compositing/windowing.rs index 45351780133..9ff7e919746 100644 --- a/components/compositing/windowing.rs +++ b/components/compositing/windowing.rs @@ -17,7 +17,7 @@ use std::fmt::{Debug, Error, Formatter}; #[cfg(feature = "gleam")] use std::rc::Rc; use style_traits::DevicePixel; -use webrender_api::{DeviceIntPoint, DevicePoint, DeviceUintSize, DeviceUintRect, ScrollLocation}; +use webrender_api::{DeviceIntPoint, DevicePoint, DeviceUintRect, DeviceUintSize, ScrollLocation}; #[derive(Clone)] pub enum MouseWindowEvent { diff --git a/components/config/opts.rs b/components/config/opts.rs index e066432680b..264938b20d1 100644 --- a/components/config/opts.rs +++ b/components/config/opts.rs @@ -19,7 +19,7 @@ use std::fs::{self, File}; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use std::process; -use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; +use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; use url::{self, Url}; /// Global flags for Servo, currently set on the command line. @@ -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..5b47a1a51a7 100644 --- a/components/config/prefs.rs +++ b/components/config/prefs.rs @@ -11,7 +11,7 @@ use std::borrow::ToOwned; use std::cmp::max; use std::collections::HashMap; use std::fs::File; -use std::io::{Read, Write, stderr}; +use std::io::{stderr, Read, Write}; use std::path::PathBuf; use std::sync::{Arc, RwLock}; @@ -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/config/tests/opts.rs b/components/config/tests/opts.rs index e2db853a991..3e427074823 100644 --- a/components/config/tests/opts.rs +++ b/components/config/tests/opts.rs @@ -4,7 +4,7 @@ extern crate servo_config; -use servo_config::opts::{parse_url_or_filename, parse_pref_from_command_line}; +use servo_config::opts::{parse_pref_from_command_line, parse_url_or_filename}; use servo_config::prefs::{PrefValue, PREFS}; use std::path::Path; diff --git a/components/config/tests/prefs.rs b/components/config/tests/prefs.rs index 823b03b76c2..ee3916b7f5a 100644 --- a/components/config/tests/prefs.rs +++ b/components/config/tests/prefs.rs @@ -5,7 +5,7 @@ extern crate servo_config; use servo_config::basedir; -use servo_config::prefs::{PREFS, PrefValue, read_prefs}; +use servo_config::prefs::{read_prefs, PrefValue, PREFS}; use std::fs::{self, File}; use std::io::{Read, Write}; diff --git a/components/constellation/constellation.rs b/components/constellation/constellation.rs index 32aaa3a1106..668aa0aae27 100644 --- a/components/constellation/constellation.rs +++ b/components/constellation/constellation.rs @@ -96,49 +96,61 @@ use canvas::webgl_thread::WebGLThreads; use canvas_traits::canvas::CanvasId; use canvas_traits::canvas::CanvasMsg; use clipboard::{ClipboardContext, ClipboardProvider}; -use compositing::SendableFrameTree; use compositing::compositor_thread::CompositorProxy; use compositing::compositor_thread::Msg as ToCompositorMsg; -use crate::browsingcontext::{AllBrowsingContextsIterator, BrowsingContext, FullyActiveBrowsingContextsIterator}; +use compositing::SendableFrameTree; use crate::browsingcontext::NewBrowsingContextInfo; +use crate::browsingcontext::{ + AllBrowsingContextsIterator, BrowsingContext, FullyActiveBrowsingContextsIterator, +}; use crate::event_loop::EventLoop; use crate::network_listener::NetworkListener; use crate::pipeline::{InitialPipelineState, Pipeline}; -use crate::session_history::{JointSessionHistory, NeedsToReload, SessionHistoryChange, SessionHistoryDiff}; +use crate::session_history::{ + JointSessionHistory, NeedsToReload, SessionHistoryChange, SessionHistoryDiff, +}; use crate::timer_scheduler::TimerScheduler; use debugger; use devtools_traits::{ChromeToDevtoolsControlMsg, DevtoolsControlMsg}; use embedder_traits::{EmbedderMsg, EmbedderProxy}; -use euclid::{Size2D, TypedSize2D, TypedScale}; +use euclid::{Size2D, TypedScale, TypedSize2D}; use gfx::font_cache_thread::FontCacheThread; use gfx_traits::Epoch; -use ipc_channel::{Error as IpcError}; -use ipc_channel::ipc::{self, IpcSender, IpcReceiver}; +use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use ipc_channel::router::ROUTER; +use ipc_channel::Error as IpcError; use keyboard_types::KeyboardEvent; use layout_traits::LayoutThreadFactory; -use log::{Log, Level, LevelFilter, Metadata, Record}; -use msg::constellation_msg::{BrowsingContextId, PipelineId, HistoryStateId, TopLevelBrowsingContextId}; +use log::{Level, LevelFilter, Log, Metadata, Record}; +use msg::constellation_msg::{ + BrowsingContextId, HistoryStateId, PipelineId, TopLevelBrowsingContextId, +}; use msg::constellation_msg::{PipelineNamespace, PipelineNamespaceId, TraversalDirection}; -use net_traits::{self, IpcSend, FetchResponseMsg, ResourceThreads}; use net_traits::pub_domains::reg_host; use net_traits::request::RequestInit; use net_traits::storage_thread::{StorageThreadMsg, StorageType}; +use net_traits::{self, FetchResponseMsg, IpcSend, ResourceThreads}; use profile_traits::mem; use profile_traits::time; -use script_traits::{AnimationState, AuxiliaryBrowsingContextLoadInfo, AnimationTickType, CompositorEvent}; -use script_traits::{ConstellationControlMsg, ConstellationMsg as FromCompositorMsg, DiscardBrowsingContext}; +use script_traits::{webdriver_msg, LogEntry, ScriptToConstellationChan, ServiceWorkerMsg}; +use script_traits::{ + AnimationState, AnimationTickType, AuxiliaryBrowsingContextLoadInfo, CompositorEvent, +}; +use script_traits::{ + ConstellationControlMsg, ConstellationMsg as FromCompositorMsg, DiscardBrowsingContext, +}; use script_traits::{DocumentActivity, DocumentState, LayoutControlMsg, LoadData}; -use script_traits::{IFrameLoadInfo, IFrameLoadInfoWithData, IFrameSandboxState, TimerSchedulerMsg}; +use script_traits::{ + IFrameLoadInfo, IFrameLoadInfoWithData, IFrameSandboxState, TimerSchedulerMsg, +}; use script_traits::{LayoutMsg as FromLayoutMsg, ScriptMsg as FromScriptMsg, ScriptThreadFactory}; -use script_traits::{LogEntry, ScriptToConstellationChan, ServiceWorkerMsg, webdriver_msg}; use script_traits::{SWManagerMsg, ScopeThings, UpdatePipelineIdReason, WebDriverCommandMsg}; use script_traits::{WindowSizeData, WindowSizeType}; use serde::{Deserialize, Serialize}; -use servo_channel::{Receiver, Sender, channel}; +use servo_channel::{channel, Receiver, Sender}; use servo_config::opts; use servo_config::prefs::PREFS; -use servo_rand::{Rng, SeedableRng, ServoRng, random}; +use servo_rand::{random, Rng, SeedableRng, ServoRng}; use servo_remutex::ReentrantMutex; use servo_url::{Host, ImmutableOrigin, ServoUrl}; use std::borrow::ToOwned; @@ -149,9 +161,9 @@ use std::process; use std::rc::{Rc, Weak}; use std::sync::Arc; use std::thread; -use style_traits::CSSPixel; use style_traits::cursor::CursorKind; use style_traits::viewport::ViewportConstraints; +use style_traits::CSSPixel; use webrender_api; use webvr_traits::{WebVREvent, WebVRMsg}; @@ -718,9 +730,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 +866,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 +878,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 +1244,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 +1664,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 +1681,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 +1747,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 +1809,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 +1823,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 +1853,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 +1911,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 +1961,11 @@ where }); } - fn handle_script_new_auxiliary(&mut self, - load_info: AuxiliaryBrowsingContextLoadInfo, - layout_sender: IpcSender) { + fn handle_script_new_auxiliary( + &mut self, + load_info: AuxiliaryBrowsingContextLoadInfo, + layout_sender: IpcSender, + ) { let AuxiliaryBrowsingContextLoadInfo { opener_pipeline_id, new_top_level_browsing_context_id, @@ -1942,19 +1982,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 +2009,7 @@ where self.compositor_proxy.clone(), url, is_opener_visible, - load_data + load_data, ); (pipeline, is_opener_private, is_opener_visible) @@ -1974,10 +2017,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 +2144,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 +2493,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 +2697,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 +2818,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 +2833,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 +2917,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 +3352,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 +3447,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 +3697,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 +3818,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 +3906,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::() { - return; + Some((ref mut rng, probability)) => { + if probability <= rng.gen::() { + return; + } }, _ => return, }; @@ -3881,7 +3945,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/event_loop.rs b/components/constellation/event_loop.rs index 7506e029570..ac8c06c2997 100644 --- a/components/constellation/event_loop.rs +++ b/components/constellation/event_loop.rs @@ -6,8 +6,8 @@ //! view of a script thread. When an `EventLoop` is dropped, an `ExitScriptThread` //! message is sent to the script thread, asking it to shut down. -use ipc_channel::Error; use ipc_channel::ipc::IpcSender; +use ipc_channel::Error; use script_traits::ConstellationControlMsg; use std::marker::PhantomData; use std::rc::Rc; diff --git a/components/constellation/lib.rs b/components/constellation/lib.rs index c2446ebca4c..54235a9b09c 100644 --- a/components/constellation/lib.rs +++ b/components/constellation/lib.rs @@ -53,7 +53,9 @@ mod sandboxing; mod session_history; mod timer_scheduler; -pub use crate::constellation::{Constellation, FromCompositorLogger, FromScriptLogger, InitialConstellationState}; +pub use crate::constellation::{ + Constellation, FromCompositorLogger, FromScriptLogger, InitialConstellationState, +}; pub use crate::pipeline::UnprivilegedPipelineContent; #[cfg(all(not(target_os = "windows"), not(target_os = "ios")))] pub use crate::sandboxing::content_process_sandbox_profile; diff --git a/components/constellation/network_listener.rs b/components/constellation/network_listener.rs index 457a2021ced..a417f5cdeeb 100644 --- a/components/constellation/network_listener.rs +++ b/components/constellation/network_listener.rs @@ -11,10 +11,10 @@ use ipc_channel::ipc; use ipc_channel::router::ROUTER; use msg::constellation_msg::PipelineId; use net::http_loader::{set_default_accept, set_default_accept_language}; -use net_traits::{CoreResourceMsg, FetchChannels, FetchMetadata, FetchResponseMsg}; -use net_traits::{IpcSend, NetworkError, ResourceThreads}; use net_traits::request::{Destination, RequestInit}; use net_traits::response::ResponseInit; +use net_traits::{CoreResourceMsg, FetchChannels, FetchMetadata, FetchResponseMsg}; +use net_traits::{IpcSend, NetworkError, ResourceThreads}; use servo_channel::Sender; pub struct NetworkListener { @@ -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..881e290164a 100644 --- a/components/constellation/pipeline.rs +++ b/components/constellation/pipeline.rs @@ -4,23 +4,23 @@ use bluetooth_traits::BluetoothRequest; use canvas_traits::webgl::WebGLPipeline; +use compositing::compositor_thread::Msg as CompositorMsg; use compositing::CompositionPipeline; use compositing::CompositorProxy; -use compositing::compositor_thread::Msg as CompositorMsg; use crate::event_loop::EventLoop; use devtools_traits::{DevtoolsControlMsg, ScriptToDevtoolsControlMsg}; -use euclid::{TypedSize2D, TypedScale}; +use euclid::{TypedScale, TypedSize2D}; use gfx::font_cache_thread::FontCacheThread; -use ipc_channel::Error; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use ipc_channel::router::ROUTER; +use ipc_channel::Error; use layout_traits::LayoutThreadFactory; use metrics::PaintTimeMetrics; -use msg::constellation_msg::{BrowsingContextId, HistoryStateId, PipelineId, PipelineNamespaceId}; use msg::constellation_msg::TopLevelBrowsingContextId; +use msg::constellation_msg::{BrowsingContextId, HistoryStateId, PipelineId, PipelineNamespaceId}; use net::image_cache::ImageCacheImpl; -use net_traits::{IpcSend, ResourceThreads}; use net_traits::image_cache::ImageCache; +use net_traits::{IpcSend, ResourceThreads}; use profile_traits::mem as profile_mem; use profile_traits::time; use script_traits::{ConstellationControlMsg, DiscardBrowsingContext, ScriptToConstellationChan}; @@ -30,7 +30,7 @@ use script_traits::{NewLayoutInfo, SWManagerMsg, SWManagerSenders}; use script_traits::{ScriptThreadFactory, TimerSchedulerMsg, WindowSizeData}; use servo_channel::Sender; use servo_config::opts::{self, Opts}; -use servo_config::prefs::{PREFS, Pref}; +use servo_config::prefs::{Pref, PREFS}; use servo_url::ServoUrl; use std::collections::{HashMap, HashSet}; #[cfg(not(windows))] @@ -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/constellation/session_history.rs b/components/constellation/session_history.rs index 996fe59fc85..ae467432bf8 100644 --- a/components/constellation/session_history.rs +++ b/components/constellation/session_history.rs @@ -3,11 +3,13 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::browsingcontext::NewBrowsingContextInfo; -use msg::constellation_msg::{BrowsingContextId, HistoryStateId, PipelineId, TopLevelBrowsingContextId}; +use msg::constellation_msg::{ + BrowsingContextId, HistoryStateId, PipelineId, TopLevelBrowsingContextId, +}; use script_traits::LoadData; use servo_url::ServoUrl; -use std::{fmt, mem}; use std::cmp::PartialEq; +use std::{fmt, mem}; /// Represents the joint session history /// https://html.spec.whatwg.org/multipage/#joint-session-history 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..f2841d86f27 100644 --- a/components/devtools/actors/console.rs +++ b/components/devtools/actors/console.rs @@ -10,10 +10,10 @@ use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; use crate::actors::object::ObjectActor; use crate::protocol::JsonPacketStream; -use devtools_traits::{CachedConsoleMessageTypes, DevtoolScriptControlMsg}; use devtools_traits::CachedConsoleMessage; use devtools_traits::EvaluateJSReply::{ActorValue, BooleanValue, StringValue}; use devtools_traits::EvaluateJSReply::{NullValue, NumberValue, VoidValue}; +use devtools_traits::{CachedConsoleMessageTypes, DevtoolScriptControlMsg}; use ipc_channel::ipc::{self, IpcSender}; use msg::constellation_msg::PipelineId; use serde_json::{self, Map, Number, Value}; @@ -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::(&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..93f87168d09 100644 --- a/components/devtools/actors/device.rs +++ b/components/devtools/actors/device.rs @@ -3,8 +3,8 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; -use crate::protocol::{ActorDescription, Method}; use crate::protocol::JsonPacketStream; +use crate::protocol::{ActorDescription, Method}; use serde_json::{Map, Value}; use std::net::TcpStream; @@ -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..b18e2647f61 100644 --- a/components/devtools/actors/inspector.rs +++ b/components/devtools/actors/inspector.rs @@ -7,9 +7,9 @@ use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; use crate::protocol::JsonPacketStream; -use devtools_traits::{ComputedNodeLayout, DevtoolScriptControlMsg, NodeInfo}; use devtools_traits::DevtoolScriptControlMsg::{GetChildren, GetDocumentElement, GetRootNode}; use devtools_traits::DevtoolScriptControlMsg::{GetLayout, ModifyAttribute}; +use devtools_traits::{ComputedNodeLayout, DevtoolScriptControlMsg, NodeInfo}; use ipc_channel::ipc::{self, IpcSender}; use msg::constellation_msg::PipelineId; use serde_json::{self, Map, Value}; @@ -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, status: Option<(StatusCode, String)>, - body: Option> + body: Option>, } 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::() { 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::() { 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..e1ad44d1ee5 100644 --- a/components/devtools/actors/timeline.rs +++ b/components/devtools/actors/timeline.rs @@ -6,9 +6,9 @@ use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; use crate::actors::framerate::FramerateActor; use crate::actors::memory::{MemoryActor, TimelineMemoryReply}; use crate::protocol::JsonPacketStream; -use devtools_traits::{PreciseTime, TimelineMarker, TimelineMarkerType}; use devtools_traits::DevtoolScriptControlMsg; use devtools_traits::DevtoolScriptControlMsg::{DropTimelineMarkers, SetTimelineMarkers}; +use devtools_traits::{PreciseTime, TimelineMarker, TimelineMarkerType}; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use msg::constellation_msg::PipelineId; use serde::{Serialize, Serializer}; @@ -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..be40e70eec6 100644 --- a/components/devtools/lib.rs +++ b/components/devtools/lib.rs @@ -48,11 +48,11 @@ use devtools_traits::{DevtoolScriptControlMsg, DevtoolsPageInfo, LogLevel, Netwo use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId}; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; -use servo_channel::{Receiver, Sender, channel}; +use servo_channel::{channel, Receiver, Sender}; use std::borrow::ToOwned; use std::cell::RefCell; -use std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; +use std::collections::HashMap; use std::net::{Shutdown, TcpListener, TcpStream}; use std::sync::{Arc, Mutex}; use std::thread; @@ -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::(actor_name).console.clone()) } else { let actor_name = (*actor_pipelines).get(&id)?; - Some(actors.find::(actor_name).console.clone()) + Some( + actors + .find::(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/devtools_traits/lib.rs b/components/devtools_traits/lib.rs index 9d95adb3d26..dc0979f580c 100644 --- a/components/devtools_traits/lib.rs +++ b/components/devtools_traits/lib.rs @@ -24,8 +24,8 @@ extern crate serde; extern crate servo_url; extern crate time; -use http::HeaderMap; use http::method::Method; +use http::HeaderMap; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; use servo_url::ServoUrl; 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/fallible/lib.rs b/components/fallible/lib.rs index ae6a40dc789..f807bc9ce7a 100644 --- a/components/fallible/lib.rs +++ b/components/fallible/lib.rs @@ -5,9 +5,9 @@ extern crate hashglobe; extern crate smallvec; -use hashglobe::FailedAllocationError; #[cfg(feature = "known_system_malloc")] use hashglobe::alloc; +use hashglobe::FailedAllocationError; use smallvec::Array; use smallvec::SmallVec; use std::vec::Vec; diff --git a/components/gfx/font.rs b/components/gfx/font.rs index 18a8ed21e11..5971d0ed130 100644 --- a/components/gfx/font.rs +++ b/components/gfx/font.rs @@ -9,9 +9,9 @@ use crate::platform::font::{FontHandle, FontTable}; use crate::platform::font_context::FontContextHandle; pub use crate::platform::font_list::fallback_font_families; use crate::platform::font_template::FontTemplateData; -use crate::text::Shaper; use crate::text::glyph::{ByteIndex, GlyphData, GlyphId, GlyphStore}; use crate::text::shaping::ShaperMethods; +use crate::text::Shaper; use euclid::{Point2D, Rect, Size2D}; use ordered_float::NotNan; use servo_atoms::Atom; @@ -22,8 +22,8 @@ use std::collections::HashMap; use std::iter; use std::rc::Rc; use std::str; +use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use std::sync::Arc; -use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering}; use style::computed_values::{font_stretch, font_style, font_variant_caps, font_weight}; use style::properties::style_structs::Font as FontStyleStruct; use style::values::computed::font::SingleFontFamily; @@ -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..77a816db9b9 100644 --- a/components/gfx/font_cache_thread.rs +++ b/components/gfx/font_cache_thread.rs @@ -7,22 +7,22 @@ use crate::font::{FontFamilyDescriptor, FontFamilyName, FontSearchScope}; use crate::font_context::FontSource; use crate::font_template::{FontTemplate, FontTemplateDescriptor}; use crate::platform::font_context::FontContextHandle; -use crate::platform::font_list::SANS_SERIF_FONT_FAMILY; use crate::platform::font_list::for_each_available_family; use crate::platform::font_list::for_each_variation; use crate::platform::font_list::system_default_family; +use crate::platform::font_list::SANS_SERIF_FONT_FAMILY; use crate::platform::font_template::FontTemplateData; use fontsan; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; -use net_traits::{CoreResourceThread, FetchResponseMsg, fetch_async}; use net_traits::request::{Destination, RequestInit}; +use net_traits::{fetch_async, CoreResourceThread, FetchResponseMsg}; use servo_atoms::Atom; use servo_url::ServoUrl; -use std::{fmt, f32, mem, thread}; use std::borrow::ToOwned; use std::collections::HashMap; use std::ops::Deref; use std::sync::{Arc, Mutex}; +use std::{f32, fmt, mem, thread}; use style::font_face::{EffectiveSources, Source}; use style::values::computed::font::FamilyName; use webrender_api; @@ -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..2fc8ee6a1f8 100644 --- a/components/gfx/font_context.rs +++ b/components/gfx/font_context.rs @@ -3,7 +3,9 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use app_units::Au; -use crate::font::{Font, FontDescriptor, FontFamilyDescriptor, FontGroup, FontHandleMethods, FontRef}; +use crate::font::{ + Font, FontDescriptor, FontFamilyDescriptor, FontGroup, FontHandleMethods, FontRef, +}; use crate::font_cache_thread::FontTemplateInfo; use crate::font_template::FontTemplateDescriptor; use crate::platform::font::FontHandle; @@ -133,7 +135,8 @@ impl FontContext { .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..d4b422ef111 100644 --- a/components/gfx/platform/freetype/android/font_list.rs +++ b/components/gfx/platform/freetype/android/font_list.rs @@ -8,11 +8,11 @@ use std::fs::File; use std::io::{self, Read}; use std::path::Path; use ucd::{Codepoint, UnicodeBlock}; -use xml5ever::Attribute; use xml5ever::driver::parse_document; use xml5ever::rcdom::*; use xml5ever::rcdom::{Node, RcDom}; use xml5ever::tendril::TendrilSink; +use xml5ever::Attribute; lazy_static! { static ref FONT_LIST: FontList = FontList::new(); @@ -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..ab315b7cc02 100644 --- a/components/gfx/platform/freetype/font.rs +++ b/components/gfx/platform/freetype/font.rs @@ -2,6 +2,7 @@ * 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/. */ +use super::c_str_to_string; use app_units::Au; use crate::font::{FontHandleMethods, FontMetrics, FontTableMethods}; use crate::font::{FontTableTag, FractionalPixel, GPOS, GSUB, KERN}; @@ -9,6 +10,7 @@ use crate::platform::font_context::FontContextHandle; use crate::platform::font_template::FontTemplateData; use crate::text::glyph::GlyphId; use crate::text::util::fixed_to_float; +use freetype::freetype::FT_Sfnt_Tag; use freetype::freetype::{FT_Done_Face, FT_New_Face, FT_New_Memory_Face}; use freetype::freetype::{FT_F26Dot6, FT_Face, FT_FaceRec}; use freetype::freetype::{FT_Get_Char_Index, FT_Get_Postscript_Name}; @@ -17,18 +19,16 @@ use freetype::freetype::{FT_GlyphSlot, FT_Library, FT_Long, FT_ULong}; use freetype::freetype::{FT_Int32, FT_Kerning_Mode, FT_STYLE_FLAG_ITALIC}; use freetype::freetype::{FT_Load_Glyph, FT_Set_Char_Size}; use freetype::freetype::{FT_SizeRec, FT_Size_Metrics, FT_UInt, FT_Vector}; -use freetype::freetype::FT_Sfnt_Tag; use freetype::succeeded; use freetype::tt_os2::TT_OS2; use servo_atoms::Atom; -use std::{mem, ptr}; use std::ffi::CString; use std::os::raw::{c_char, c_long}; use std::sync::Arc; +use std::{mem, ptr}; use style::computed_values::font_stretch::T as FontStretch; use style::computed_values::font_weight::T as FontWeight; use style::values::computed::font::FontStyle; -use super::c_str_to_string; // This constant is not present in the freetype // bindings due to bindgen not handling the way @@ -216,7 +216,8 @@ impl FontHandleMethods for FontHandle { } } else { FontStretchKeyword::Normal - }.compute(); + } + .compute(); FontStretch(NonNegative(percentage)) } diff --git a/components/gfx/platform/freetype/font_context.rs b/components/gfx/platform/freetype/font_context.rs index dbc8816efc5..2da91cf5008 100644 --- a/components/gfx/platform/freetype/font_context.rs +++ b/components/gfx/platform/freetype/font_context.rs @@ -10,7 +10,7 @@ use freetype::freetype::FT_MemoryRec_; use freetype::freetype::FT_New_Library; use freetype::succeeded; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; -use servo_allocator::libc_compat::{malloc, realloc, free}; +use servo_allocator::libc_compat::{free, malloc, realloc}; use servo_allocator::usable_size; use std::os::raw::{c_long, c_void}; use std::ptr; diff --git a/components/gfx/platform/freetype/font_list.rs b/components/gfx/platform/freetype/font_list.rs index 71b7e9bc4e0..e285a4eee58 100644 --- a/components/gfx/platform/freetype/font_list.rs +++ b/components/gfx/platform/freetype/font_list.rs @@ -2,18 +2,20 @@ * 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/. */ +use super::c_str_to_string; use crate::text::util::is_cjk; use fontconfig::fontconfig::{FcChar8, FcResultMatch, FcSetSystem}; use fontconfig::fontconfig::{FcConfigGetCurrent, FcConfigGetFonts, FcConfigSubstitute}; use fontconfig::fontconfig::{FcDefaultSubstitute, FcFontMatch, FcNameParse, FcPatternGetString}; use fontconfig::fontconfig::{FcFontSetDestroy, FcMatchPattern, FcPatternCreate, FcPatternDestroy}; -use fontconfig::fontconfig::{FcFontSetList, FcObjectSetCreate, FcObjectSetDestroy, FcPatternAddString}; +use fontconfig::fontconfig::{ + FcFontSetList, FcObjectSetCreate, FcObjectSetDestroy, FcPatternAddString, +}; use fontconfig::fontconfig::{FcObjectSetAdd, FcPatternGetInteger}; use libc; use libc::{c_char, c_int}; use std::ffi::CString; use std::ptr; -use super::c_str_to_string; static FC_FAMILY: &'static [u8] = b"family\0"; static FC_FILE: &'static [u8] = b"file\0"; diff --git a/components/gfx/platform/freetype/font_template.rs b/components/gfx/platform/freetype/font_template.rs index 674739b69ce..90bb5677167 100644 --- a/components/gfx/platform/freetype/font_template.rs +++ b/components/gfx/platform/freetype/font_template.rs @@ -5,7 +5,7 @@ use servo_atoms::Atom; use std::fmt; use std::fs::File; -use std::io::{Read, Error}; +use std::io::{Error, Read}; use webrender_api::NativeFontHandle; /// Platform specific font representation for Linux. @@ -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..a27cc2a7c43 100644 --- a/components/gfx/platform/macos/font.rs +++ b/components/gfx/platform/macos/font.rs @@ -11,17 +11,19 @@ use core_foundation::string::UniChar; use core_graphics::font::CGGlyph; use core_graphics::geometry::CGRect; use core_text::font::CTFont; -use core_text::font_descriptor::{SymbolicTraitAccessors, TraitAccessors}; use core_text::font_descriptor::kCTFontDefaultOrientation; -use crate::font::{FontHandleMethods, FontMetrics, FontTableMethods, FontTableTag, FractionalPixel}; +use core_text::font_descriptor::{SymbolicTraitAccessors, TraitAccessors}; +use crate::font::{ + FontHandleMethods, FontMetrics, FontTableMethods, FontTableTag, FractionalPixel, +}; use crate::font::{GPOS, GSUB, KERN}; use crate::platform::font_template::FontTemplateData; use crate::platform::macos::font_context::FontContextHandle; use crate::text::glyph::GlyphId; use servo_atoms::Atom; -use std::{fmt, ptr}; use std::ops::Range; use std::sync::Arc; +use std::{fmt, ptr}; use style::values::computed::font::{FontStretch, FontStyle, FontWeight}; const KERN_PAIR_LEN: usize = 6; @@ -236,8 +238,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..ea6bd57e413 100644 --- a/components/gfx/platform/macos/font_template.rs +++ b/components/gfx/platform/macos/font_template.rs @@ -7,15 +7,15 @@ use core_graphics::data_provider::CGDataProvider; use core_graphics::font::CGFont; use core_text; use core_text::font::CTFont; -use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde::de::{Error, Visitor}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; use servo_atoms::Atom; use servo_url::ServoUrl; use std::borrow::ToOwned; use std::collections::HashMap; use std::fmt; use std::fs::File; -use std::io::{Read, Error as IoError}; +use std::io::{Error as IoError, Read}; use std::ops::Deref; use std::sync::{Arc, Mutex}; use webrender_api::NativeFontHandle; @@ -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 9fb075aa027..b654b47e0cb 100644 --- a/components/gfx/platform/windows/font.rs +++ b/components/gfx/platform/windows/font.rs @@ -23,8 +23,8 @@ use std::sync::Arc; use style::computed_values::font_stretch::T as StyleFontStretch; use style::computed_values::font_weight::T as StyleFontWeight; use style::values::computed::font::FontStyle as StyleFontStyle; -use style::values::generics::NonNegative; use style::values::generics::font::FontStyle as GenericFontStyle; +use style::values::generics::NonNegative; use style::values::specified::font::FontStretchKeyword; use truetype; @@ -119,7 +119,7 @@ struct FontInfo { impl FontInfo { fn new_from_face(face: &FontFace) -> Result { - use std::cmp::{min, max}; + use std::cmp::{max, min}; use std::io::Cursor; use truetype::{NamingTable, Value, WindowsMetrics}; @@ -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_list.rs b/components/gfx/platform/windows/font_list.rs index 21e47aa76e6..ac58f7c91d4 100644 --- a/components/gfx/platform/windows/font_list.rs +++ b/components/gfx/platform/windows/font_list.rs @@ -3,11 +3,11 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::text::util::unicode_plane; -use dwrote::{Font, FontDescriptor, FontCollection}; +use dwrote::{Font, FontCollection, FontDescriptor}; use servo_atoms::Atom; use std::collections::HashMap; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; -use std::sync::atomic::{Ordering, AtomicUsize}; use ucd::{Codepoint, UnicodeBlock}; lazy_static! { 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..d4dea69597d 100644 --- a/components/gfx/tests/font_context.rs +++ b/components/gfx/tests/font_context.rs @@ -10,8 +10,10 @@ extern crate style; extern crate webrender_api; use app_units::Au; -use gfx::font::{fallback_font_families, FontDescriptor, FontFamilyDescriptor, FontFamilyName, FontSearchScope}; -use gfx::font_cache_thread::{FontTemplates, FontTemplateInfo}; +use gfx::font::{ + fallback_font_families, FontDescriptor, FontFamilyDescriptor, FontFamilyName, FontSearchScope, +}; +use gfx::font_cache_thread::{FontTemplateInfo, FontTemplates}; use gfx::font_context::{FontContext, FontContextHandle, FontSource}; use gfx::font_template::FontTemplateDescriptor; use servo_arc::Arc; @@ -24,7 +26,9 @@ use std::path::PathBuf; use std::rc::Rc; use style::properties::longhands::font_variant_caps::computed_value::T as FontVariantCaps; use style::properties::style_structs::Font as FontStyleStruct; -use style::values::computed::font::{FamilyName, FamilyNameSyntax, FontFamily, FontFamilyList, FontSize}; +use style::values::computed::font::{ + FamilyName, FamilyNameSyntax, FontFamily, FontFamilyList, FontSize, +}; use style::values::computed::font::{FontStretch, FontWeight, SingleFontFamily}; use style::values::generics::font::FontStyle; @@ -119,7 +123,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..8d1935f738d 100644 --- a/components/gfx/tests/font_template.rs +++ b/components/gfx/tests/font_template.rs @@ -19,10 +19,10 @@ fn test_font_template_descriptor() { use std::fs::File; use std::io::prelude::*; use std::path::PathBuf; - use style::values::computed::Percentage; use style::values::computed::font::{FontStretch, FontWeight}; - use style::values::generics::NonNegative; + use style::values::computed::Percentage; use style::values::generics::font::FontStyle; + use style::values::generics::NonNegative; fn descriptor(filename: &str) -> FontTemplateDescriptor { let mut path: PathBuf = [ @@ -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/tests/text_util.rs b/components/gfx/tests/text_util.rs index 0b8132e9c88..c35a06a2e2f 100644 --- a/components/gfx/tests/text_util.rs +++ b/components/gfx/tests/text_util.rs @@ -4,7 +4,7 @@ extern crate gfx; -use gfx::text::util::{CompressionMode, transform_text}; +use gfx::text::util::{transform_text, CompressionMode}; #[test] fn test_transform_compress_none() { diff --git a/components/gfx/text/glyph.rs b/components/gfx/text/glyph.rs index 8e4c56e309b..d7029e86225 100644 --- a/components/gfx/text/glyph.rs +++ b/components/gfx/text/glyph.rs @@ -10,9 +10,9 @@ use euclid::Point2D; ))] use packed_simd::u32x4; use range::{self, EachIndex, Range, RangeIndex}; -use std::{fmt, mem, u16}; use std::cmp::{Ordering, PartialOrd}; use std::vec::Vec; +use std::{fmt, mem, u16}; pub use gfx_traits::ByteIndex; @@ -223,16 +223,15 @@ impl<'a> DetailedGlyphStore { entry_offset, glyphs ); - /* 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) - } - */ + // 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) + // } self.detail_lookup.push(entry); self.detail_buffer.extend_from_slice(glyphs); @@ -541,7 +540,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/shaping/harfbuzz.rs b/components/gfx/text/shaping/harfbuzz.rs index 343c27c63c9..675c57b4615 100644 --- a/components/gfx/text/shaping/harfbuzz.rs +++ b/components/gfx/text/shaping/harfbuzz.rs @@ -5,15 +5,7 @@ #![allow(unsafe_code)] use app_units::Au; -use crate::font::{ShapingFlags, Font, FontTableMethods, FontTableTag, ShapingOptions, KERN}; -use crate::harfbuzz::{HB_DIRECTION_LTR, HB_DIRECTION_RTL, HB_MEMORY_MODE_READONLY}; -use crate::harfbuzz::{hb_blob_create, hb_face_create_for_tables}; -use crate::harfbuzz::{hb_buffer_create, hb_font_destroy}; -use crate::harfbuzz::{hb_buffer_get_glyph_infos, hb_shape}; -use crate::harfbuzz::{hb_buffer_set_direction, hb_buffer_set_script}; -use crate::harfbuzz::{hb_buffer_t, hb_codepoint_t, hb_font_funcs_t}; -use crate::harfbuzz::{hb_face_t, hb_font_t}; -use crate::harfbuzz::{hb_position_t, hb_tag_t}; +use crate::font::{Font, FontTableMethods, FontTableTag, ShapingFlags, ShapingOptions, KERN}; use crate::harfbuzz::hb_blob_t; use crate::harfbuzz::hb_bool_t; use crate::harfbuzz::hb_buffer_add_utf8; @@ -32,13 +24,21 @@ use crate::harfbuzz::hb_font_set_ppem; use crate::harfbuzz::hb_font_set_scale; use crate::harfbuzz::hb_glyph_info_t; use crate::harfbuzz::hb_glyph_position_t; +use crate::harfbuzz::{hb_blob_create, hb_face_create_for_tables}; +use crate::harfbuzz::{hb_buffer_create, hb_font_destroy}; +use crate::harfbuzz::{hb_buffer_get_glyph_infos, hb_shape}; +use crate::harfbuzz::{hb_buffer_set_direction, hb_buffer_set_script}; +use crate::harfbuzz::{hb_buffer_t, hb_codepoint_t, hb_font_funcs_t}; +use crate::harfbuzz::{hb_face_t, hb_font_t}; +use crate::harfbuzz::{hb_position_t, hb_tag_t}; +use crate::harfbuzz::{HB_DIRECTION_LTR, HB_DIRECTION_RTL, HB_MEMORY_MODE_READONLY}; use crate::platform::font::FontTable; use crate::text::glyph::{ByteIndex, GlyphData, GlyphId, GlyphStore}; use crate::text::shaping::ShaperMethods; use crate::text::util::{fixed_to_float, float_to_fixed, is_bidi_control}; use euclid::Point2D; -use std::{char, cmp, ptr}; use std::os::raw::{c_char, c_int, c_uint, c_void}; +use std::{char, cmp, ptr}; const NO_GLYPH: i32 = -1; const LIGA: u32 = ot_tag!('l', 'i', 'g', 'a'); diff --git a/components/gfx/text/text_run.rs b/components/gfx/text/text_run.rs index 7a6e6623b9c..40e8aaf2427 100644 --- a/components/gfx/text/text_run.rs +++ b/components/gfx/text/text_run.rs @@ -9,7 +9,7 @@ use crate::platform::font_template::FontTemplateData; use crate::text::glyph::{ByteIndex, GlyphStore}; use range::Range; use std::cell::Cell; -use std::cmp::{Ordering, max}; +use std::cmp::{max, Ordering}; use std::slice::Iter; use std::sync::Arc; use style::str::char_is_whitespace; @@ -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/gfx_traits/lib.rs b/components/gfx_traits/lib.rs index 457814abddf..308c01cd279 100644 --- a/components/gfx_traits/lib.rs +++ b/components/gfx_traits/lib.rs @@ -17,7 +17,7 @@ extern crate serde; pub mod print_tree; use range::RangeIndex; -use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; /// A newtype struct for denoting the age of messages; prevents race conditions. #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] diff --git a/components/hashglobe/src/fake.rs b/components/hashglobe/src/fake.rs index c5cd9d39bb7..d2cdd549e48 100644 --- a/components/hashglobe/src/fake.rs +++ b/components/hashglobe/src/fake.rs @@ -20,8 +20,8 @@ use std::fmt; use std::hash::{BuildHasher, Hash}; use std::ops::{Deref, DerefMut}; -pub use std::collections::hash_map::{Entry, RandomState, Iter as MapIter, IterMut as MapIterMut}; -pub use std::collections::hash_set::{Iter as SetIter, IntoIter as SetIntoIter}; +pub use std::collections::hash_map::{Entry, Iter as MapIter, IterMut as MapIterMut, RandomState}; +pub use std::collections::hash_set::{IntoIter as SetIntoIter, Iter as SetIter}; #[derive(Clone)] pub struct HashMap(StdMap); diff --git a/components/hashglobe/src/hash_map.rs b/components/hashglobe/src/hash_map.rs index 57ac9bcc049..03ade951e1e 100644 --- a/components/hashglobe/src/hash_map.rs +++ b/components/hashglobe/src/hash_map.rs @@ -15,13 +15,13 @@ use std::borrow::Borrow; use std::cmp::max; use std::fmt::{self, Debug}; #[allow(deprecated)] -use std::hash::{Hash, BuildHasher}; +use std::hash::{BuildHasher, Hash}; use std::iter::FromIterator; use std::mem::{self, replace}; use std::ops::{Deref, Index}; -use super::table::{self, Bucket, EmptyBucket, FullBucket, FullBucketMut, RawTable, SafeHash}; use super::table::BucketState::{Empty, Full}; +use super::table::{self, Bucket, EmptyBucket, FullBucket, FullBucketMut, RawTable, SafeHash}; use FailedAllocationError; @@ -2214,11 +2214,11 @@ fn assert_covariance() { #[cfg(test)] mod test_map { extern crate rand; - use super::HashMap; + use self::rand::{thread_rng, Rng}; use super::Entry::{Occupied, Vacant}; + use super::HashMap; use super::RandomState; use cell::RefCell; - use self::rand::{thread_rng, Rng}; #[test] fn test_zero_capacities() { diff --git a/components/hashglobe/src/hash_set.rs b/components/hashglobe/src/hash_set.rs index 34e657e44fc..694e01c46eb 100644 --- a/components/hashglobe/src/hash_set.rs +++ b/components/hashglobe/src/hash_set.rs @@ -10,12 +10,12 @@ use std::borrow::Borrow; use std::fmt; -use std::hash::{Hash, BuildHasher}; +use std::hash::{BuildHasher, Hash}; use std::iter::{Chain, FromIterator}; -use std::ops::{BitOr, BitAnd, BitXor, Sub}; +use std::ops::{BitAnd, BitOr, BitXor, Sub}; -use super::Recover; use super::hash_map::{self, HashMap, Keys, RandomState}; +use super::Recover; // Future Optimization (FIXME!) // ============================= @@ -1258,8 +1258,8 @@ fn assert_covariance() { #[cfg(test)] mod test_set { - use super::HashSet; use super::hash_map::RandomState; + use super::HashSet; #[test] fn test_zero_capacities() { diff --git a/components/hashglobe/src/table.rs b/components/hashglobe/src/table.rs index 0b8b49001e2..15e3394884f 100644 --- a/components/hashglobe/src/table.rs +++ b/components/hashglobe/src/table.rs @@ -9,13 +9,13 @@ // except according to those terms. use alloc::{alloc, dealloc}; +use shim::{Shared, Unique}; use std::cmp; use std::hash::{BuildHasher, Hash, Hasher}; use std::marker; use std::mem::{self, align_of, size_of}; use std::ops::{Deref, DerefMut}; use std::ptr; -use shim::{Unique, Shared}; use self::BucketState::*; use FailedAllocationError; diff --git a/components/layout/animation.rs b/components/layout/animation.rs index c9c83744361..2a2b49d9715 100644 --- a/components/layout/animation.rs +++ b/components/layout/animation.rs @@ -11,10 +11,10 @@ use crate::opaque_node::OpaqueNodeMethods; use fxhash::FxHashMap; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; -use script_traits::{AnimationState, ConstellationControlMsg, LayoutMsg as ConstellationMsg}; use script_traits::UntrustedNodeAddress; +use script_traits::{AnimationState, ConstellationControlMsg, LayoutMsg as ConstellationMsg}; use servo_channel::Receiver; -use style::animation::{Animation, update_style_for_animation}; +use style::animation::{update_style_for_animation, Animation}; use style::dom::TElement; use style::font_metrics::ServoMetricsProvider; use style::selector_parser::RestyleDamage; @@ -89,7 +89,10 @@ pub fn update_animation_state( }, }; - 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( } 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( .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..9fbd7434ea9 100644 --- a/components/layout/block.rs +++ b/components/layout/block.rs @@ -27,18 +27,26 @@ use app_units::{Au, MAX_AU}; use crate::context::LayoutContext; +use crate::display_list::items::DisplayListSection; +use crate::display_list::StackingContextCollectionState; use crate::display_list::{BlockFlowDisplayListBuilding, BorderPaintingMode}; use crate::display_list::{DisplayListBuildState, StackingContextCollectionFlags}; -use crate::display_list::StackingContextCollectionState; -use crate::display_list::items::DisplayListSection; use crate::floats::{ClearType, FloatKind, Floats, PlacementInfo}; -use crate::flow::{BaseFlow, EarlyAbsolutePositionInfo, Flow, FlowClass, ForceNonfloatedFlag, GetBaseFlow}; -use crate::flow::{ImmutableFlowUtils, LateAbsolutePositionInfo, OpaqueFlow, FragmentationContext, FlowFlags}; +use crate::flow::{ + BaseFlow, EarlyAbsolutePositionInfo, Flow, FlowClass, ForceNonfloatedFlag, GetBaseFlow, +}; +use crate::flow::{ + FlowFlags, FragmentationContext, ImmutableFlowUtils, LateAbsolutePositionInfo, OpaqueFlow, +}; use crate::flow_list::FlowList; -use crate::fragment::{CoordinateSystem, Fragment, FragmentBorderBoxIterator, Overflow, FragmentFlags}; +use crate::fragment::{ + CoordinateSystem, Fragment, FragmentBorderBoxIterator, FragmentFlags, Overflow, +}; use crate::incremental::RelayoutMode; use crate::layout_debug; -use crate::model::{AdjoiningMargins, CollapsibleMargins, IntrinsicISizes, MarginCollapseInfo, MaybeAuto}; +use crate::model::{ + AdjoiningMargins, CollapsibleMargins, IntrinsicISizes, MarginCollapseInfo, MaybeAuto, +}; use crate::sequential; use crate::traversal::PreorderFlowTraversal; use euclid::{Point2D, Rect, SideOffsets2D, Size2D}; @@ -58,8 +66,8 @@ use style::context::SharedStyleContext; use style::logical_geometry::{LogicalMargin, LogicalPoint, LogicalRect, LogicalSize, WritingMode}; use style::properties::ComputedValues; use style::servo::restyle_damage::ServoRestyleDamage; -use style::values::computed::{LengthOrPercentageOrNone, LengthOrPercentage}; use style::values::computed::LengthOrPercentageOrAuto; +use style::values::computed::{LengthOrPercentage, LengthOrPercentageOrNone}; /// Information specific to floated blocks. #[derive(Clone, Serialize)] @@ -1334,7 +1342,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 +1370,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 +2636,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..ee0e0ee451a 100644 --- a/components/layout/construct.rs +++ b/components/layout/construct.rs @@ -11,21 +11,28 @@ //! maybe it's an absolute or fixed position thing that hasn't found its containing block yet. //! Construction items bubble up the tree from children to parents until they find their homes. -use crate::ServoArc; use crate::block::BlockFlow; -use crate::context::{LayoutContext, with_thread_local_font_context}; -use crate::data::{LayoutDataFlags, LayoutData}; +use crate::context::{with_thread_local_font_context, LayoutContext}; +use crate::data::{LayoutData, LayoutDataFlags}; use crate::display_list::items::OpaqueNode; use crate::flex::FlexFlow; use crate::floats::FloatKind; use crate::flow::{AbsoluteDescendants, Flow, FlowClass, GetBaseFlow, ImmutableFlowUtils}; use crate::flow::{FlowFlags, MutableFlowUtils, MutableOwnedFlowUtils}; use crate::flow_ref::FlowRef; -use crate::fragment::{CanvasFragmentInfo, Fragment, FragmentFlags, GeneratedContentInfo, IframeFragmentInfo}; -use crate::fragment::{ImageFragmentInfo, InlineAbsoluteFragmentInfo, InlineAbsoluteHypotheticalFragmentInfo}; -use crate::fragment::{InlineBlockFragmentInfo, MediaFragmentInfo, SpecificFragmentInfo, SvgFragmentInfo}; -use crate::fragment::{TableColumnFragmentInfo, UnscannedTextFragmentInfo, WhitespaceStrippingResult}; -use crate::inline::{InlineFlow, InlineFragmentNodeInfo, InlineFragmentNodeFlags}; +use crate::fragment::{ + CanvasFragmentInfo, Fragment, FragmentFlags, GeneratedContentInfo, IframeFragmentInfo, +}; +use crate::fragment::{ + ImageFragmentInfo, InlineAbsoluteFragmentInfo, InlineAbsoluteHypotheticalFragmentInfo, +}; +use crate::fragment::{ + InlineBlockFragmentInfo, MediaFragmentInfo, SpecificFragmentInfo, SvgFragmentInfo, +}; +use crate::fragment::{ + TableColumnFragmentInfo, UnscannedTextFragmentInfo, WhitespaceStrippingResult, +}; +use crate::inline::{InlineFlow, InlineFragmentNodeFlags, InlineFragmentNodeInfo}; use crate::linked_list::prepend_from; use crate::list_item::{ListItemFlow, ListStyleTypeContent}; use crate::multicol::{MulticolColumnFlow, MulticolFlow}; @@ -40,15 +47,18 @@ use crate::table_wrapper::TableWrapperFlow; use crate::text::TextRunScanner; use crate::traversal::PostorderNodeMutTraversal; use crate::wrapper::{LayoutNodeLayoutData, TextContent, ThreadSafeLayoutNodeHelpers}; -use script_layout_interface::{LayoutElementType, LayoutNodeType, is_image_data}; -use script_layout_interface::wrapper_traits::{PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode}; +use crate::ServoArc; +use script_layout_interface::wrapper_traits::{ + PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode, +}; +use script_layout_interface::{is_image_data, LayoutElementType, LayoutNodeType}; use servo_config::opts; use servo_url::ServoUrl; use std::collections::LinkedList; use std::marker::PhantomData; use std::mem; -use std::sync::Arc; use std::sync::atomic::Ordering; +use std::sync::Arc; use style::computed_values::caption_side::T as CaptionSide; use style::computed_values::display::T as Display; use style::computed_values::empty_cells::T as EmptyCells; @@ -185,7 +195,8 @@ impl InlineBlockSplit { predecessors: mem::replace( fragment_accumulator, InlineFragmentsAccumulator::from_inline_node(node, style_context), - ).to_intermediate_inline_fragments::(style_context), + ) + .to_intermediate_inline_fragments::(style_context), flow: flow, }; @@ -402,7 +413,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/context.rs b/components/layout/context.rs index 134a3cedec1..1ab4637cd8a 100644 --- a/components/layout/context.rs +++ b/components/layout/context.rs @@ -4,7 +4,7 @@ //! Data needed by the layout thread. -use crate::display_list::items::{WebRenderImageInfo, OpaqueNode}; +use crate::display_list::items::{OpaqueNode, WebRenderImageInfo}; use crate::opaque_node::OpaqueNodeMethods; use fnv::FnvHasher; use gfx::font_cache_thread::FontCacheThread; diff --git a/components/layout/display_list/background.rs b/components/layout/display_list/background.rs index 23e519f1c1d..a8d0cebde12 100644 --- a/components/layout/display_list/background.rs +++ b/components/layout/display_list/background.rs @@ -13,8 +13,8 @@ use style::computed_values::background_clip::single_value::T as BackgroundClip; use style::computed_values::background_origin::single_value::T as BackgroundOrigin; use style::properties::style_structs::Background; use style::values::computed::{BackgroundSize, LengthOrPercentageOrAuto}; -use style::values::generics::NonNegative; use style::values::generics::background::BackgroundSize as GenericBackgroundSize; +use style::values::generics::NonNegative; use style::values::specified::background::BackgroundRepeatKeyword; use webrender_api::BorderRadius; diff --git a/components/layout/display_list/border.rs b/components/layout/display_list/border.rs index f32f5a84399..a70fc2bb452 100644 --- a/components/layout/display_list/border.rs +++ b/components/layout/display_list/border.rs @@ -9,14 +9,14 @@ use crate::display_list::ToLayout; use euclid::{Rect, SideOffsets2D, Size2D}; use style::computed_values::border_image_outset::T as BorderImageOutset; use style::properties::style_structs::Border; -use style::values::Either; +use style::values::computed::NumberOrPercentage; use style::values::computed::{BorderCornerRadius, BorderImageWidth}; use style::values::computed::{BorderImageSideWidth, LengthOrNumber}; -use style::values::computed::NumberOrPercentage; -use style::values::generics::border::{BorderImageSideWidth as GenericBorderImageSideWidth}; +use style::values::generics::border::BorderImageSideWidth as GenericBorderImageSideWidth; use style::values::generics::rect::Rect as StyleRect; +use style::values::Either; use webrender_api::{BorderRadius, BorderSide, BorderStyle, ColorF}; -use webrender_api::{LayoutSize, LayoutSideOffsets, NormalBorder}; +use webrender_api::{LayoutSideOffsets, LayoutSize, NormalBorder}; /// Computes a border radius size against the containing size. /// diff --git a/components/layout/display_list/builder.rs b/components/layout/display_list/builder.rs index 2d99900eac2..a57f9292bb1 100644 --- a/components/layout/display_list/builder.rs +++ b/components/layout/display_list/builder.rs @@ -12,31 +12,31 @@ use app_units::{Au, AU_PER_PX}; use canvas_traits::canvas::{CanvasMsg, FromLayoutMsg}; use crate::block::BlockFlow; use crate::context::LayoutContext; -use crate::display_list::ToLayout; use crate::display_list::background::{self, get_cyclic}; use crate::display_list::border; use crate::display_list::gradient; -use crate::display_list::items::{BaseDisplayItem, BLUR_INFLATION_FACTOR, ClipScrollNode}; +use crate::display_list::items::{BaseDisplayItem, ClipScrollNode, BLUR_INFLATION_FACTOR}; use crate::display_list::items::{ClipScrollNodeIndex, ClipScrollNodeType, ClippingAndScrolling}; use crate::display_list::items::{ClippingRegion, DisplayItem, DisplayItemMetadata, DisplayList}; -use crate::display_list::items::{DisplayListSection, CommonDisplayItem}; +use crate::display_list::items::{CommonDisplayItem, DisplayListSection}; use crate::display_list::items::{IframeDisplayItem, OpaqueNode}; use crate::display_list::items::{PopAllTextShadowsDisplayItem, PushTextShadowDisplayItem}; use crate::display_list::items::{StackingContext, StackingContextType, StickyFrameData}; use crate::display_list::items::{TextOrientation, WebRenderImageInfo}; +use crate::display_list::ToLayout; use crate::flex::FlexFlow; use crate::flow::{BaseFlow, Flow, FlowFlags}; use crate::flow_ref::FlowRef; -use crate::fragment::{CanvasFragmentSource, CoordinateSystem, Fragment, ScannedTextFragmentInfo}; use crate::fragment::SpecificFragmentInfo; +use crate::fragment::{CanvasFragmentSource, CoordinateSystem, Fragment, ScannedTextFragmentInfo}; use crate::inline::{InlineFlow, InlineFragmentNodeFlags}; use crate::list_item::ListItemFlow; use crate::model::MaybeAuto; use crate::table_cell::CollapsedBordersForCell; use euclid::{rect, Point2D, Rect, SideOffsets2D, Size2D, TypedSize2D, Vector2D}; use fnv::FnvHashMap; -use gfx::text::TextRun; use gfx::text::glyph::ByteIndex; +use gfx::text::TextRun; use gfx_traits::{combine_id_with_fragment_type, FragmentType, StackingContextId}; use ipc_channel::ipc; use msg::constellation_msg::{BrowsingContextId, PipelineId}; @@ -56,20 +56,20 @@ use style::computed_values::visibility::T as Visibility; use style::logical_geometry::{LogicalMargin, LogicalPoint, LogicalRect}; use style::properties::{style_structs, ComputedValues}; use style::servo::restyle_damage::ServoRestyleDamage; -use style::values::{Either, RGBA}; -use style::values::computed::Gradient; use style::values::computed::effects::SimpleShadow; use style::values::computed::image::Image as ComputedImage; +use style::values::computed::Gradient; use style::values::generics::background::BackgroundSize; use style::values::generics::image::{GradientKind, Image, PaintWorklet}; use style::values::generics::ui::Cursor; +use style::values::{Either, RGBA}; +use style_traits::cursor::CursorKind; use style_traits::CSSPixel; use style_traits::ToCss; -use style_traits::cursor::CursorKind; use webrender_api::{self, BorderDetails, BorderRadius, BorderSide, BoxShadowClipMode, ColorF}; use webrender_api::{ExternalScrollId, FilterOp, GlyphInstance, ImageRendering, LayoutRect}; use webrender_api::{LayoutSize, LayoutTransform, LayoutVector2D, LineStyle, NinePatchBorder}; -use webrender_api::{NinePatchBorderSource, NormalBorder, StickyOffsetBounds, ScrollSensitivity}; +use webrender_api::{NinePatchBorderSource, NormalBorder, ScrollSensitivity, StickyOffsetBounds}; fn establishes_containing_block_for_absolute( flags: StackingContextCollectionFlags, diff --git a/components/layout/display_list/conversions.rs b/components/layout/display_list/conversions.rs index a40dadb0eb9..39c67253915 100644 --- a/components/layout/display_list/conversions.rs +++ b/components/layout/display_list/conversions.rs @@ -7,10 +7,10 @@ use euclid::{Point2D, Rect, SideOffsets2D, Size2D, Vector2D}; use style::computed_values::image_rendering::T as ImageRendering; use style::computed_values::mix_blend_mode::T as MixBlendMode; use style::computed_values::transform_style::T as TransformStyle; -use style::values::RGBA; use style::values::computed::{BorderStyle, Filter}; use style::values::generics::effects::Filter as GenericFilter; use style::values::specified::border::BorderImageRepeatKeyword; +use style::values::RGBA; use webrender_api as wr; pub trait ToLayout { diff --git a/components/layout/display_list/gradient.rs b/components/layout/display_list/gradient.rs index 70f53cce024..5ce61f84615 100644 --- a/components/layout/display_list/gradient.rs +++ b/components/layout/display_list/gradient.rs @@ -8,11 +8,11 @@ use app_units::Au; use crate::display_list::ToLayout; use euclid::{Point2D, Size2D, Vector2D}; use style::properties::ComputedValues; -use style::values::computed::{Angle, GradientItem, LengthOrPercentage, Percentage, Position}; use style::values::computed::image::{EndingShape, LineDirection}; -use style::values::generics::image::{Circle, Ellipse, ShapeExtent}; +use style::values::computed::{Angle, GradientItem, LengthOrPercentage, Percentage, Position}; use style::values::generics::image::EndingShape as GenericEndingShape; use style::values::generics::image::GradientItem as GenericGradientItem; +use style::values::generics::image::{Circle, Ellipse, ShapeExtent}; use style::values::specified::position::{X, Y}; use webrender_api::{ExtendMode, Gradient, GradientBuilder, GradientStop, RadialGradient}; diff --git a/components/layout/display_list/items.rs b/components/layout/display_list/items.rs index 13de1360737..f07099c5b07 100644 --- a/components/layout/display_list/items.rs +++ b/components/layout/display_list/items.rs @@ -13,8 +13,8 @@ //! low-level drawing primitives. use euclid::{SideOffsets2D, TypedRect, Vector2D}; -use gfx_traits::{self, StackingContextId}; use gfx_traits::print_tree::PrintTree; +use gfx_traits::{self, StackingContextId}; use msg::constellation_msg::PipelineId; use net_traits::image::base::Image; use servo_geometry::MaxRect; @@ -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..42cf2c454fe 100644 --- a/components/layout/flex.rs +++ b/components/layout/flex.rs @@ -7,10 +7,10 @@ use app_units::{Au, MAX_AU}; use crate::block::{AbsoluteAssignBSizesTraversal, BlockFlow, MarginsMayCollapseFlag}; use crate::context::LayoutContext; -use crate::display_list::{DisplayListBuildState, FlexFlowDisplayListBuilding}; use crate::display_list::StackingContextCollectionState; +use crate::display_list::{DisplayListBuildState, FlexFlowDisplayListBuilding}; use crate::floats::FloatKind; -use crate::flow::{Flow, FlowClass, GetBaseFlow, ImmutableFlowUtils, OpaqueFlow, FlowFlags}; +use crate::flow::{Flow, FlowClass, FlowFlags, GetBaseFlow, ImmutableFlowUtils, OpaqueFlow}; use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; use crate::layout_debug; use crate::model::{AdjoiningMargins, CollapsibleMargins}; @@ -27,8 +27,10 @@ use style::computed_values::justify_content::T as JustifyContent; use style::logical_geometry::{Direction, LogicalSize}; use style::properties::ComputedValues; use style::servo::restyle_damage::ServoRestyleDamage; -use style::values::computed::{LengthOrPercentage, LengthOrPercentageOrAuto, LengthOrPercentageOrNone}; use style::values::computed::flex::FlexBasis; +use style::values::computed::{ + LengthOrPercentage, LengthOrPercentageOrAuto, LengthOrPercentageOrNone, +}; use style::values::generics::flex::FlexBasis as GenericFlexBasis; /// The size of an axis. May be a specified size, a min/max @@ -922,7 +924,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/flow.rs b/components/layout/flow.rs index aa6b1b1e79d..fea1c94f89d 100644 --- a/components/layout/flow.rs +++ b/components/layout/flow.rs @@ -28,8 +28,8 @@ use app_units::Au; use crate::block::{BlockFlow, FormattingContextType}; use crate::context::LayoutContext; -use crate::display_list::{DisplayListBuildState, StackingContextCollectionState}; use crate::display_list::items::ClippingAndScrolling; +use crate::display_list::{DisplayListBuildState, StackingContextCollectionState}; use crate::flex::FlexFlow; use crate::floats::{Floats, SpeculatedFloatPlacement}; use crate::flow_list::{FlowList, FlowListIterator, MutFlowListIterator}; @@ -46,16 +46,16 @@ use crate::table_colgroup::TableColGroupFlow; use crate::table_row::TableRowFlow; use crate::table_rowgroup::TableRowGroupFlow; use crate::table_wrapper::TableWrapperFlow; -use euclid::{Point2D, Vector2D, Rect, Size2D}; -use gfx_traits::StackingContextId; +use euclid::{Point2D, Rect, Size2D, Vector2D}; use gfx_traits::print_tree::PrintTree; +use gfx_traits::StackingContextId; use serde::ser::{Serialize, SerializeStruct, Serializer}; use servo_geometry::{au_rect_to_f32_rect, f32_rect_to_au_rect, MaxRect}; use std::fmt; use std::iter::Zip; use std::slice::IterMut; -use std::sync::Arc; use std::sync::atomic::Ordering; +use std::sync::Arc; use style::computed_values::clear::T as Clear; use style::computed_values::float::T as Float; use style::computed_values::overflow_x::T as StyleOverflow; diff --git a/components/layout/flow_list.rs b/components/layout/flow_list.rs index ca6fffe627b..c24734a5a7d 100644 --- a/components/layout/flow_list.rs +++ b/components/layout/flow_list.rs @@ -5,8 +5,8 @@ use crate::flow::{Flow, FlowClass}; use crate::flow_ref::FlowRef; use serde::ser::{Serialize, SerializeSeq, Serializer}; -use serde_json::{Map, Value, to_value}; -use std::collections::{LinkedList, linked_list}; +use serde_json::{to_value, Map, Value}; +use std::collections::{linked_list, LinkedList}; use std::ops::Deref; use std::sync::Arc; diff --git a/components/layout/fragment.rs b/components/layout/fragment.rs index 7774a4a9014..37a23807e82 100644 --- a/components/layout/fragment.rs +++ b/components/layout/fragment.rs @@ -5,24 +5,24 @@ //! The `Fragment` type, which represents the leaves of the layout tree. use app_units::Au; -use canvas_traits::canvas::{CanvasMsg, CanvasId}; -use crate::ServoArc; -use crate::context::{LayoutContext, with_thread_local_font_context}; +use canvas_traits::canvas::{CanvasId, CanvasMsg}; +use crate::context::{with_thread_local_font_context, LayoutContext}; +use crate::display_list::items::{ClipScrollNodeIndex, OpaqueNode, BLUR_INFLATION_FACTOR}; use crate::display_list::ToLayout; -use crate::display_list::items::{BLUR_INFLATION_FACTOR, ClipScrollNodeIndex, OpaqueNode}; use crate::floats::ClearType; use crate::flow::{GetBaseFlow, ImmutableFlowUtils}; use crate::flow_ref::FlowRef; -use crate::inline::{InlineFragmentNodeFlags, InlineFragmentContext, InlineFragmentNodeInfo}; +use crate::inline::{InlineFragmentContext, InlineFragmentNodeFlags, InlineFragmentNodeInfo}; use crate::inline::{InlineMetrics, LineMetrics}; #[cfg(debug_assertions)] use crate::layout_debug; -use crate::model::{self, IntrinsicISizes, IntrinsicISizesContribution, MaybeAuto, SizeConstraint}; use crate::model::style_length; +use crate::model::{self, IntrinsicISizes, IntrinsicISizesContribution, MaybeAuto, SizeConstraint}; use crate::text; use crate::text::TextRunScanner; use crate::wrapper::ThreadSafeLayoutNodeHelpers; -use euclid::{Point2D, Vector2D, Rect, Size2D}; +use crate::ServoArc; +use euclid::{Point2D, Rect, Size2D, Vector2D}; use gfx; use gfx::text::glyph::ByteIndex; use gfx::text::text_run::{TextRun, TextRunSlice}; @@ -32,15 +32,17 @@ use msg::constellation_msg::{BrowsingContextId, PipelineId}; use net_traits::image::base::{Image, ImageMetadata}; use net_traits::image_cache::{ImageOrMetadataAvailable, UsePlaceholder}; use range::*; +use script_layout_interface::wrapper_traits::{ + PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode, +}; use script_layout_interface::{HTMLCanvasData, HTMLCanvasDataSource, HTMLMediaData, SVGSVGData}; -use script_layout_interface::wrapper_traits::{PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode}; use serde::ser::{Serialize, SerializeStruct, Serializer}; use servo_url::ServoUrl; -use std::{f32, fmt}; use std::borrow::ToOwned; -use std::cmp::{Ordering, max, min}; +use std::cmp::{max, min, Ordering}; use std::collections::LinkedList; use std::sync::{Arc, Mutex}; +use std::{f32, fmt}; use style::computed_values::border_collapse::T as BorderCollapse; use style::computed_values::box_sizing::T as BoxSizing; use style::computed_values::clear::T as Clear; @@ -59,8 +61,8 @@ use style::properties::ComputedValues; use style::selector_parser::RestyleDamage; use style::servo::restyle_damage::ServoRestyleDamage; use style::str::char_is_whitespace; -use style::values::computed::{Length, LengthOrPercentage, LengthOrPercentageOrAuto}; use style::values::computed::counters::ContentItem; +use style::values::computed::{Length, LengthOrPercentage, LengthOrPercentageOrAuto}; use style::values::generics::box_::{Perspective, VerticalAlign}; use style::values::generics::transform; use webrender_api::{self, LayoutTransform}; @@ -416,23 +418,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 +459,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 +1017,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 +1047,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 +1179,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 +3182,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/generated_content.rs b/components/layout/generated_content.rs index f7a2836e036..024d51b22fb 100644 --- a/components/layout/generated_content.rs +++ b/components/layout/generated_content.rs @@ -8,10 +8,12 @@ //! done in parallel and is therefore a sequential pass that runs on as little of the flow tree //! as possible. -use crate::context::{LayoutContext, with_thread_local_font_context}; +use crate::context::{with_thread_local_font_context, LayoutContext}; use crate::display_list::items::OpaqueNode; use crate::flow::{Flow, FlowFlags, GetBaseFlow, ImmutableFlowUtils}; -use crate::fragment::{Fragment, GeneratedContentInfo, SpecificFragmentInfo, UnscannedTextFragmentInfo}; +use crate::fragment::{ + Fragment, GeneratedContentInfo, SpecificFragmentInfo, UnscannedTextFragmentInfo, +}; use crate::text::TextRunScanner; use crate::traversal::InorderFlowTraversal; use script_layout_interface::wrapper_traits::PseudoElementType; diff --git a/components/layout/incremental.rs b/components/layout/incremental.rs index b0b4ec51437..6734620e5a0 100644 --- a/components/layout/incremental.rs +++ b/components/layout/incremental.rs @@ -2,7 +2,7 @@ * 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/. */ -use crate::flow::{FlowFlags, Flow, GetBaseFlow}; +use crate::flow::{Flow, FlowFlags, GetBaseFlow}; use style::computed_values::float::T as Float; use style::selector_parser::RestyleDamage; use style::servo::restyle_damage::ServoRestyleDamage; diff --git a/components/layout/inline.rs b/components/layout/inline.rs index 8093f3c9eeb..08a371bac08 100644 --- a/components/layout/inline.rs +++ b/components/layout/inline.rs @@ -3,32 +3,32 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use app_units::{Au, MIN_AU}; -use crate::ServoArc; use crate::block::AbsoluteAssignBSizesTraversal; use crate::context::{LayoutContext, LayoutFontContext}; -use crate::display_list::{DisplayListBuildState, InlineFlowDisplayListBuilding}; -use crate::display_list::StackingContextCollectionState; use crate::display_list::items::OpaqueNode; +use crate::display_list::StackingContextCollectionState; +use crate::display_list::{DisplayListBuildState, InlineFlowDisplayListBuilding}; use crate::floats::{FloatKind, Floats, PlacementInfo}; use crate::flow::{BaseFlow, Flow, FlowClass, ForceNonfloatedFlag}; -use crate::flow::{FlowFlags, EarlyAbsolutePositionInfo, GetBaseFlow, OpaqueFlow}; +use crate::flow::{EarlyAbsolutePositionInfo, FlowFlags, GetBaseFlow, OpaqueFlow}; use crate::flow_ref::FlowRef; -use crate::fragment::{CoordinateSystem, Fragment, FragmentBorderBoxIterator, Overflow}; use crate::fragment::FragmentFlags; use crate::fragment::SpecificFragmentInfo; +use crate::fragment::{CoordinateSystem, Fragment, FragmentBorderBoxIterator, Overflow}; use crate::layout_debug; use crate::model::IntrinsicISizesContribution; use crate::text; use crate::traversal::PreorderFlowTraversal; +use crate::ServoArc; use euclid::{Point2D, Size2D}; use gfx::font::FontMetrics; use gfx_traits::print_tree::PrintTree; use range::{Range, RangeIndex}; use script_layout_interface::wrapper_traits::PseudoElementType; -use std::{fmt, i32, isize, mem}; use std::cmp::max; use std::collections::VecDeque; use std::sync::Arc; +use std::{fmt, i32, isize, mem}; use style::computed_values::display::T as Display; use style::computed_values::overflow_x::T as StyleOverflow; use style::computed_values::position::T as Position; @@ -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/layout_debug.rs b/components/layout/layout_debug.rs index 88bae7be23c..dec9d49def5 100644 --- a/components/layout/layout_debug.rs +++ b/components/layout/layout_debug.rs @@ -13,7 +13,7 @@ use std::cell::RefCell; use std::fs::File; use std::io::Write; #[cfg(debug_assertions)] -use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; thread_local!(static STATE_KEY: RefCell> = RefCell::new(None)); diff --git a/components/layout/lib.rs b/components/layout/lib.rs index 725ad09061f..b91ee22eba8 100644 --- a/components/layout/lib.rs +++ b/components/layout/lib.rs @@ -87,9 +87,9 @@ pub mod traversal; pub mod wrapper; // For unit tests: +pub use self::data::LayoutData; pub use crate::fragment::Fragment; pub use crate::fragment::SpecificFragmentInfo; -pub use self::data::LayoutData; // We can't use servo_arc for everything in layout, because the Flow stuff uses // weak references. diff --git a/components/layout/list_item.rs b/components/layout/list_item.rs index 002651918f3..cef1487f2f0 100644 --- a/components/layout/list_item.rs +++ b/components/layout/list_item.rs @@ -7,13 +7,15 @@ use app_units::Au; use crate::block::BlockFlow; -use crate::context::{LayoutContext, with_thread_local_font_context}; -use crate::display_list::{DisplayListBuildState, ListItemFlowDisplayListBuilding}; +use crate::context::{with_thread_local_font_context, LayoutContext}; use crate::display_list::StackingContextCollectionState; +use crate::display_list::{DisplayListBuildState, ListItemFlowDisplayListBuilding}; use crate::floats::FloatKind; use crate::flow::{Flow, FlowClass, OpaqueFlow}; -use crate::fragment::{CoordinateSystem, Fragment, FragmentBorderBoxIterator, GeneratedContentInfo}; use crate::fragment::Overflow; +use crate::fragment::{ + CoordinateSystem, Fragment, FragmentBorderBoxIterator, GeneratedContentInfo, +}; use crate::generated_content; use crate::inline::InlineFlow; use euclid::Point2D; @@ -257,7 +259,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..3fba3e27fba 100644 --- a/components/layout/model.rs +++ b/components/layout/model.rs @@ -11,8 +11,8 @@ use std::cmp::{max, min}; use std::fmt; use style::logical_geometry::{LogicalMargin, WritingMode}; use style::properties::ComputedValues; -use style::values::computed::{LengthOrPercentageOrAuto, LengthOrPercentage}; use style::values::computed::LengthOrPercentageOrNone; +use style::values::computed::{LengthOrPercentage, LengthOrPercentageOrAuto}; /// A collapsible margin. See CSS 2.1 § 8.3.1. #[derive(Clone, Copy, Debug)] @@ -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..71d9befac61 100644 --- a/components/layout/multicol.rs +++ b/components/layout/multicol.rs @@ -5,23 +5,23 @@ //! CSS Multi-column layout http://dev.w3.org/csswg/css-multicol/ use app_units::Au; -use crate::ServoArc; use crate::block::BlockFlow; use crate::context::LayoutContext; use crate::display_list::{DisplayListBuildState, StackingContextCollectionState}; use crate::floats::FloatKind; -use crate::flow::{Flow, FlowClass, OpaqueFlow, FragmentationContext, GetBaseFlow}; +use crate::flow::{Flow, FlowClass, FragmentationContext, GetBaseFlow, OpaqueFlow}; use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; +use crate::ServoArc; use euclid::{Point2D, Vector2D}; use gfx_traits::print_tree::PrintTree; -use std::cmp::{min, max}; +use std::cmp::{max, min}; use std::fmt; use std::sync::Arc; use style::logical_geometry::LogicalSize; use style::properties::ComputedValues; -use style::values::Either; use style::values::computed::{LengthOrPercentageOrAuto, LengthOrPercentageOrNone}; use style::values::generics::column::ColumnCount; +use style::values::Either; #[allow(unsafe_code)] unsafe impl crate::flow::HasBaseFlow for MulticolFlow {} @@ -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/parallel.rs b/components/layout/parallel.rs index 1587e957007..f510851ce92 100644 --- a/components/layout/parallel.rs +++ b/components/layout/parallel.rs @@ -14,7 +14,7 @@ use crate::flow::{Flow, GetBaseFlow}; use crate::flow_ref::FlowRef; use crate::traversal::{AssignBSizes, AssignISizes, BubbleISizes}; use crate::traversal::{PostorderFlowTraversal, PreorderFlowTraversal}; -use profile_traits::time::{self, TimerMetadata, profile}; +use profile_traits::time::{self, profile, TimerMetadata}; use rayon; use servo_config::opts; use smallvec::SmallVec; diff --git a/components/layout/query.rs b/components/layout/query.rs index eb94e9c0449..7a6a85824ed 100644 --- a/components/layout/query.rs +++ b/components/layout/query.rs @@ -7,27 +7,29 @@ use app_units::Au; use crate::construct::ConstructionResult; use crate::context::LayoutContext; -use crate::display_list::IndexableText; use crate::display_list::items::{DisplayList, OpaqueNode, ScrollOffsetMap}; +use crate::display_list::IndexableText; use crate::flow::{Flow, GetBaseFlow}; use crate::fragment::{Fragment, FragmentBorderBoxIterator, SpecificFragmentInfo}; use crate::inline::InlineFragmentNodeFlags; use crate::opaque_node::OpaqueNodeMethods; use crate::sequential; use crate::wrapper::LayoutNodeLayoutData; -use euclid::{Point2D, Vector2D, Rect, Size2D}; +use euclid::{Point2D, Rect, Size2D, Vector2D}; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; -use script_layout_interface::{LayoutElementType, LayoutNodeType}; -use script_layout_interface::StyleData; +use script_layout_interface::rpc::TextIndexResponse; use script_layout_interface::rpc::{ContentBoxResponse, ContentBoxesResponse, LayoutRPC}; use script_layout_interface::rpc::{NodeGeometryResponse, NodeScrollIdResponse}; use script_layout_interface::rpc::{OffsetParentResponse, ResolvedStyleResponse, StyleResponse}; -use script_layout_interface::rpc::TextIndexResponse; -use script_layout_interface::wrapper_traits::{LayoutNode, ThreadSafeLayoutElement, ThreadSafeLayoutNode}; +use script_layout_interface::wrapper_traits::{ + LayoutNode, ThreadSafeLayoutElement, ThreadSafeLayoutNode, +}; +use script_layout_interface::StyleData; +use script_layout_interface::{LayoutElementType, LayoutNodeType}; use script_traits::LayoutMsg as ConstellationMsg; use script_traits::UntrustedNodeAddress; -use std::cmp::{min, max}; +use std::cmp::{max, min}; use std::ops::Deref; use std::sync::{Arc, Mutex}; use style::computed_values::display::T as Display; @@ -35,8 +37,8 @@ use style::computed_values::position::T as Position; use style::computed_values::visibility::T as Visibility; use style::context::{StyleContext, ThreadLocalStyleContext}; use style::dom::TElement; -use style::logical_geometry::{WritingMode, BlockFlowDirection, InlineBaseDirection}; -use style::properties::{style_structs, PropertyId, PropertyDeclarationId, LonghandId}; +use style::logical_geometry::{BlockFlowDirection, InlineBaseDirection, WritingMode}; +use style::properties::{style_structs, LonghandId, PropertyDeclarationId, PropertyId}; use style::selector_parser::PseudoElement; use style_traits::ToCss; use webrender_api::ExternalScrollId; @@ -603,7 +605,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 +842,11 @@ where let applies = true; fn used_value_for_position_property( - layout_el: ::ConcreteThreadSafeLayoutElement, - layout_root: &mut Flow, - requested_node: N, - longhand_id: LonghandId, - ) -> String - { + layout_el: ::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/sequential.rs b/components/layout/sequential.rs index b35bba206b2..3203dee5e49 100644 --- a/components/layout/sequential.rs +++ b/components/layout/sequential.rs @@ -8,8 +8,8 @@ use app_units::Au; use crate::context::LayoutContext; use crate::display_list::{DisplayListBuildState, StackingContextCollectionState}; use crate::floats::SpeculatedFloatPlacement; -use crate::flow::{Flow, ImmutableFlowUtils, FlowFlags, GetBaseFlow}; -use crate::fragment::{FragmentBorderBoxIterator, CoordinateSystem}; +use crate::flow::{Flow, FlowFlags, GetBaseFlow, ImmutableFlowUtils}; +use crate::fragment::{CoordinateSystem, FragmentBorderBoxIterator}; use crate::generated_content::ResolveGeneratedContent; use crate::incremental::RelayoutMode; use crate::traversal::{AssignBSizes, AssignISizes, BubbleISizes, BuildDisplayList}; diff --git a/components/layout/table.rs b/components/layout/table.rs index f167f74911e..4f28b22e6f6 100644 --- a/components/layout/table.rs +++ b/components/layout/table.rs @@ -9,8 +9,13 @@ use crate::block::{BlockFlow, CandidateBSizeIterator, ISizeAndMarginsComputer}; use crate::block::{ISizeConstraintInput, ISizeConstraintSolution}; use crate::context::LayoutContext; use crate::display_list::{BlockFlowDisplayListBuilding, BorderPaintingMode}; -use crate::display_list::{DisplayListBuildState, StackingContextCollectionFlags, StackingContextCollectionState}; -use crate::flow::{BaseFlow, EarlyAbsolutePositionInfo, Flow, FlowClass, ImmutableFlowUtils, GetBaseFlow, OpaqueFlow}; +use crate::display_list::{ + DisplayListBuildState, StackingContextCollectionFlags, StackingContextCollectionState, +}; +use crate::flow::{ + BaseFlow, EarlyAbsolutePositionInfo, Flow, FlowClass, GetBaseFlow, ImmutableFlowUtils, + OpaqueFlow, +}; use crate::flow_list::{FlowListIterator, MutFlowListIterator}; use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; use crate::layout_debug; @@ -25,11 +30,11 @@ use std::{cmp, fmt}; use style::computed_values::{border_collapse, border_spacing, table_layout}; use style::context::SharedStyleContext; use style::logical_geometry::LogicalSize; -use style::properties::ComputedValues; use style::properties::style_structs::Background; +use style::properties::ComputedValues; use style::servo::restyle_damage::ServoRestyleDamage; -use style::values::CSSFloat; use style::values::computed::LengthOrPercentageOrAuto; +use style::values::CSSFloat; #[allow(unsafe_code)] unsafe impl crate::flow::HasBaseFlow for TableFlow {} 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_row.rs b/components/layout/table_row.rs index 15d660098bf..5b50b48448e 100644 --- a/components/layout/table_row.rs +++ b/components/layout/table_row.rs @@ -9,7 +9,9 @@ use crate::block::{BlockFlow, ISizeAndMarginsComputer}; use crate::context::LayoutContext; use crate::display_list::{BlockFlowDisplayListBuilding, DisplayListBuildState}; use crate::display_list::{StackingContextCollectionFlags, StackingContextCollectionState}; -use crate::flow::{EarlyAbsolutePositionInfo, Flow, FlowClass, ImmutableFlowUtils, GetBaseFlow, OpaqueFlow}; +use crate::flow::{ + EarlyAbsolutePositionInfo, Flow, FlowClass, GetBaseFlow, ImmutableFlowUtils, OpaqueFlow, +}; use crate::flow_list::MutFlowListIterator; use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; use crate::layout_debug; diff --git a/components/layout/table_wrapper.rs b/components/layout/table_wrapper.rs index 0d1596d9c85..ad6bee3b4e3 100644 --- a/components/layout/table_wrapper.rs +++ b/components/layout/table_wrapper.rs @@ -12,13 +12,17 @@ //! Hereafter this document is referred to as INTRINSIC. use app_units::Au; -use crate::block::{AbsoluteNonReplaced, BlockFlow, FloatNonReplaced, ISizeAndMarginsComputer, ISizeConstraintInput}; +use crate::block::{ + AbsoluteNonReplaced, BlockFlow, FloatNonReplaced, ISizeAndMarginsComputer, ISizeConstraintInput, +}; use crate::block::{ISizeConstraintSolution, MarginsMayCollapseFlag}; use crate::context::LayoutContext; -use crate::display_list::{BlockFlowDisplayListBuilding, DisplayListBuildState, StackingContextCollectionFlags}; use crate::display_list::StackingContextCollectionState; +use crate::display_list::{ + BlockFlowDisplayListBuilding, DisplayListBuildState, StackingContextCollectionFlags, +}; use crate::floats::FloatKind; -use crate::flow::{Flow, FlowClass, ImmutableFlowUtils, FlowFlags, OpaqueFlow}; +use crate::flow::{Flow, FlowClass, FlowFlags, ImmutableFlowUtils, OpaqueFlow}; use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; use crate::model::MaybeAuto; use crate::table::{ColumnComputedInlineSize, ColumnIntrinsicInlineSize}; @@ -31,8 +35,8 @@ use style::computed_values::{position, table_layout}; use style::context::SharedStyleContext; use style::logical_geometry::{LogicalRect, LogicalSize}; use style::properties::ComputedValues; -use style::values::CSSFloat; use style::values::computed::LengthOrPercentageOrAuto; +use style::values::CSSFloat; #[derive(Clone, Copy, Debug, Serialize)] pub enum TableLayout { @@ -143,7 +147,8 @@ impl TableWrapperFlow { ); total_guess = &total_guess + &guess; guess - }).collect(); + }) + .collect(); // Assign inline sizes. let selection = @@ -385,7 +390,8 @@ impl Flow for TableWrapperFlow { size: column_intrinsic_inline_size.minimum_length, percentage: column_intrinsic_inline_size.percentage, }, - ).collect::>(); + ) + .collect::>(); // 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 +759,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/text.rs b/components/layout/text.rs index 358a386d887..6ba30eb2cc0 100644 --- a/components/layout/text.rs +++ b/components/layout/text.rs @@ -10,7 +10,7 @@ use crate::fragment::{Fragment, ScannedTextFlags}; use crate::fragment::{ScannedTextFragmentInfo, SpecificFragmentInfo, UnscannedTextFragmentInfo}; use crate::inline::{InlineFragmentNodeFlags, InlineFragments}; use crate::linked_list::split_off_head; -use gfx::font::{FontRef, FontMetrics, RunMetrics, ShapingFlags, ShapingOptions}; +use gfx::font::{FontMetrics, FontRef, RunMetrics, ShapingFlags, ShapingOptions}; use gfx::text::glyph::ByteIndex; use gfx::text::text_run::TextRun; use gfx::text::util::{self, CompressionMode}; @@ -26,11 +26,11 @@ use style::computed_values::text_transform::T as TextTransform; use style::computed_values::white_space::T as WhiteSpace; use style::computed_values::word_break::T as WordBreak; use style::logical_geometry::{LogicalSize, WritingMode}; -use style::properties::ComputedValues; use style::properties::style_structs::Font as FontStyleStruct; +use style::properties::ComputedValues; use style::values::generics::text::LineHeight; use unicode_bidi as bidi; -use unicode_script::{Script, get_script}; +use unicode_script::{get_script, Script}; use xi_unicode::LineBreakLeafIter; /// Returns the concatenated text of a list of unscanned text fragments. diff --git a/components/layout/traversal.rs b/components/layout/traversal.rs index c18eeae5112..51888069cac 100644 --- a/components/layout/traversal.rs +++ b/components/layout/traversal.rs @@ -7,9 +7,9 @@ use crate::construct::FlowConstructor; use crate::context::LayoutContext; use crate::display_list::DisplayListBuildState; -use crate::flow::{FlowFlags, Flow, GetBaseFlow, ImmutableFlowUtils}; -use crate::wrapper::{GetRawData, LayoutNodeLayoutData}; +use crate::flow::{Flow, FlowFlags, GetBaseFlow, ImmutableFlowUtils}; use crate::wrapper::ThreadSafeLayoutNodeHelpers; +use crate::wrapper::{GetRawData, LayoutNodeLayoutData}; use script_layout_interface::wrapper_traits::{LayoutNode, ThreadSafeLayoutNode}; use servo_config::opts; use style::context::{SharedStyleContext, StyleContext}; @@ -17,8 +17,8 @@ use style::data::ElementData; use style::dom::{NodeInfo, TElement, TNode}; use style::selector_parser::RestyleDamage; use style::servo::restyle_damage::ServoRestyleDamage; -use style::traversal::{DomTraversal, recalc_style_at}; use style::traversal::PerLevelTraversalData; +use style::traversal::{recalc_style_at, DomTraversal}; pub struct RecalcStyleAndConstructFlows<'a> { context: LayoutContext<'a>, diff --git a/components/layout/wrapper.rs b/components/layout/wrapper.rs index 42369c04761..82ffd6be718 100644 --- a/components/layout/wrapper.rs +++ b/components/layout/wrapper.rs @@ -32,8 +32,8 @@ use atomic_refcell::{AtomicRef, AtomicRefMut}; use crate::data::{LayoutData, LayoutDataFlags, StyleAndLayoutData}; -use script_layout_interface::wrapper_traits::{ThreadSafeLayoutElement, ThreadSafeLayoutNode}; use script_layout_interface::wrapper_traits::GetLayoutData; +use script_layout_interface::wrapper_traits::{ThreadSafeLayoutElement, ThreadSafeLayoutNode}; use style::dom::{NodeInfo, TNode}; use style::selector_parser::RestyleDamage; use style::values::computed::counters::ContentItem; diff --git a/components/layout_thread/dom_wrapper.rs b/components/layout_thread/dom_wrapper.rs index bd760204884..21e61d96fff 100644 --- a/components/layout_thread/dom_wrapper.rs +++ b/components/layout_thread/dom_wrapper.rs @@ -30,7 +30,7 @@ #![allow(unsafe_code)] -use atomic_refcell::{AtomicRef, AtomicRefMut, AtomicRefCell}; +use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut}; use gfx_traits::ByteIndex; use html5ever::{LocalName, Namespace}; use layout::data::StyleAndLayoutData; @@ -38,19 +38,27 @@ use layout::wrapper::GetRawData; use msg::constellation_msg::{BrowsingContextId, PipelineId}; use net_traits::image::base::{Image, ImageMetadata}; use range::Range; +use script::layout_exports::NodeFlags; +use script::layout_exports::PendingRestyle; use script::layout_exports::{CharacterDataTypeId, ElementTypeId, HTMLElementTypeId, NodeTypeId}; use script::layout_exports::{Document, Element, Node, Text}; use script::layout_exports::{LayoutCharacterDataHelpers, LayoutDocumentHelpers}; -use script::layout_exports::{LayoutElementHelpers, LayoutNodeHelpers, LayoutDom, RawLayoutElementHelpers}; -use script::layout_exports::NodeFlags; -use script::layout_exports::PendingRestyle; -use script_layout_interface::{HTMLCanvasData, HTMLMediaData, LayoutNodeType, OpaqueStyleAndLayoutData}; +use script::layout_exports::{ + LayoutDom, LayoutElementHelpers, LayoutNodeHelpers, RawLayoutElementHelpers, +}; +use script_layout_interface::wrapper_traits::{ + DangerousThreadSafeLayoutNode, GetLayoutData, LayoutNode, +}; +use script_layout_interface::wrapper_traits::{ + PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode, +}; +use script_layout_interface::{ + HTMLCanvasData, HTMLMediaData, LayoutNodeType, OpaqueStyleAndLayoutData, +}; use script_layout_interface::{SVGSVGData, StyleData, TrustedNodeAddress}; -use script_layout_interface::wrapper_traits::{DangerousThreadSafeLayoutNode, GetLayoutData, LayoutNode}; -use script_layout_interface::wrapper_traits::{PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode}; -use selectors::attr::{AttrSelectorOperation, NamespaceConstraint, CaseSensitivity}; -use selectors::matching::{ElementSelectorFlags, MatchingContext, QuirksMode}; +use selectors::attr::{AttrSelectorOperation, CaseSensitivity, NamespaceConstraint}; use selectors::matching::VisitedHandlingMode; +use selectors::matching::{ElementSelectorFlags, MatchingContext, QuirksMode}; use selectors::sink::Push; use servo_arc::{Arc, ArcBorrow}; use servo_atoms::Atom; @@ -60,9 +68,8 @@ use std::fmt::Debug; use std::hash::{Hash, Hasher}; use std::marker::PhantomData; use std::ptr::NonNull; -use std::sync::Arc as StdArc; use std::sync::atomic::Ordering; -use style::CaseSensitivityExt; +use std::sync::Arc as StdArc; use style::applicable_declarations::ApplicableDeclarationBlock; use style::attr::AttrValue; use style::context::SharedStyleContext; @@ -72,11 +79,12 @@ use style::dom::{TDocument, TElement, TNode, TShadowRoot}; use style::element_state::*; use style::font_metrics::ServoMetricsProvider; use style::properties::{ComputedValues, PropertyDeclarationBlock}; -use style::selector_parser::{AttrValue as SelectorAttrValue, NonTSPseudoClass, Lang}; -use style::selector_parser::{PseudoElement, SelectorImpl, extended_filtering}; -use style::shared_lock::{SharedRwLock as StyleSharedRwLock, Locked as StyleLocked}; +use style::selector_parser::{extended_filtering, PseudoElement, SelectorImpl}; +use style::selector_parser::{AttrValue as SelectorAttrValue, Lang, NonTSPseudoClass}; +use style::shared_lock::{Locked as StyleLocked, SharedRwLock as StyleSharedRwLock}; use style::str::is_whitespace; use style::stylist::CascadeData; +use style::CaseSensitivityExt; pub unsafe fn drop_style_and_layout_data(data: OpaqueStyleAndLayoutData) { let ptr = data.ptr.as_ptr() as *mut StyleData; @@ -664,7 +672,7 @@ impl<'le> ServoLayoutElement<'le> { } pub unsafe fn note_dirty_descendant(&self) { - use ::selectors::Element; + use selectors::Element; let mut current = Some(*self); while let Some(el) = current { @@ -687,9 +695,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> { @@ -1134,7 +1140,7 @@ where { type Item = ConcreteNode; fn next(&mut self) -> Option { - use ::selectors::Element; + use selectors::Element; match self.parent_node.get_pseudo_element_type() { PseudoElementType::Before | PseudoElementType::After => None, @@ -1272,9 +1278,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 { diff --git a/components/layout_thread/lib.rs b/components/layout_thread/lib.rs index ad0e7cac3ef..bf10a795732 100644 --- a/components/layout_thread/lib.rs +++ b/components/layout_thread/lib.rs @@ -55,8 +55,8 @@ extern crate webrender_api; mod dom_wrapper; use app_units::Au; -use crate::dom_wrapper::{ServoLayoutElement, ServoLayoutDocument, ServoLayoutNode}; use crate::dom_wrapper::drop_style_and_layout_data; +use crate::dom_wrapper::{ServoLayoutDocument, ServoLayoutElement, ServoLayoutNode}; use embedder_traits::resources::{self, Resource}; use euclid::{Point2D, Rect, Size2D, TypedScale, TypedSize2D}; use fnv::FnvHashMap; @@ -64,28 +64,34 @@ use fxhash::FxHashMap; use gfx::font; use gfx::font_cache_thread::FontCacheThread; use gfx::font_context; -use gfx_traits::{Epoch, node_id_from_scroll_id}; +use gfx_traits::{node_id_from_scroll_id, Epoch}; use histogram::Histogram; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use layout::animation; use layout::construct::ConstructionResult; +use layout::context::malloc_size_of_persistent_local_context; use layout::context::LayoutContext; use layout::context::RegisteredPainter; use layout::context::RegisteredPainters; -use layout::context::malloc_size_of_persistent_local_context; -use layout::display_list::{IndexableText, ToLayout, WebRenderDisplayListConverter}; use layout::display_list::items::{OpaqueNode, WebRenderImageInfo}; +use layout::display_list::{IndexableText, ToLayout, WebRenderDisplayListConverter}; use layout::flow::{Flow, GetBaseFlow, ImmutableFlowUtils, MutableOwnedFlowUtils}; use layout::flow_ref::FlowRef; use layout::incremental::{LayoutDamageComputation, RelayoutMode, SpecialRestyleDamage}; use layout::layout_debug; use layout::parallel; -use layout::query::{LayoutRPCImpl, LayoutThreadData, process_content_box_request, process_content_boxes_request}; +use layout::query::{ + process_content_box_request, process_content_boxes_request, LayoutRPCImpl, LayoutThreadData, +}; use layout::query::{process_element_inner_text_query, process_node_geometry_request}; use layout::query::{process_node_scroll_area_request, process_node_scroll_id_request}; -use layout::query::{process_offset_parent_query, process_resolved_style_request, process_style_query}; +use layout::query::{ + process_offset_parent_query, process_resolved_style_request, process_style_query, +}; use layout::sequential; -use layout::traversal::{ComputeStackingRelativePositions, PreorderFlowTraversal, RecalcStyleAndConstructFlows}; +use layout::traversal::{ + ComputeStackingRelativePositions, PreorderFlowTraversal, RecalcStyleAndConstructFlows, +}; use layout::wrapper::LayoutNodeLayoutData; use layout_traits::LayoutThreadFactory; use libc::c_void; @@ -96,21 +102,21 @@ use msg::constellation_msg::TopLevelBrowsingContextId; use net_traits::image_cache::{ImageCache, UsePlaceholder}; use parking_lot::RwLock; use profile_traits::mem::{self, Report, ReportKind, ReportsChan}; -use profile_traits::time::{self, TimerMetadata, profile}; +use profile_traits::time::{self, profile, TimerMetadata}; use profile_traits::time::{TimerMetadataFrameType, TimerMetadataReflowType}; use script_layout_interface::message::{Msg, NewLayoutThreadInfo, NodesFromPointQueryType, Reflow}; -use script_layout_interface::message::{ReflowComplete, QueryMsg, ReflowGoal, ScriptReflow}; -use script_layout_interface::rpc::{LayoutRPC, StyleResponse, OffsetParentResponse}; +use script_layout_interface::message::{QueryMsg, ReflowComplete, ReflowGoal, ScriptReflow}; use script_layout_interface::rpc::TextIndexResponse; +use script_layout_interface::rpc::{LayoutRPC, OffsetParentResponse, StyleResponse}; use script_layout_interface::wrapper_traits::LayoutNode; +use script_traits::Painter; use script_traits::{ConstellationControlMsg, LayoutControlMsg, LayoutMsg as ConstellationMsg}; use script_traits::{DrawAPaintImageResult, PaintWorkletError}; use script_traits::{ScrollState, UntrustedNodeAddress}; -use script_traits::Painter; use selectors::Element; use servo_arc::Arc as ServoArc; use servo_atoms::Atom; -use servo_channel::{Receiver, Sender, channel, route_ipc_receiver_to_new_servo_receiver}; +use servo_channel::{channel, route_ipc_receiver_to_new_servo_receiver, Receiver, Sender}; use servo_config::opts; use servo_config::prefs::PREFS; use servo_geometry::MaxRect; @@ -121,8 +127,8 @@ use std::collections::HashMap; use std::mem as std_mem; use std::ops::{Deref, DerefMut}; use std::process; -use std::sync::{Arc, Mutex, MutexGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; use std::thread; use style::animation::Animation; use style::context::{QuirksMode, RegisteredSpeculativePainter, RegisteredSpeculativePainters}; @@ -137,7 +143,9 @@ use style::properties::PropertyId; use style::selector_parser::SnapshotMap; use style::servo::restyle_damage::ServoRestyleDamage; use style::shared_lock::{SharedRwLock, SharedRwLockReadGuard, StylesheetGuards}; -use style::stylesheets::{Origin, Stylesheet, DocumentStyleSheet, StylesheetInDocument, UserAgentStylesheets}; +use style::stylesheets::{ + DocumentStyleSheet, Origin, Stylesheet, StylesheetInDocument, UserAgentStylesheets, +}; use style::stylist::Stylist; use style::thread_state::{self, ThreadState}; use style::timer::Timer; @@ -334,7 +342,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 +516,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 +777,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 +1258,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/layout_traits/lib.rs b/components/layout_traits/lib.rs index 646706e7717..9fb431c8e2e 100644 --- a/components/layout_traits/lib.rs +++ b/components/layout_traits/lib.rs @@ -27,8 +27,8 @@ use msg::constellation_msg::PipelineId; use msg::constellation_msg::TopLevelBrowsingContextId; use net_traits::image_cache::ImageCache; use profile_traits::{mem, time}; -use script_traits::{ConstellationControlMsg, LayoutControlMsg}; use script_traits::LayoutMsg as ConstellationMsg; +use script_traits::{ConstellationControlMsg, LayoutControlMsg}; use servo_channel::{Receiver, Sender}; use servo_url::ServoUrl; use std::sync::Arc; diff --git a/components/malloc_size_of/lib.rs b/components/malloc_size_of/lib.rs index 540ff8bffd5..69dc48ce30d 100644 --- a/components/malloc_size_of/lib.rs +++ b/components/malloc_size_of/lib.rs @@ -82,8 +82,8 @@ extern crate xml5ever; use serde_bytes::ByteBuf; use std::hash::{BuildHasher, Hash}; use std::mem::size_of; -use std::ops::{Deref, DerefMut}; use std::ops::Range; +use std::ops::{Deref, DerefMut}; use std::os::raw::c_void; use void::Void; 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 { bar: Bar, baz: T, #[ignore_malloc_size_of = \"\"] z: Arc }", - ).unwrap(); + ) + .unwrap(); let source = synstructure::Structure::new(&source); let expanded = malloc_size_of_derive(source).to_string(); diff --git a/components/metrics/lib.rs b/components/metrics/lib.rs index f0411cb7627..f83a80b9302 100644 --- a/components/metrics/lib.rs +++ b/components/metrics/lib.rs @@ -16,11 +16,11 @@ extern crate servo_config; extern crate servo_url; extern crate time; -use gfx_traits::{Epoch, DisplayList}; +use gfx_traits::{DisplayList, Epoch}; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; -use profile_traits::time::{ProfilerChan, ProfilerCategory, send_profile_data}; use profile_traits::time::TimerMetadata; +use profile_traits::time::{send_profile_data, ProfilerCategory, ProfilerChan}; use script_traits::{ConstellationControlMsg, LayoutMsg, ProgressiveWebMetricType}; use servo_config::opts; use servo_url::ServoUrl; diff --git a/components/net/blob_loader.rs b/components/net/blob_loader.rs index 94e35ee4782..2afed16ad7f 100644 --- a/components/net/blob_loader.rs +++ b/components/net/blob_loader.rs @@ -5,13 +5,13 @@ use crate::filemanager_thread::FileManager; use headers_core::HeaderMapExt; use headers_ext::{ContentLength, ContentType}; -use http::HeaderMap; use http::header::{self, HeaderValue}; +use http::HeaderMap; use ipc_channel::ipc; use mime::{self, Mime}; -use net_traits::{http_percent_encode, NetworkError}; use net_traits::blob_url_store::parse_blob_url; use net_traits::filemanager_thread::ReadFileProgress; +use net_traits::{http_percent_encode, NetworkError}; use servo_url::ServoUrl; // TODO: Check on GET diff --git a/components/net/connector.rs b/components/net/connector.rs index e347862d2c9..38693e70e24 100644 --- a/components/net/connector.rs +++ b/components/net/connector.rs @@ -5,17 +5,17 @@ use crate::hosts::replace_host; use crate::http_loader::Decoder; use flate2::read::GzDecoder; -use hyper::{Body, Client}; use hyper::body::Payload; -use hyper::client::HttpConnector as HyperHttpConnector; use hyper::client::connect::{Connect, Destination}; +use hyper::client::HttpConnector as HyperHttpConnector; use hyper::rt::Future; +use hyper::{Body, Client}; use hyper_openssl::HttpsConnector; use openssl::ssl::{SslConnector, SslConnectorBuilder, SslMethod, SslOptions}; use openssl::x509; use std::io::{Cursor, Read}; -use tokio::prelude::{Async, Stream}; use tokio::prelude::future::Executor; +use tokio::prelude::{Async, Stream}; pub const BUF_SIZE: usize = 32768; diff --git a/components/net/cookie.rs b/components/net/cookie.rs index d7d68196d4a..5b9089cc1d3 100644 --- a/components/net/cookie.rs +++ b/components/net/cookie.rs @@ -7,12 +7,12 @@ use crate::cookie_rs; use hyper_serde::{self, Serde}; -use net_traits::CookieSource; use net_traits::pub_domains::is_pub_domain; +use net_traits::CookieSource; use servo_url::ServoUrl; use std::borrow::ToOwned; use std::net::{Ipv4Addr, Ipv6Addr}; -use time::{Tm, now, at, Duration}; +use time::{at, now, Duration, Tm}; /// A stored cookie that wraps the definition in cookie-rs. This is used to implement /// various behaviours defined in the spec that rely on an associated request URL, diff --git a/components/net/cookie_storage.rs b/components/net/cookie_storage.rs index 8959b6d97ac..7eefb164439 100644 --- a/components/net/cookie_storage.rs +++ b/components/net/cookie_storage.rs @@ -7,8 +7,8 @@ use crate::cookie::Cookie; use crate::cookie_rs; -use net_traits::CookieSource; use net_traits::pub_domains::reg_suffix; +use net_traits::CookieSource; use servo_url::ServoUrl; use std::cmp::Ordering; use std::collections::HashMap; @@ -236,10 +236,9 @@ fn evict_one_cookie(is_secure_cookie: bool, cookies: &mut Vec) -> bool { fn get_oldest_accessed(is_secure_cookie: bool, cookies: &mut Vec) -> 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/data_loader.rs b/components/net/data_loader.rs index 3cd282bb1ed..9f0e1627ea3 100644 --- a/components/net/data_loader.rs +++ b/components/net/data_loader.rs @@ -5,8 +5,8 @@ use base64; use mime::Mime; use servo_url::ServoUrl; -use url::Position; use url::percent_encoding::percent_decode; +use url::Position; pub enum DecodeError { InvalidDataUri, diff --git a/components/net/fetch/methods.rs b/components/net/fetch/methods.rs index 0e744e0de26..0ad92f527ef 100644 --- a/components/net/fetch/methods.rs +++ b/components/net/fetch/methods.rs @@ -6,7 +6,7 @@ use crate::blob_loader::load_blob_sync; use crate::data_loader::decode; use crate::fetch::cors_cache::CorsCache; use crate::filemanager_thread::FileManager; -use crate::http_loader::{HttpState, determine_request_referrer, http_fetch}; +use crate::http_loader::{determine_request_referrer, http_fetch, HttpState}; use crate::http_loader::{set_default_accept, set_default_accept_language}; use crate::subresource_integrity::is_response_integrity_valid; use devtools_traits::DevtoolsControlMsg; @@ -18,20 +18,20 @@ use hyper::StatusCode; use ipc_channel::ipc::IpcReceiver; use mime::{self, Mime}; use mime_guess::guess_mime_type; -use net_traits::{FetchTaskTarget, NetworkError, ReferrerPolicy}; use net_traits::request::{CredentialsMode, Destination, Referrer, Request, RequestMode}; -use net_traits::request::{ResponseTainting, Origin, Window}; +use net_traits::request::{Origin, ResponseTainting, Window}; use net_traits::response::{Response, ResponseBody, ResponseType}; -use servo_channel::{channel, Sender, Receiver}; +use net_traits::{FetchTaskTarget, NetworkError, ReferrerPolicy}; +use servo_channel::{channel, Receiver, Sender}; use servo_url::ServoUrl; use std::borrow::Cow; use std::fs::File; -use std::io::{BufReader, BufRead, Seek, SeekFrom}; +use std::io::{BufRead, BufReader, Seek, SeekFrom}; use std::mem; use std::ops::Bound; use std::str; -use std::sync::{Arc, Mutex}; use std::sync::atomic::Ordering; +use std::sync::{Arc, Mutex}; use std::thread; lazy_static! { @@ -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, + } } /// diff --git a/components/net/filemanager_thread.rs b/components/net/filemanager_thread.rs index f1e3b3e61df..966f8a21bcb 100644 --- a/components/net/filemanager_thread.rs +++ b/components/net/filemanager_thread.rs @@ -7,15 +7,17 @@ use ipc_channel::ipc::{self, IpcSender}; use mime_guess::guess_mime_type_opt; use net_traits::blob_url_store::{BlobBuf, BlobURLStoreError}; use net_traits::filemanager_thread::{FileManagerResult, FileManagerThreadMsg, FileOrigin}; -use net_traits::filemanager_thread::{FileManagerThreadError, ReadFileProgress, RelativePos, SelectedFile}; +use net_traits::filemanager_thread::{ + FileManagerThreadError, ReadFileProgress, RelativePos, SelectedFile, +}; use servo_config::prefs::PREFS; use std::collections::HashMap; use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use std::ops::Index; use std::path::{Path, PathBuf}; -use std::sync::{Arc, RwLock}; use std::sync::atomic::{self, AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, RwLock}; use std::thread; use url::Url; use uuid::Uuid; diff --git a/components/net/hsts.rs b/components/net/hsts.rs index bcf6ee02747..693869af0db 100644 --- a/components/net/hsts.rs +++ b/components/net/hsts.rs @@ -3,8 +3,8 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use embedder_traits::resources::{self, Resource}; -use net_traits::IncludeSubdomains; use net_traits::pub_domains::reg_suffix; +use net_traits::IncludeSubdomains; use serde_json; use servo_url::ServoUrl; use std::collections::HashMap; diff --git a/components/net/http_cache.rs b/components/net/http_cache.rs index b234389d69b..ab7f99f1e0e 100644 --- a/components/net/http_cache.rs +++ b/components/net/http_cache.rs @@ -10,22 +10,24 @@ use crate::fetch::methods::{Data, DoneChannel}; use headers_core::HeaderMapExt; use headers_ext::{CacheControl, ContentRange, Expires, LastModified, Pragma, Range, Vary}; -use http::{header, HeaderMap}; use http::header::HeaderValue; +use http::{header, HeaderMap}; use hyper::{Method, StatusCode}; -use malloc_size_of::{MallocSizeOf, MallocSizeOfOps, MallocUnconditionalSizeOf, MallocUnconditionalShallowSizeOf}; use malloc_size_of::Measurable; -use net_traits::{Metadata, FetchMetadata}; +use malloc_size_of::{ + MallocSizeOf, MallocSizeOfOps, MallocUnconditionalShallowSizeOf, MallocUnconditionalSizeOf, +}; use net_traits::request::Request; use net_traits::response::{HttpsState, Response, ResponseBody}; +use net_traits::{FetchMetadata, Metadata}; use servo_arc::Arc; -use servo_channel::{Sender, channel}; +use servo_channel::{channel, Sender}; use servo_config::prefs::PREFS; use servo_url::ServoUrl; use std::collections::HashMap; use std::ops::Bound; -use std::sync::Mutex; use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; use std::time::SystemTime; use time; use time::{Duration, Timespec, Tm}; diff --git a/components/net/http_loader.rs b/components/net/http_loader.rs index 10fccc3561b..8898fdf1924 100644 --- a/components/net/http_loader.rs +++ b/components/net/http_loader.rs @@ -4,38 +4,47 @@ use brotli::Decompressor; use bytes::Bytes; -use crate::connector::{BUF_SIZE, Connector, create_http_client, WrappedBody}; +use crate::connector::{create_http_client, Connector, WrappedBody, BUF_SIZE}; use crate::cookie; use crate::cookie_storage::CookieStorage; use crate::fetch::cors_cache::CorsCache; +use crate::fetch::methods::{ + is_cors_safelisted_method, is_cors_safelisted_request_header, main_fetch, +}; use crate::fetch::methods::{Data, DoneChannel, FetchContext, Target}; -use crate::fetch::methods::{is_cors_safelisted_request_header, is_cors_safelisted_method, main_fetch}; use crate::hsts::HstsList; use crate::http_cache::HttpCache; use crate::resource_thread::AuthCache; -use devtools_traits::{ChromeToDevtoolsControlMsg, DevtoolsControlMsg, HttpRequest as DevtoolsHttpRequest}; +use devtools_traits::{ + ChromeToDevtoolsControlMsg, DevtoolsControlMsg, HttpRequest as DevtoolsHttpRequest, +}; use devtools_traits::{HttpResponse as DevtoolsHttpResponse, NetworkEvent}; use flate2::read::{DeflateDecoder, GzDecoder}; use headers_core::HeaderMapExt; use headers_ext::{AccessControlAllowCredentials, AccessControlAllowHeaders}; -use headers_ext::{AccessControlAllowMethods, AccessControlRequestHeaders, AccessControlRequestMethod, Authorization}; +use headers_ext::{ + AccessControlAllowMethods, AccessControlRequestHeaders, AccessControlRequestMethod, + Authorization, +}; use headers_ext::{AccessControlAllowOrigin, AccessControlMaxAge, Basic}; use headers_ext::{CacheControl, ContentEncoding, ContentLength}; -use headers_ext::{Host, IfModifiedSince, LastModified, Origin as HyperOrigin, Pragma, Referer, UserAgent}; -use http::{HeaderMap, Request as HyperRequest}; +use headers_ext::{ + Host, IfModifiedSince, LastModified, Origin as HyperOrigin, Pragma, Referer, UserAgent, +}; use http::header::{self, HeaderName, HeaderValue}; use http::uri::Authority; -use hyper::{Body, Client, Method, StatusCode, Response as HyperResponse}; +use http::{HeaderMap, Request as HyperRequest}; +use hyper::{Body, Client, Method, Response as HyperResponse, StatusCode}; use hyper_serde::Serde; use log; use mime; use msg::constellation_msg::{HistoryStateId, PipelineId}; -use net_traits::{CookieSource, FetchMetadata, NetworkError, ReferrerPolicy}; use net_traits::quality::{quality_to_value, Quality, QualityItem}; use net_traits::request::{CacheMode, CredentialsMode, Destination, Origin}; use net_traits::request::{RedirectMode, Referrer, Request, RequestMode}; use net_traits::request::{ResponseTainting, ServiceWorkersMode}; use net_traits::response::{HttpsState, Response, ResponseBody, ResponseType}; +use net_traits::{CookieSource, FetchMetadata, NetworkError, ReferrerPolicy}; use openssl::ssl::SslConnectorBuilder; use servo_channel::{channel, Sender}; use servo_url::{ImmutableOrigin, ServoUrl}; @@ -50,7 +59,7 @@ use std::sync::Mutex; use std::sync::RwLock; use std::time::{Duration, SystemTime}; use time::{self, Tm}; -use tokio::prelude::{Future, future, Stream}; +use tokio::prelude::{future, Future, Stream}; use tokio::runtime::Runtime; use uuid; @@ -506,12 +515,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 +1051,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 +1390,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/image_cache.rs b/components/net/image_cache.rs index 4272bdcb6a3..8dc194a10d1 100644 --- a/components/net/image_cache.rs +++ b/components/net/image_cache.rs @@ -4,15 +4,15 @@ use embedder_traits::resources::{self, Resource}; use immeta::load_from_buf; -use net_traits::{FetchMetadata, FetchResponseMsg, NetworkError}; -use net_traits::image::base::{Image, ImageMetadata, PixelFormat, load_from_memory}; +use net_traits::image::base::{load_from_memory, Image, ImageMetadata, PixelFormat}; use net_traits::image_cache::{CanRequestImages, ImageCache, ImageResponder}; use net_traits::image_cache::{ImageOrMetadataAvailable, ImageResponse, ImageState}; use net_traits::image_cache::{PendingImageId, UsePlaceholder}; +use net_traits::{FetchMetadata, FetchResponseMsg, NetworkError}; use pixels; use servo_url::ServoUrl; -use std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; +use std::collections::HashMap; use std::io; use std::mem; use std::sync::{Arc, Mutex}; diff --git a/components/net/lib.rs b/components/net/lib.rs index 9fbb9415ab6..e4373edee33 100644 --- a/components/net/lib.rs +++ b/components/net/lib.rs @@ -76,6 +76,6 @@ pub mod fetch { /// A module for re-exports of items used in unit tests. pub mod test { + pub use crate::hosts::{parse_hostsfile, replace_host_table}; pub use crate::http_loader::HttpState; - pub use crate::hosts::{replace_host_table, parse_hostsfile}; } 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/resource_thread.rs b/components/net/resource_thread.rs index 6c4cc78479a..9793fcb862d 100644 --- a/components/net/resource_thread.rs +++ b/components/net/resource_thread.rs @@ -8,28 +8,28 @@ use crate::cookie; use crate::cookie_rs; use crate::cookie_storage::CookieStorage; use crate::fetch::cors_cache::CorsCache; -use crate::fetch::methods::{CancellationListener, FetchContext, fetch}; +use crate::fetch::methods::{fetch, CancellationListener, FetchContext}; use crate::filemanager_thread::FileManager; use crate::hsts::HstsList; use crate::http_cache::HttpCache; -use crate::http_loader::{HANDLE, HttpState, http_redirect_fetch}; +use crate::http_loader::{http_redirect_fetch, HttpState, HANDLE}; use crate::storage_thread::StorageThreadFactory; use crate::websocket_loader; use devtools_traits::DevtoolsControlMsg; -use embedder_traits::EmbedderProxy; use embedder_traits::resources::{self, Resource}; +use embedder_traits::EmbedderProxy; use hyper_serde::Serde; use ipc_channel::ipc::{self, IpcReceiver, IpcReceiverSet, IpcSender}; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; -use net_traits::{CookieSource, CoreResourceThread}; -use net_traits::{CoreResourceMsg, CustomResponseMediator, FetchChannels}; -use net_traits::{FetchResponseMsg, ResourceThreads, WebSocketDomAction}; -use net_traits::WebSocketNetworkEvent; use net_traits::request::{Request, RequestInit}; use net_traits::response::{Response, ResponseInit}; use net_traits::storage_thread::StorageThreadMsg; -use profile_traits::mem::{Report, ReportsChan, ReportKind}; +use net_traits::WebSocketNetworkEvent; +use net_traits::{CookieSource, CoreResourceThread}; +use net_traits::{CoreResourceMsg, CustomResponseMediator, FetchChannels}; +use net_traits::{FetchResponseMsg, ResourceThreads, WebSocketDomAction}; use profile_traits::mem::ProfilerChan as MemProfilerChan; +use profile_traits::mem::{Report, ReportKind, ReportsChan}; use profile_traits::time::ProfilerChan; use serde::{Deserialize, Serialize}; use serde_json; diff --git a/components/net/subresource_integrity.rs b/components/net/subresource_integrity.rs index 6abeb39149c..de90fea9338 100644 --- a/components/net/subresource_integrity.rs +++ b/components/net/subresource_integrity.rs @@ -4,7 +4,7 @@ use base64; use net_traits::response::{Response, ResponseBody, ResponseType}; -use openssl::hash::{MessageDigest, hash}; +use openssl::hash::{hash, MessageDigest}; use std::iter::Filter; use std::str::Split; use std::sync::MutexGuard; diff --git a/components/net/tests/data_loader.rs b/components/net/tests/data_loader.rs index 5ab5c68943f..9996aed73e6 100644 --- a/components/net/tests/data_loader.rs +++ b/components/net/tests/data_loader.rs @@ -7,9 +7,9 @@ use headers_core::HeaderMapExt; use headers_ext::ContentType; use hyper_serde::Serde; use mime::{self, Mime}; -use net_traits::{FetchMetadata, FilteredMetadata, NetworkError}; use net_traits::request::{Origin, Request}; use net_traits::response::ResponseBody; +use net_traits::{FetchMetadata, FilteredMetadata, NetworkError}; use servo_url::ServoUrl; use std::ops::Deref; diff --git a/components/net/tests/fetch.rs b/components/net/tests/fetch.rs index aba99c2fdd4..2414bb153e9 100644 --- a/components/net/tests/fetch.rs +++ b/components/net/tests/fetch.rs @@ -2,21 +2,28 @@ * 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/. */ -use crate::{DEFAULT_USER_AGENT, new_fetch_context, create_embedder_proxy, fetch, make_server, make_ssl_server}; use crate::fetch_with_context; use crate::fetch_with_cors_cache; use crate::http_loader::{expect_devtools_http_request, expect_devtools_http_response}; +use crate::{ + create_embedder_proxy, fetch, make_server, make_ssl_server, new_fetch_context, + DEFAULT_USER_AGENT, +}; use devtools_traits::HttpRequest as DevtoolsHttpRequest; use devtools_traits::HttpResponse as DevtoolsHttpResponse; use headers_core::HeaderMapExt; -use headers_ext::{AccessControlAllowCredentials, AccessControlAllowHeaders, AccessControlAllowOrigin}; +use headers_ext::{ + AccessControlAllowCredentials, AccessControlAllowHeaders, AccessControlAllowOrigin, +}; use headers_ext::{AccessControlAllowMethods, AccessControlMaxAge}; -use headers_ext::{CacheControl, ContentLength, ContentType, Expires, Host, LastModified, Pragma, UserAgent}; -use http::{Method, StatusCode}; +use headers_ext::{ + CacheControl, ContentLength, ContentType, Expires, Host, LastModified, Pragma, UserAgent, +}; use http::header::{self, HeaderMap, HeaderName, HeaderValue}; use http::uri::Authority; -use hyper::{Request as HyperRequest, Response as HyperResponse}; +use http::{Method, StatusCode}; use hyper::body::Body; +use hyper::{Request as HyperRequest, Response as HyperResponse}; use mime::{self, Mime}; use msg::constellation_msg::TEST_PIPELINE_ID; use net::connector::create_ssl_connector_builder; @@ -25,20 +32,20 @@ use net::fetch::methods::{CancellationListener, FetchContext}; use net::filemanager_thread::FileManager; use net::hsts::HstsEntry; use net::test::HttpState; +use net_traits::request::{Destination, Origin, RedirectMode, Referrer, Request, RequestMode}; +use net_traits::response::{CacheState, Response, ResponseBody, ResponseType}; use net_traits::IncludeSubdomains; use net_traits::NetworkError; use net_traits::ReferrerPolicy; -use net_traits::request::{Destination, Origin, RedirectMode, Referrer, Request, RequestMode}; -use net_traits::response::{CacheState, Response, ResponseBody, ResponseType}; use servo_channel::{channel, Sender}; use servo_url::{ImmutableOrigin, ServoUrl}; use std::fs::File; use std::io::Read; use std::iter::FromIterator; use std::path::Path; -use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::time::{SystemTime, Duration}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, SystemTime}; // TODO write a struct that impls Handler for storing test values @@ -221,19 +228,25 @@ fn test_cors_preflight_fetch() { let handler = move |request: HyperRequest, response: &mut HyperResponse| { 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 +292,16 @@ fn test_cors_preflight_cache_fetch() { let handler = move |request: HyperRequest, response: &mut HyperResponse| { 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 +361,16 @@ fn test_cors_preflight_fetch_network_error() { let handler = move |request: HyperRequest, response: &mut HyperResponse| { 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 +429,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 +503,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/filemanager_thread.rs b/components/net/tests/filemanager_thread.rs index 35634cad815..50141326722 100644 --- a/components/net/tests/filemanager_thread.rs +++ b/components/net/tests/filemanager_thread.rs @@ -7,7 +7,9 @@ use embedder_traits::FilterPattern; use ipc_channel::ipc; use net::filemanager_thread::FileManager; use net_traits::blob_url_store::BlobURLStoreError; -use net_traits::filemanager_thread::{FileManagerThreadMsg, FileManagerThreadError, ReadFileProgress}; +use net_traits::filemanager_thread::{ + FileManagerThreadError, FileManagerThreadMsg, ReadFileProgress, +}; use servo_config::prefs::{PrefValue, PREFS}; use std::fs::File; use std::io::Read; 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..bc5112f1f58 100644 --- a/components/net/tests/http_loader.rs +++ b/components/net/tests/http_loader.rs @@ -7,35 +7,37 @@ use crate::fetch; use crate::fetch_with_context; use crate::make_server; use crate::new_fetch_context; -use devtools_traits::{ChromeToDevtoolsControlMsg, DevtoolsControlMsg, NetworkEvent}; use devtools_traits::HttpRequest as DevtoolsHttpRequest; use devtools_traits::HttpResponse as DevtoolsHttpResponse; -use flate2::Compression; +use devtools_traits::{ChromeToDevtoolsControlMsg, DevtoolsControlMsg, NetworkEvent}; use flate2::write::{DeflateEncoder, GzEncoder}; +use flate2::Compression; use futures::{self, Future, Stream}; use headers_core::HeaderMapExt; -use headers_ext::{Authorization, Basic, AccessControlAllowOrigin, ContentLength, Date, Host, Origin}; +use headers_ext::{ + AccessControlAllowOrigin, Authorization, Basic, ContentLength, Date, Host, Origin, +}; use headers_ext::{StrictTransportSecurity, UserAgent}; -use http::{Method, StatusCode}; use http::header::{self, HeaderMap, HeaderValue}; use http::uri::Authority; -use hyper::{Request as HyperRequest, Response as HyperResponse}; +use http::{Method, StatusCode}; use hyper::body::Body; +use hyper::{Request as HyperRequest, Response as HyperResponse}; use msg::constellation_msg::TEST_PIPELINE_ID; use net::cookie::Cookie; use net::cookie_storage::CookieStorage; use net::resource_thread::AuthCacheEntry; use net::test::replace_host_table; -use net_traits::{CookieSource, NetworkError}; -use net_traits::request::{Request, RequestInit, RequestMode, CredentialsMode, Destination}; +use net_traits::request::{CredentialsMode, Destination, Request, RequestInit, RequestMode}; use net_traits::response::ResponseBody; +use net_traits::{CookieSource, NetworkError}; use servo_channel::{channel, Receiver}; -use servo_url::{ServoUrl, ImmutableOrigin}; +use servo_url::{ImmutableOrigin, ServoUrl}; use std::collections::HashMap; use std::io::Write; use std::str; -use std::sync::{Arc, Mutex, RwLock}; use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, RwLock}; use std::time::Duration; fn mock_origin() -> ImmutableOrigin { @@ -142,13 +144,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 +174,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 +208,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 +245,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 +346,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 +592,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 +641,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 +696,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 +745,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 +785,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 +801,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 +837,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 +876,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 +918,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 +957,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 +999,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 +1038,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 +1374,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 +1439,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 +1469,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 +1490,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/net/tests/main.rs b/components/net/tests/main.rs index c20c846bf7d..aa7a6aa9cf6 100644 --- a/components/net/tests/main.rs +++ b/components/net/tests/main.rs @@ -44,21 +44,21 @@ mod resource_thread; mod subresource_integrity; use devtools_traits::DevtoolsControlMsg; -use embedder_traits::{EmbedderProxy, EventLoopWaker}; use embedder_traits::resources::{self, Resource}; +use embedder_traits::{EmbedderProxy, EventLoopWaker}; use futures::{Future, Stream}; -use hyper::{Body, Request as HyperRequest, Response as HyperResponse}; -use hyper::server::Server as HyperServer; use hyper::server::conn::Http; +use hyper::server::Server as HyperServer; use hyper::service::service_fn_ok; +use hyper::{Body, Request as HyperRequest, Response as HyperResponse}; use net::connector::create_ssl_connector_builder; use net::fetch::cors_cache::CorsCache; use net::fetch::methods::{self, CancellationListener, FetchContext}; use net::filemanager_thread::FileManager; use net::test::HttpState; -use net_traits::FetchTaskTarget; use net_traits::request::Request; use net_traits::response::Response; +use net_traits::FetchTaskTarget; use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod}; use servo_channel::{channel, Sender}; use servo_url::ServoUrl; diff --git a/components/net/tests/subresource_integrity.rs b/components/net/tests/subresource_integrity.rs index 7607fc378b7..3cd5ac2b017 100644 --- a/components/net/tests/subresource_integrity.rs +++ b/components/net/tests/subresource_integrity.rs @@ -2,7 +2,7 @@ * 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/. */ -use net::subresource_integrity::{SriEntry, get_prioritized_hash_function, get_strongest_metadata}; +use net::subresource_integrity::{get_prioritized_hash_function, get_strongest_metadata, SriEntry}; use net::subresource_integrity::{is_response_integrity_valid, parsed_metadata}; use net_traits::response::{Response, ResponseBody}; use servo_url::ServoUrl; diff --git a/components/net/websocket_loader.rs b/components/net/websocket_loader.rs index c37555afcb5..85149c60ec0 100644 --- a/components/net/websocket_loader.rs +++ b/components/net/websocket_loader.rs @@ -12,20 +12,23 @@ use headers_ext::Host; use http::header::{self, HeaderMap, HeaderName, HeaderValue}; use http::uri::Authority; use ipc_channel::ipc::{IpcReceiver, IpcSender}; +use net_traits::request::{RequestInit, RequestMode}; use net_traits::{CookieSource, MessageData}; use net_traits::{WebSocketDomAction, WebSocketNetworkEvent}; -use net_traits::request::{RequestInit, RequestMode}; use openssl::ssl::SslStream; use servo_config::opts; use servo_url::ServoUrl; use std::fs; -use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; use std::thread; use url::Url; -use ws::{CloseCode, Factory, Handler, Handshake, Message, Request, Response as WsResponse, Sender, WebSocket}; -use ws::{Error as WebSocketError, ErrorKind as WebSocketErrorKind, Result as WebSocketResult}; use ws::util::TcpStream; +use ws::{ + CloseCode, Factory, Handler, Handshake, Message, Request, Response as WsResponse, Sender, + WebSocket, +}; +use ws::{Error as WebSocketError, ErrorKind as WebSocketErrorKind, Result as WebSocketResult}; /// A client for connecting to a websocket server #[derive(Clone)] diff --git a/components/net_traits/image_cache.rs b/components/net_traits/image_cache.rs index 6cc70ba245a..6f035187a81 100644 --- a/components/net_traits/image_cache.rs +++ b/components/net_traits/image_cache.rs @@ -2,8 +2,8 @@ * 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/. */ -use crate::FetchResponseMsg; use crate::image::base::{Image, ImageMetadata}; +use crate::FetchResponseMsg; use ipc_channel::ipc::IpcSender; use servo_url::ServoUrl; use std::sync::Arc; diff --git a/components/net_traits/lib.rs b/components/net_traits/lib.rs index e766bee302c..9acfe5dfcca 100644 --- a/components/net_traits/lib.rs +++ b/components/net_traits/lib.rs @@ -45,9 +45,9 @@ use http::{Error as HttpError, HeaderMap}; use hyper::Error as HyperError; use hyper::StatusCode; use hyper_serde::Serde; -use ipc_channel::Error as IpcError; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use ipc_channel::router::ROUTER; +use ipc_channel::Error as IpcError; use mime::Mime; use msg::constellation_msg::HistoryStateId; use servo_url::ServoUrl; diff --git a/components/net_traits/response.rs b/components/net_traits/response.rs index f8d454854ce..33eebc4eb66 100644 --- a/components/net_traits/response.rs +++ b/components/net_traits/response.rs @@ -11,8 +11,8 @@ use http::{HeaderMap, StatusCode}; use hyper_serde::Serde; use servo_arc::Arc; use servo_url::ServoUrl; -use std::sync::Mutex; use std::sync::atomic::AtomicBool; +use std::sync::Mutex; /// [Response type](https://fetch.spec.whatwg.org/#concept-response-type) #[derive(Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] 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, rect: Rect) -> 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/heartbeats.rs b/components/profile/heartbeats.rs index ef95c853fce..4bdd5fd7527 100644 --- a/components/profile/heartbeats.rs +++ b/components/profile/heartbeats.rs @@ -2,9 +2,9 @@ * 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/. */ +use self::synchronized_heartbeat::{heartbeat_window_callback, lock_and_work}; use heartbeats_simple::HeartbeatPow as Heartbeat; use profile_traits::time::ProfilerCategory; -use self::synchronized_heartbeat::{heartbeat_window_callback, lock_and_work}; use servo_config::opts; use std::collections::HashMap; use std::env::var_os; @@ -139,12 +139,12 @@ fn log_heartbeat_records(hb: &mut Heartbeat) { } mod synchronized_heartbeat { + use super::log_heartbeat_records; use heartbeats_simple::HeartbeatPow as Heartbeat; use heartbeats_simple::HeartbeatPowContext as HeartbeatContext; use profile_traits::time::ProfilerCategory; use std::collections::HashMap; - use std::sync::atomic::{ATOMIC_BOOL_INIT, AtomicBool, Ordering}; - use super::log_heartbeat_records; + use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; static mut HBS: Option<*mut HashMap> = None; diff --git a/components/profile/mem.rs b/components/profile/mem.rs index 83756722e61..8e6a86c59cd 100644 --- a/components/profile/mem.rs +++ b/components/profile/mem.rs @@ -7,8 +7,8 @@ use crate::time::duration_from_seconds; use ipc_channel::ipc::{self, IpcReceiver}; use ipc_channel::router::ROUTER; -use profile_traits::mem::{ProfilerChan, ProfilerMsg, ReportKind, Reporter, ReporterRequest}; use profile_traits::mem::ReportsChan; +use profile_traits::mem::{ProfilerChan, ProfilerMsg, ReportKind, Reporter, ReporterRequest}; use std::borrow::ToOwned; use std::cmp::Ordering; use std::collections::HashMap; @@ -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); @@ -384,10 +386,11 @@ impl ReportsForest { //--------------------------------------------------------------------------- mod system_reporter { - #[cfg(all(feature = "unstable", not(target_os = "windows")))] - use libc::{c_void, size_t}; + use super::{JEMALLOC_HEAP_ALLOCATED_STR, SYSTEM_HEAP_ALLOCATED_STR}; #[cfg(target_os = "linux")] use libc::c_int; + #[cfg(all(feature = "unstable", not(target_os = "windows")))] + use libc::{c_void, size_t}; use profile_traits::mem::{Report, ReportKind, ReporterRequest}; #[cfg(all(feature = "unstable", not(target_os = "windows")))] use std::ffi::CString; @@ -395,9 +398,8 @@ mod system_reporter { use std::mem::size_of; #[cfg(all(feature = "unstable", not(target_os = "windows")))] use std::ptr::null_mut; - use super::{JEMALLOC_HEAP_ALLOCATED_STR, SYSTEM_HEAP_ALLOCATED_STR}; #[cfg(target_os = "macos")] - use task_info::task_basic_info::{virtual_size, resident_size}; + use task_info::task_basic_info::{resident_size, virtual_size}; /// Collects global measurements from the OS and heap allocators. pub fn collect_reports(request: ReporterRequest) { @@ -599,10 +601,10 @@ mod system_reporter { #[cfg(target_os = "linux")] fn resident_segments() -> Vec<(String, usize)> { use regex::Regex; - use std::collections::HashMap; use std::collections::hash_map::Entry; + use std::collections::HashMap; use std::fs::File; - use std::io::{BufReader, BufRead}; + use std::io::{BufRead, BufReader}; // The first line of an entry in /proc//smaps looks just like an entry // in /proc//maps: @@ -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..7cfdbcee14d 100644 --- a/components/profile/time.rs +++ b/components/profile/time.rs @@ -12,10 +12,11 @@ use influent::create_client; use influent::measurement::{Measurement, Value}; use ipc_channel::ipc::{self, IpcReceiver}; use profile_traits::energy::{energy_interval_ms, read_energy_uj}; -use profile_traits::time::{ProfilerCategory, ProfilerChan, ProfilerMsg, ProfilerData, TimerMetadata}; +use profile_traits::time::{ + ProfilerCategory, ProfilerChan, ProfilerData, ProfilerMsg, TimerMetadata, +}; use profile_traits::time::{TimerMetadataFrameType, TimerMetadataReflowType}; use servo_config::opts::OutputOptions; -use std::{f64, thread, u32, u64}; use std::borrow::ToOwned; use std::cmp::Ordering; use std::collections::BTreeMap; @@ -24,6 +25,7 @@ use std::fs::File; use std::io::{self, Write}; use std::path::Path; use std::time::Duration; +use std::{f64, thread, u32, u64}; use tokio; use tokio::prelude::Future; @@ -184,7 +186,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 +203,8 @@ impl Profiler { if chan.send(ProfilerMsg::Print).is_err() { break; } - }).expect("Thread spawning failed"); + }) + .expect("Thread spawning failed"); }, } }, @@ -214,7 +218,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 +233,8 @@ impl Profiler { }, _ => {}, } - }).expect("Thread spawning failed"); + }) + .expect("Thread spawning failed"); } }, } @@ -281,7 +287,8 @@ impl Profiler { start_time = end_time; start_energy = end_energy; } - }).expect("Thread spawning failed"); + }) + .expect("Thread spawning failed"); } profiler_chan @@ -323,9 +330,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 +390,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 +407,8 @@ impl Profiler { min, max, data_len - ).unwrap(); + ) + .unwrap(); } } }, @@ -417,7 +428,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 +445,8 @@ impl Profiler { min, max, data_len - ).unwrap(); + ) + .unwrap(); } } writeln!(&mut lock, "").unwrap(); @@ -473,8 +486,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, 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/profile_traits/time.rs b/components/profile_traits/time.rs index ec3e5520b3d..010bb009682 100644 --- a/components/profile_traits/time.rs +++ b/components/profile_traits/time.rs @@ -4,9 +4,9 @@ extern crate time as std_time; +use self::std_time::precise_time_ns; use crate::energy::read_energy_uj; use ipc_channel::ipc::IpcSender; -use self::std_time::precise_time_ns; use servo_config::opts; use signpost; diff --git a/components/rand/lib.rs b/components/rand/lib.rs index 5a10bf9e3c1..56c20522b76 100644 --- a/components/rand/lib.rs +++ b/components/rand/lib.rs @@ -19,13 +19,13 @@ extern crate log; extern crate rand; extern crate uuid; -pub use rand::{Rand, Rng, SeedableRng}; #[cfg(target_pointer_width = "64")] use rand::isaac::Isaac64Rng as IsaacWordRng; #[cfg(target_pointer_width = "32")] use rand::isaac::IsaacRng as IsaacWordRng; use rand::os::OsRng; -use rand::reseeding::{ReseedingRng, Reseeder}; +use rand::reseeding::{Reseeder, ReseedingRng}; +pub use rand::{Rand, Rng, SeedableRng}; use std::cell::RefCell; use std::mem; use std::rc::Rc; diff --git a/components/remutex/lib.rs b/components/remutex/lib.rs index 6f8f11ac498..d47237d0ef6 100644 --- a/components/remutex/lib.rs +++ b/components/remutex/lib.rs @@ -18,8 +18,8 @@ extern crate log; use std::cell::{Cell, UnsafeCell}; use std::num::NonZeroUsize; use std::ops::Deref; -use std::sync::{LockResult, Mutex, MutexGuard, PoisonError, TryLockError, TryLockResult}; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{LockResult, Mutex, MutexGuard, PoisonError, TryLockError, TryLockResult}; /// A type for thread ids. 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/clipboard_provider.rs b/components/script/clipboard_provider.rs index 8b9ce13b582..9ae2bdaa6ea 100644 --- a/components/script/clipboard_provider.rs +++ b/components/script/clipboard_provider.rs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use ipc_channel::ipc::channel; -use script_traits::{ScriptToConstellationChan, ScriptMsg}; +use script_traits::{ScriptMsg, ScriptToConstellationChan}; use std::borrow::ToOwned; pub trait ClipboardProvider { diff --git a/components/script/devtools.rs b/components/script/devtools.rs index d0409cf5fbc..ddc5528ecc4 100644 --- a/components/script/devtools.rs +++ b/components/script/devtools.rs @@ -7,7 +7,7 @@ use crate::dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods; use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use crate::dom::bindings::codegen::Bindings::ElementBinding::ElementMethods; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; -use crate::dom::bindings::conversions::{ConversionResult, FromJSValConvertible, jsstring_to_str}; +use crate::dom::bindings::conversions::{jsstring_to_str, ConversionResult, FromJSValConvertible}; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::DomObject; use crate::dom::bindings::root::DomRoot; @@ -15,13 +15,13 @@ use crate::dom::bindings::str::DOMString; use crate::dom::document::AnimationFrameCallback; use crate::dom::element::Element; use crate::dom::globalscope::GlobalScope; -use crate::dom::node::{Node, window_from_node}; +use crate::dom::node::{window_from_node, Node}; use crate::dom::window::Window; use crate::script_thread::Documents; +use devtools_traits::TimelineMarkerType; use devtools_traits::{AutoMargins, CachedConsoleMessage, CachedConsoleMessageTypes}; use devtools_traits::{ComputedNodeLayout, ConsoleAPI, PageError}; use devtools_traits::{EvaluateJSReply, Modification, NodeInfo, TimelineMarker}; -use devtools_traits::TimelineMarkerType; use ipc_channel::ipc::IpcSender; use js::jsapi::JSAutoCompartment; use js::jsval::UndefinedValue; @@ -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..433641961d4 100644 --- a/components/script/document_loader.rs +++ b/components/script/document_loader.rs @@ -10,9 +10,9 @@ use crate::dom::bindings::root::Dom; use crate::dom::document::Document; use crate::fetch::FetchCanceller; use ipc_channel::ipc::IpcSender; -use net_traits::{CoreResourceMsg, FetchChannels, FetchResponseMsg}; -use net_traits::{ResourceThreads, IpcSend}; use net_traits::request::RequestInit; +use net_traits::{CoreResourceMsg, FetchChannels, FetchResponseMsg}; +use net_traits::{IpcSend, ResourceThreads}; use servo_url::ServoUrl; use std::thread; @@ -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/abstractworkerglobalscope.rs b/components/script/dom/abstractworkerglobalscope.rs index 1ca0fdcacfd..ab919bd87c4 100644 --- a/components/script/dom/abstractworkerglobalscope.rs +++ b/components/script/dom/abstractworkerglobalscope.rs @@ -9,7 +9,7 @@ use crate::dom::dedicatedworkerglobalscope::{AutoWorkerReset, DedicatedWorkerScr use crate::dom::globalscope::GlobalScope; use crate::dom::worker::TrustedWorkerAddress; use crate::dom::workerglobalscope::WorkerGlobalScope; -use crate::script_runtime::{ScriptChan, CommonScriptMsg, ScriptPort}; +use crate::script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort}; use crate::task_queue::{QueuedTaskConversion, TaskQueue}; use devtools_traits::DevtoolScriptControlMsg; use servo_channel::{Receiver, Sender}; diff --git a/components/script/dom/analysernode.rs b/components/script/dom/analysernode.rs index 88cee14c3a1..cf04bd44fca 100644 --- a/components/script/dom/analysernode.rs +++ b/components/script/dom/analysernode.rs @@ -5,8 +5,12 @@ use crate::dom::audionode::AudioNode; use crate::dom::baseaudiocontext::BaseAudioContext; use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::AnalyserNodeBinding::{self, AnalyserNodeMethods, AnalyserOptions}; -use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ChannelCountMode, ChannelInterpretation}; +use crate::dom::bindings::codegen::Bindings::AnalyserNodeBinding::{ + self, AnalyserNodeMethods, AnalyserOptions, +}; +use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ + ChannelCountMode, ChannelInterpretation, +}; use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::num::Finite; use crate::dom::bindings::refcounted::Trusted; @@ -37,17 +41,20 @@ impl AnalyserNode { context: &BaseAudioContext, options: &AnalyserOptions, ) -> Fallible<(AnalyserNode, IpcReceiver)> { - let node_options = options.parent - .unwrap_or(2, ChannelCountMode::Max, - ChannelInterpretation::Speakers); + let node_options = + options + .parent + .unwrap_or(2, ChannelCountMode::Max, ChannelInterpretation::Speakers); - if options.fftSize > 32768 || options.fftSize < 32 || - (options.fftSize & (options.fftSize - 1) != 0) { - return Err(Error::IndexSize) + if options.fftSize > 32768 || + options.fftSize < 32 || + (options.fftSize & (options.fftSize - 1) != 0) + { + return Err(Error::IndexSize); } if *options.maxDecibels <= *options.minDecibels { - return Err(Error::IndexSize) + return Err(Error::IndexSize); } if *options.smoothingTimeConstant < 0. || *options.smoothingTimeConstant > 1. { @@ -67,14 +74,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 +101,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 +148,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 +157,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 +166,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 +195,7 @@ impl AnalyserNodeMethods for AnalyserNode { /// https://webaudio.github.io/web-audio-api/#dom-analysernode-mindecibels fn SetMinDecibels(&self, value: Finite) -> 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 +209,7 @@ impl AnalyserNodeMethods for AnalyserNode { /// https://webaudio.github.io/web-audio-api/#dom-analysernode-maxdecibels fn SetMaxDecibels(&self, value: Finite) -> 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 +223,9 @@ impl AnalyserNodeMethods for AnalyserNode { /// https://webaudio.github.io/web-audio-api/#dom-analysernode-smoothingtimeconstant fn SetSmoothingTimeConstant(&self, value: Finite) -> 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/attr.rs b/components/script/dom/attr.rs index b90fe33e347..955b05ebdd9 100644 --- a/components/script/dom/attr.rs +++ b/components/script/dom/attr.rs @@ -5,7 +5,7 @@ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods}; use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{DomRoot, LayoutDom, MutNullableDom, RootedReference}; use crate::dom::bindings::str::DOMString; use crate::dom::customelementregistry::CallbackReaction; @@ -17,7 +17,7 @@ use crate::dom::window::Window; use crate::script_thread::ScriptThread; use devtools_traits::AttrInfo; use dom_struct::dom_struct; -use html5ever::{Prefix, LocalName, Namespace}; +use html5ever::{LocalName, Namespace, Prefix}; use servo_atoms::Atom; use std::borrow::ToOwned; use std::cell::Ref; diff --git a/components/script/dom/audiobuffer.rs b/components/script/dom/audiobuffer.rs index 2ebdfee5377..8aa05a35e11 100644 --- a/components/script/dom/audiobuffer.rs +++ b/components/script/dom/audiobuffer.rs @@ -4,17 +4,19 @@ use crate::dom::audionode::MAX_CHANNEL_COUNT; use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::AudioBufferBinding::{self, AudioBufferMethods, AudioBufferOptions}; +use crate::dom::bindings::codegen::Bindings::AudioBufferBinding::{ + self, AudioBufferMethods, AudioBufferOptions, +}; use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::num::Finite; -use crate::dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::window::Window; use dom_struct::dom_struct; -use js::jsapi::{Heap, JSAutoCompartment, JSContext, JSObject}; use js::jsapi::JS_GetArrayBufferViewBuffer; -use js::rust::CustomAutoRooterGuard; +use js::jsapi::{Heap, JSAutoCompartment, JSContext, JSObject}; use js::rust::wrappers::JS_DetachArrayBuffer; +use js::rust::CustomAutoRooterGuard; use js::typedarray::{CreateWith, Float32Array}; use servo_media::audio::buffer_source_node::AudioBuffer as ServoMediaAudioBuffer; use std::cell::Ref; @@ -110,10 +112,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]>) { - 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 +143,8 @@ impl AudioBuffer { cx, CreateWith::Slice(&shared_channels.buffers[i]), array.handle_mut(), - ).is_err() + ) + .is_err() { return false; } @@ -159,10 +160,8 @@ impl AudioBuffer { // https://webaudio.github.io/web-audio-api/#acquire-the-content #[allow(unsafe_code)] fn acquire_contents(&self) -> Option { - 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 +202,7 @@ impl AudioBuffer { *self.shared_channels.borrow_mut() = channels; } } - return self.shared_channels.borrow() + return self.shared_channels.borrow(); } } @@ -324,7 +323,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/audiobuffersourcenode.rs b/components/script/dom/audiobuffersourcenode.rs index 7dbe2550b62..09f6e7dadc6 100644 --- a/components/script/dom/audiobuffersourcenode.rs +++ b/components/script/dom/audiobuffersourcenode.rs @@ -20,7 +20,7 @@ use crate::dom::window::Window; use dom_struct::dom_struct; use servo_media::audio::buffer_source_node::AudioBufferSourceNodeMessage; use servo_media::audio::buffer_source_node::AudioBufferSourceNodeOptions; -use servo_media::audio::node::{AudioNodeMessage, AudioNodeInit}; +use servo_media::audio::node::{AudioNodeInit, AudioNodeMessage}; use servo_media::audio::param::ParamType; use std::cell::Cell; use std::f32; diff --git a/components/script/dom/audiocontext.rs b/components/script/dom/audiocontext.rs index af7e63aa83d..03cdb516139 100644 --- a/components/script/dom/audiocontext.rs +++ b/components/script/dom/audiocontext.rs @@ -4,15 +4,19 @@ use crate::dom::baseaudiocontext::{BaseAudioContext, BaseAudioContextOptions}; use crate::dom::bindings::codegen::Bindings::AudioContextBinding; -use crate::dom::bindings::codegen::Bindings::AudioContextBinding::{AudioContextLatencyCategory, AudioContextMethods}; -use crate::dom::bindings::codegen::Bindings::AudioContextBinding::{AudioContextOptions, AudioTimestamp}; +use crate::dom::bindings::codegen::Bindings::AudioContextBinding::{ + AudioContextLatencyCategory, AudioContextMethods, +}; +use crate::dom::bindings::codegen::Bindings::AudioContextBinding::{ + AudioContextOptions, AudioTimestamp, +}; use crate::dom::bindings::codegen::Bindings::BaseAudioContextBinding::AudioContextState; use crate::dom::bindings::codegen::Bindings::BaseAudioContextBinding::BaseAudioContextBinding::BaseAudioContextMethods; use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::num::Finite; use crate::dom::bindings::refcounted::{Trusted, TrustedPromise}; -use crate::dom::bindings::reflector::{DomObject, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::DomRoot; use crate::dom::promise::Promise; use crate::dom::window::Window; diff --git a/components/script/dom/audiodestinationnode.rs b/components/script/dom/audiodestinationnode.rs index e2e8905774b..42336b862aa 100644 --- a/components/script/dom/audiodestinationnode.rs +++ b/components/script/dom/audiodestinationnode.rs @@ -4,9 +4,13 @@ use crate::dom::audionode::{AudioNode, MAX_CHANNEL_COUNT}; use crate::dom::baseaudiocontext::BaseAudioContext; -use crate::dom::bindings::codegen::Bindings::AudioDestinationNodeBinding::{self, AudioDestinationNodeMethods}; -use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ChannelCountMode, ChannelInterpretation}; +use crate::dom::bindings::codegen::Bindings::AudioDestinationNodeBinding::{ + self, AudioDestinationNodeMethods, +}; use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::AudioNodeOptions; +use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ + ChannelCountMode, ChannelInterpretation, +}; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; diff --git a/components/script/dom/audiolistener.rs b/components/script/dom/audiolistener.rs index ef2be88799d..f9ad0ff35d0 100644 --- a/components/script/dom/audiolistener.rs +++ b/components/script/dom/audiolistener.rs @@ -6,11 +6,11 @@ use crate::dom::audioparam::AudioParam; use crate::dom::baseaudiocontext::BaseAudioContext; use crate::dom::bindings::codegen::Bindings::AudioListenerBinding::{self, AudioListenerMethods}; use crate::dom::bindings::codegen::Bindings::AudioParamBinding::AutomationRate; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::window::Window; use dom_struct::dom_struct; -use servo_media::audio::param::{ParamType, ParamDir}; +use servo_media::audio::param::{ParamDir, ParamType}; use std::f32; #[dom_struct] diff --git a/components/script/dom/audionode.rs b/components/script/dom/audionode.rs index b96dde64a4c..17aabade2e7 100644 --- a/components/script/dom/audionode.rs +++ b/components/script/dom/audionode.rs @@ -4,8 +4,12 @@ use crate::dom::audioparam::AudioParam; use crate::dom::baseaudiocontext::BaseAudioContext; -use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{AudioNodeMethods, AudioNodeOptions}; -use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ChannelCountMode, ChannelInterpretation}; +use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ + AudioNodeMethods, AudioNodeOptions, +}; +use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ + ChannelCountMode, ChannelInterpretation, +}; use crate::dom::bindings::codegen::InheritTypes::{AudioNodeTypeId, EventTargetTypeId}; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::inheritance::Castable; @@ -13,9 +17,9 @@ use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::eventtarget::EventTarget; use dom_struct::dom_struct; use servo_media::audio::graph::NodeId; -use servo_media::audio::node::{AudioNodeMessage, AudioNodeInit, ChannelInfo}; use servo_media::audio::node::ChannelCountMode as ServoMediaChannelCountMode; use servo_media::audio::node::ChannelInterpretation as ServoMediaChannelInterpretation; +use servo_media::audio::node::{AudioNodeInit, AudioNodeMessage, ChannelInfo}; use std::cell::Cell; // 32 is the minimum required by the spec for createBuffer() and the deprecated diff --git a/components/script/dom/audioparam.rs b/components/script/dom/audioparam.rs index d35bac52c44..659b4dde76d 100644 --- a/components/script/dom/audioparam.rs +++ b/components/script/dom/audioparam.rs @@ -4,9 +4,11 @@ use crate::dom::baseaudiocontext::BaseAudioContext; use crate::dom::bindings::codegen::Bindings::AudioParamBinding; -use crate::dom::bindings::codegen::Bindings::AudioParamBinding::{AudioParamMethods, AutomationRate}; +use crate::dom::bindings::codegen::Bindings::AudioParamBinding::{ + AudioParamMethods, AutomationRate, +}; use crate::dom::bindings::num::Finite; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::window::Window; use dom_struct::dom_struct; diff --git a/components/script/dom/audioscheduledsourcenode.rs b/components/script/dom/audioscheduledsourcenode.rs index fa094555c1e..31527fda3de 100644 --- a/components/script/dom/audioscheduledsourcenode.rs +++ b/components/script/dom/audioscheduledsourcenode.rs @@ -12,8 +12,8 @@ use crate::dom::bindings::refcounted::Trusted; use crate::dom::bindings::reflector::DomObject; use crate::task_source::{TaskSource, TaskSourceName}; use dom_struct::dom_struct; -use servo_media::audio::node::{AudioNodeMessage, AudioNodeInit, AudioScheduledSourceNodeMessage}; use servo_media::audio::node::OnEndedCallback; +use servo_media::audio::node::{AudioNodeInit, AudioNodeMessage, AudioScheduledSourceNodeMessage}; use std::cell::Cell; #[dom_struct] diff --git a/components/script/dom/baseaudiocontext.rs b/components/script/dom/baseaudiocontext.rs index 95ad60314ee..3b9a0a6b105 100644 --- a/components/script/dom/baseaudiocontext.rs +++ b/components/script/dom/baseaudiocontext.rs @@ -12,8 +12,10 @@ use crate::dom::bindings::callback::ExceptionHandling; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::AnalyserNodeBinding::AnalyserOptions; use crate::dom::bindings::codegen::Bindings::AudioBufferSourceNodeBinding::AudioBufferSourceOptions; -use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ChannelCountMode, ChannelInterpretation}; use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::AudioNodeOptions; +use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ + ChannelCountMode, ChannelInterpretation, +}; use crate::dom::bindings::codegen::Bindings::BaseAudioContextBinding::AudioContextState; use crate::dom::bindings::codegen::Bindings::BaseAudioContextBinding::BaseAudioContextMethods; use crate::dom::bindings::codegen::Bindings::BaseAudioContextBinding::DecodeErrorCallback; @@ -42,11 +44,11 @@ use crate::task_source::{TaskSource, TaskSourceName}; use dom_struct::dom_struct; use js::rust::CustomAutoRooterGuard; use js::typedarray::ArrayBuffer; -use servo_media::{Backend, ServoMedia}; use servo_media::audio::context::{AudioContext, AudioContextOptions, ProcessingState}; use servo_media::audio::context::{OfflineAudioContextOptions, RealTimeAudioContextOptions}; use servo_media::audio::decoder::AudioDecoderCallbacks; use servo_media::audio::graph::NodeId; +use servo_media::{Backend, ServoMedia}; use std::cell::Cell; use std::collections::{HashMap, VecDeque}; use std::mem; @@ -348,7 +350,11 @@ impl BaseAudioContextMethods for BaseAudioContext { /// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbiquadfilter fn CreateBiquadFilter(&self) -> Fallible> { - 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 +438,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 +469,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 +487,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/callback.rs b/components/script/dom/bindings/callback.rs index 4db1fdf22cd..365817dcff1 100644 --- a/components/script/dom/bindings/callback.rs +++ b/components/script/dom/bindings/callback.rs @@ -4,19 +4,19 @@ //! Base classes to work with IDL callbacks. -use crate::dom::bindings::error::{Error, Fallible, report_pending_exception}; +use crate::dom::bindings::error::{report_pending_exception, Error, Fallible}; use crate::dom::bindings::reflector::DomObject; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::settings_stack::{AutoEntryScript, AutoIncumbentScript}; use crate::dom::bindings::utils::AsCCharPtrPtr; use crate::dom::globalscope::GlobalScope; -use js::jsapi::{IsCallable, JSContext, JSObject, AddRawValueRoot}; -use js::jsapi::{JSCompartment, JS_EnterCompartment, JS_LeaveCompartment, RemoveRawValueRoot}; use js::jsapi::Heap; use js::jsapi::JSAutoCompartment; -use js::jsval::{JSVal, UndefinedValue, ObjectValue}; +use js::jsapi::{AddRawValueRoot, IsCallable, JSContext, JSObject}; +use js::jsapi::{JSCompartment, JS_EnterCompartment, JS_LeaveCompartment, RemoveRawValueRoot}; +use js::jsval::{JSVal, ObjectValue, UndefinedValue}; +use js::rust::wrappers::{JS_GetProperty, JS_WrapObject}; use js::rust::{MutableHandleObject, Runtime}; -use js::rust::wrappers::{JS_WrapObject, JS_GetProperty}; use std::default::Default; use std::ffi::CString; use std::mem::drop; diff --git a/components/script/dom/bindings/constant.rs b/components/script/dom/bindings/constant.rs index 0329d106132..4d88d485ee3 100644 --- a/components/script/dom/bindings/constant.rs +++ b/components/script/dom/bindings/constant.rs @@ -4,11 +4,11 @@ //! WebIDL constants. -use js::jsapi::{JSContext, JSPROP_ENUMERATE, JSPROP_PERMANENT}; use js::jsapi::JSPROP_READONLY; +use js::jsapi::{JSContext, JSPROP_ENUMERATE, JSPROP_PERMANENT}; use js::jsval::{BooleanValue, DoubleValue, Int32Value, JSVal, NullValue, UInt32Value}; -use js::rust::HandleObject; use js::rust::wrappers::JS_DefineProperty; +use js::rust::HandleObject; use libc; /// Representation of an IDL constant. diff --git a/components/script/dom/bindings/conversions.rs b/components/script/dom/bindings/conversions.rs index aecaf0c1a04..a96371aaf06 100644 --- a/components/script/dom/bindings/conversions.rs +++ b/components/script/dom/bindings/conversions.rs @@ -41,22 +41,24 @@ use crate::dom::bindings::str::{ByteString, DOMString, USVString}; use crate::dom::bindings::trace::{JSTraceable, RootedTraceableBox}; use crate::dom::bindings::utils::DOMClass; use js; -pub use js::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible}; -pub use js::conversions::ConversionBehavior; use js::conversions::latin1_to_string; +pub use js::conversions::ConversionBehavior; +pub use js::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible}; use js::error::throw_type_error; +use js::glue::GetProxyReservedSlot; +use js::glue::JS_GetReservedSlot; use js::glue::{IsWrapper, UnwrapObject}; use js::glue::{RUST_JSID_IS_INT, RUST_JSID_TO_INT}; use js::glue::{RUST_JSID_IS_STRING, RUST_JSID_TO_STRING}; -use js::glue::GetProxyReservedSlot; -use js::glue::JS_GetReservedSlot; use js::jsapi::{Heap, JSContext, JSObject, JSString}; -use js::jsapi::{JS_GetLatin1StringCharsAndLength, JS_GetTwoByteStringCharsAndLength, JS_IsExceptionPending}; +use js::jsapi::{ + JS_GetLatin1StringCharsAndLength, JS_GetTwoByteStringCharsAndLength, JS_IsExceptionPending, +}; use js::jsapi::{JS_NewStringCopyN, JS_StringHasLatin1Chars}; use js::jsval::{ObjectValue, StringValue, UndefinedValue}; -use js::rust::{HandleId, HandleObject, HandleValue, MutableHandleValue}; -use js::rust::{get_object_class, is_dom_class, is_dom_object, maybe_wrap_value, ToString}; use js::rust::wrappers::{JS_GetProperty, JS_IsArrayObject}; +use js::rust::{get_object_class, is_dom_class, is_dom_object, maybe_wrap_value, ToString}; +use js::rust::{HandleId, HandleObject, HandleValue, MutableHandleValue}; use libc; use num_traits::Float; use servo_config::opts; diff --git a/components/script/dom/bindings/error.rs b/components/script/dom/bindings/error.rs index 061e74fb3cc..bba99606ae7 100644 --- a/components/script/dom/bindings/error.rs +++ b/components/script/dom/bindings/error.rs @@ -10,8 +10,10 @@ use backtrace::Backtrace; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods; use crate::dom::bindings::codegen::PrototypeList::proto_id_to_name; -use crate::dom::bindings::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible}; use crate::dom::bindings::conversions::root_from_object; +use crate::dom::bindings::conversions::{ + ConversionResult, FromJSValConvertible, ToJSValConvertible, +}; use crate::dom::bindings::str::USVString; use crate::dom::domexception::{DOMErrorName, DOMException}; use crate::dom::globalscope::GlobalScope; @@ -20,11 +22,11 @@ use js::jsapi::JSContext; use js::jsapi::JS_ClearPendingException; use js::jsapi::JS_IsExceptionPending; use js::jsval::UndefinedValue; -use js::rust::HandleObject; -use js::rust::MutableHandleValue; use js::rust::wrappers::JS_ErrorFromException; use js::rust::wrappers::JS_GetPendingException; use js::rust::wrappers::JS_SetPendingException; +use js::rust::HandleObject; +use js::rust::MutableHandleValue; use libc::c_uint; use std::slice::from_raw_parts; diff --git a/components/script/dom/bindings/htmlconstructor.rs b/components/script/dom/bindings/htmlconstructor.rs index 9923ad8716d..f0f46aabeec 100644 --- a/components/script/dom/bindings/htmlconstructor.rs +++ b/components/script/dom/bindings/htmlconstructor.rs @@ -77,8 +77,8 @@ use crate::dom::element::{CustomElementState, Element, ElementCreator}; use crate::dom::htmlelement::HTMLElement; use crate::dom::window::Window; use crate::script_thread::ScriptThread; -use html5ever::LocalName; use html5ever::interface::QualName; +use html5ever::LocalName; use js::glue::UnwrapObject; use js::jsapi::{CallArgs, CurrentGlobalOrNull}; use js::jsapi::{JSAutoCompartment, JSContext, JSObject}; diff --git a/components/script/dom/bindings/inheritance.rs b/components/script/dom/bindings/inheritance.rs index 5e535a0a0ba..888e0525fea 100644 --- a/components/script/dom/bindings/inheritance.rs +++ b/components/script/dom/bindings/inheritance.rs @@ -6,8 +6,8 @@ pub use crate::dom::bindings::codegen::InheritTypes::*; -use crate::dom::bindings::conversions::{DerivedFrom, IDLInterface}; use crate::dom::bindings::conversions::get_dom_class; +use crate::dom::bindings::conversions::{DerivedFrom, IDLInterface}; use crate::dom::bindings::reflector::DomObject; use std::mem; diff --git a/components/script/dom/bindings/interface.rs b/components/script/dom/bindings/interface.rs index e390eb54742..5389fabd07d 100644 --- a/components/script/dom/bindings/interface.rs +++ b/components/script/dom/bindings/interface.rs @@ -9,28 +9,32 @@ use crate::dom::bindings::codegen::PrototypeList; use crate::dom::bindings::constant::{define_constants, ConstantSpec}; use crate::dom::bindings::conversions::{get_dom_class, DOM_OBJECT_SLOT}; use crate::dom::bindings::guard::Guard; -use crate::dom::bindings::utils::{get_proto_or_iface_array, ProtoOrIfaceArray, DOM_PROTOTYPE_SLOT}; +use crate::dom::bindings::utils::{ + get_proto_or_iface_array, ProtoOrIfaceArray, DOM_PROTOTYPE_SLOT, +}; use js::error::throw_type_error; use js::glue::{UncheckedUnwrapObject, RUST_SYMBOL_TO_JSID}; +use js::jsapi::HandleObject as RawHandleObject; +use js::jsapi::MutableHandleValue as RawMutableHandleValue; use js::jsapi::{Class, ClassOps, CompartmentOptions}; use js::jsapi::{GetGlobalForObjectCrossCompartment, GetWellKnownSymbol}; -use js::jsapi::{JSAutoCompartment, JSClass, JSContext, JSFunctionSpec, JSObject, JSFUN_CONSTRUCTOR}; -use js::jsapi::{JSPROP_PERMANENT, JSPROP_READONLY, JSPROP_RESOLVING}; +use js::jsapi::{ + JSAutoCompartment, JSClass, JSContext, JSFunctionSpec, JSObject, JSFUN_CONSTRUCTOR, +}; use js::jsapi::{JSPropertySpec, JSString, JSTracer, JS_AtomizeAndPinString}; use js::jsapi::{JS_GetFunctionObject, JS_NewFunction, JS_NewGlobalObject}; use js::jsapi::{JS_NewObject, JS_NewPlainObject}; use js::jsapi::{JS_NewStringCopyN, JS_SetReservedSlot}; use js::jsapi::{ObjectOps, OnNewGlobalHookOption, SymbolCode}; use js::jsapi::{TrueHandleValue, Value}; -use js::jsapi::HandleObject as RawHandleObject; -use js::jsapi::MutableHandleValue as RawMutableHandleValue; +use js::jsapi::{JSPROP_PERMANENT, JSPROP_READONLY, JSPROP_RESOLVING}; use js::jsval::{JSVal, PrivateValue}; -use js::rust::{HandleObject, HandleValue, MutableHandleObject}; -use js::rust::{define_methods, define_properties, get_object_class}; use js::rust::wrappers::{JS_DefineProperty, JS_DefineProperty2}; use js::rust::wrappers::{JS_DefineProperty3, JS_DefineProperty4, JS_DefinePropertyById4}; use js::rust::wrappers::{JS_FireOnNewGlobalObject, JS_GetPrototype}; use js::rust::wrappers::{JS_LinkConstructorAndPrototype, JS_NewObjectWithUniqueType}; +use js::rust::{define_methods, define_properties, get_object_class}; +use js::rust::{HandleObject, HandleValue, MutableHandleObject}; use libc; use std::convert::TryFrom; use std::ptr; diff --git a/components/script/dom/bindings/iterable.rs b/components/script/dom/bindings/iterable.rs index c8b6caf5f42..b75dba9591b 100644 --- a/components/script/dom/bindings/iterable.rs +++ b/components/script/dom/bindings/iterable.rs @@ -9,7 +9,7 @@ use crate::dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyAndValueResult; use crate::dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyOrValueResult; use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::trace::{JSTraceable, RootedTraceableBox}; use crate::dom::globalscope::GlobalScope; diff --git a/components/script/dom/bindings/mozmap.rs b/components/script/dom/bindings/mozmap.rs index 5c0451cca71..4d74a6405b0 100644 --- a/components/script/dom/bindings/mozmap.rs +++ b/components/script/dom/bindings/mozmap.rs @@ -9,19 +9,19 @@ use crate::dom::bindings::error::report_pending_exception; use crate::dom::bindings::str::DOMString; use js::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible}; use js::jsapi::JSContext; +use js::jsapi::JS_NewPlainObject; use js::jsapi::JSITER_HIDDEN; use js::jsapi::JSITER_OWNONLY; use js::jsapi::JSITER_SYMBOLS; use js::jsapi::JSPROP_ENUMERATE; -use js::jsapi::JS_NewPlainObject; use js::jsval::ObjectValue; use js::jsval::UndefinedValue; -use js::rust::HandleValue; -use js::rust::IdVector; -use js::rust::MutableHandleValue; use js::rust::wrappers::GetPropertyKeys; use js::rust::wrappers::JS_DefineUCProperty2; use js::rust::wrappers::JS_GetPropertyById; +use js::rust::HandleValue; +use js::rust::IdVector; +use js::rust::MutableHandleValue; use std::collections::HashMap; use std::ops::Deref; diff --git a/components/script/dom/bindings/proxyhandler.rs b/components/script/dom/bindings/proxyhandler.rs index 924696ecb26..a4584f2daa1 100644 --- a/components/script/dom/bindings/proxyhandler.rs +++ b/components/script/dom/bindings/proxyhandler.rs @@ -8,11 +8,9 @@ use crate::dom::bindings::conversions::is_dom_proxy; use crate::dom::bindings::utils::delete_property_by_id; +use js::glue::InvokeGetOwnPropertyDescriptor; use js::glue::{GetProxyHandler, GetProxyHandlerFamily}; use js::glue::{GetProxyPrivate, SetProxyPrivate}; -use js::glue::InvokeGetOwnPropertyDescriptor; -use js::jsapi::{DOMProxyShadowsResult, JSContext, JSObject, PropertyDescriptor}; -use js::jsapi::{JSErrNum, SetDOMProxyInformation}; use js::jsapi::GetObjectProto; use js::jsapi::GetStaticPrototype; use js::jsapi::Handle as RawHandle; @@ -23,11 +21,13 @@ use js::jsapi::JS_GetPropertyDescriptorById; use js::jsapi::MutableHandle as RawMutableHandle; use js::jsapi::MutableHandleObject as RawMutableHandleObject; use js::jsapi::ObjectOpResult; +use js::jsapi::{DOMProxyShadowsResult, JSContext, JSObject, PropertyDescriptor}; +use js::jsapi::{JSErrNum, SetDOMProxyInformation}; use js::jsval::ObjectValue; use js::jsval::UndefinedValue; -use js::rust::{Handle, HandleObject, MutableHandle, MutableHandleObject}; use js::rust::wrappers::JS_AlreadyHasOwnPropertyById; use js::rust::wrappers::JS_NewObjectWithGivenProto; +use js::rust::{Handle, HandleObject, MutableHandle, MutableHandleObject}; use std::ptr; /// Determine if this id shadows any existing properties for this proxy. diff --git a/components/script/dom/bindings/refcounted.rs b/components/script/dom/bindings/refcounted.rs index 740cb82b520..ca6bf086960 100644 --- a/components/script/dom/bindings/refcounted.rs +++ b/components/script/dom/bindings/refcounted.rs @@ -42,9 +42,9 @@ use std::sync::{Arc, Weak}; #[allow(missing_docs)] // FIXME mod dummy { // Attributes don’t apply through the macro. + use super::LiveDOMReferences; use std::cell::RefCell; use std::rc::Rc; - use super::LiveDOMReferences; thread_local!(pub static LIVE_REFERENCES: Rc>> = Rc::new(RefCell::new(None))); } diff --git a/components/script/dom/bindings/reflector.rs b/components/script/dom/bindings/reflector.rs index a86f502e235..0d27a5206db 100644 --- a/components/script/dom/bindings/reflector.rs +++ b/components/script/dom/bindings/reflector.rs @@ -7,7 +7,7 @@ use crate::dom::bindings::conversions::DerivedFrom; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; -use js::jsapi::{JSContext, JSObject, Heap}; +use js::jsapi::{Heap, JSContext, JSObject}; use js::rust::HandleObject; use std::default::Default; diff --git a/components/script/dom/bindings/root.rs b/components/script/dom/bindings/root.rs index 8c4a528b67a..25b77e052e6 100644 --- a/components/script/dom/bindings/root.rs +++ b/components/script/dom/bindings/root.rs @@ -27,10 +27,10 @@ use crate::dom::bindings::conversions::DerivedFrom; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::{DomObject, Reflector}; -use crate::dom::bindings::trace::JSTraceable; use crate::dom::bindings::trace::trace_reflector; +use crate::dom::bindings::trace::JSTraceable; use crate::dom::node::Node; -use js::jsapi::{JSObject, JSTracer, Heap}; +use js::jsapi::{Heap, JSObject, JSTracer}; use js::rust::GCMethods; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use mitochondria::OnceCell; 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 { .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/str.rs b/components/script/dom/bindings/str.rs index e52cf7755a3..9f038026562 100644 --- a/components/script/dom/bindings/str.rs +++ b/components/script/dom/bindings/str.rs @@ -4,8 +4,8 @@ //! The `ByteString` struct. +use chrono::prelude::{Utc, Weekday}; use chrono::{Datelike, TimeZone}; -use chrono::prelude::{Weekday, Utc}; use cssparser::CowRcStr; use html5ever::{LocalName, Namespace}; use servo_atoms::Atom; diff --git a/components/script/dom/bindings/structuredclone.rs b/components/script/dom/bindings/structuredclone.rs index 094749ff875..d4cc8c1cdae 100644 --- a/components/script/dom/bindings/structuredclone.rs +++ b/components/script/dom/bindings/structuredclone.rs @@ -16,19 +16,19 @@ use js::glue::DeleteJSAutoStructuredCloneBuffer; use js::glue::GetLengthOfJSStructuredCloneData; use js::glue::NewJSAutoStructuredCloneBuffer; use js::glue::WriteBytesToJSStructuredCloneData; -use js::jsapi::{JSAutoCompartment, JSContext}; -use js::jsapi::{JSStructuredCloneCallbacks, JSStructuredCloneReader, JSStructuredCloneWriter}; -use js::jsapi::{JS_ClearPendingException, JSObject}; -use js::jsapi::{JS_ReadBytes, JS_WriteBytes}; -use js::jsapi::{JS_ReadUint32Pair, JS_WriteUint32Pair}; use js::jsapi::CloneDataPolicy; use js::jsapi::HandleObject as RawHandleObject; -use js::jsapi::JS_STRUCTURED_CLONE_VERSION; use js::jsapi::MutableHandleObject as RawMutableHandleObject; use js::jsapi::StructuredCloneScope; use js::jsapi::TransferableOwnership; +use js::jsapi::JS_STRUCTURED_CLONE_VERSION; +use js::jsapi::{JSAutoCompartment, JSContext}; +use js::jsapi::{JSObject, JS_ClearPendingException}; +use js::jsapi::{JSStructuredCloneCallbacks, JSStructuredCloneReader, JSStructuredCloneWriter}; +use js::jsapi::{JS_ReadBytes, JS_WriteBytes}; +use js::jsapi::{JS_ReadUint32Pair, JS_WriteUint32Pair}; +use js::rust::wrappers::{JS_ReadStructuredClone, JS_WriteStructuredClone}; use js::rust::{Handle, HandleValue, MutableHandleValue}; -use js::rust::wrappers::{JS_WriteStructuredClone, JS_ReadStructuredClone}; use libc::size_t; use std::os::raw; use std::ptr; diff --git a/components/script/dom/bindings/trace.rs b/components/script/dom/bindings/trace.rs index 669f9481fb5..d45bbdef121 100644 --- a/components/script/dom/bindings/trace.rs +++ b/components/script/dom/bindings/trace.rs @@ -30,7 +30,9 @@ //! `JSTraceable` to a datatype. use app_units::Au; -use canvas_traits::canvas::{CanvasGradientStop, CanvasId, LinearGradientStyle, RadialGradientStyle}; +use canvas_traits::canvas::{ + CanvasGradientStop, CanvasId, LinearGradientStyle, RadialGradientStyle, +}; use canvas_traits::canvas::{CompositionOrBlending, LineCapStyle, LineJoinStyle, RepetitionStyle}; use canvas_traits::webgl::{ActiveAttribInfo, ActiveUniformInfo, WebGLBufferId, WebGLChan}; use canvas_traits::webgl::{WebGLContextShareMode, WebGLError, WebGLFramebufferId, WebGLMsgSender}; @@ -50,11 +52,11 @@ use crate::dom::htmlmediaelement::MediaFrameRenderer; use cssparser::RGBA; use devtools_traits::{CSSError, TimelineMarkerType, WorkerId}; use encoding_rs::{Decoder, Encoding}; -use euclid::{Transform2D, Transform3D, Point2D, Vector2D, Rect, TypedSize2D, TypedScale}; use euclid::Length as EuclidLength; -use html5ever::{Prefix, LocalName, Namespace, QualName}; +use euclid::{Point2D, Rect, Transform2D, Transform3D, TypedScale, TypedSize2D, Vector2D}; use html5ever::buffer_queue::BufferQueue; use html5ever::tendril::IncompleteUtf8; +use html5ever::{LocalName, Namespace, Prefix, QualName}; use http::header::HeaderMap; use hyper::Method; use hyper::StatusCode; @@ -67,31 +69,31 @@ use js::typedarray::TypedArray; use js::typedarray::TypedArrayElement; use metrics::{InteractiveMetrics, InteractiveWindow}; use mime::Mime; -use msg::constellation_msg::{BrowsingContextId, HistoryStateId, PipelineId, TopLevelBrowsingContextId}; -use net_traits::{Metadata, NetworkError, ReferrerPolicy, ResourceThreads}; +use msg::constellation_msg::{ + BrowsingContextId, HistoryStateId, PipelineId, TopLevelBrowsingContextId, +}; use net_traits::filemanager_thread::RelativePos; use net_traits::image::base::{Image, ImageMetadata}; use net_traits::image_cache::{ImageCache, PendingImageId}; use net_traits::request::{Request, RequestInit}; -use net_traits::response::{Response, ResponseBody}; use net_traits::response::HttpsState; +use net_traits::response::{Response, ResponseBody}; use net_traits::storage_thread::StorageType; +use net_traits::{Metadata, NetworkError, ReferrerPolicy, ResourceThreads}; use offscreen_gl_context::GLLimits; use profile_traits::mem::ProfilerChan as MemProfilerChan; use profile_traits::time::ProfilerChan as TimeProfilerChan; -use script_layout_interface::OpaqueStyleAndLayoutData; use script_layout_interface::reporter::CSSErrorReporter; use script_layout_interface::rpc::LayoutRPC; +use script_layout_interface::OpaqueStyleAndLayoutData; +use script_traits::DrawAPaintImageResult; use script_traits::{DocumentActivity, ScriptToConstellationChan, TimerEventId, TimerSource}; use script_traits::{UntrustedNodeAddress, WindowSizeData, WindowSizeType}; -use script_traits::DrawAPaintImageResult; use selectors::matching::ElementSelectorFlags; use serde::{Deserialize, Serialize}; use servo_arc::Arc as ServoArc; use servo_atoms::Atom; use servo_channel::{Receiver, Sender}; -use servo_media::Backend; -use servo_media::Error as ServoMediaError; use servo_media::audio::analyser_node::AnalysisEngine; use servo_media::audio::buffer_source_node::AudioBuffer; use servo_media::audio::context::AudioContext; @@ -99,6 +101,8 @@ use servo_media::audio::graph::NodeId; use servo_media::audio::panner_node::{DistanceModel, PanningModel}; use servo_media::audio::param::ParamType; use servo_media::player::Player; +use servo_media::Backend; +use servo_media::Error as ServoMediaError; use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl}; use smallvec::SmallVec; use std::cell::{Cell, RefCell, UnsafeCell}; @@ -107,20 +111,20 @@ use std::hash::{BuildHasher, Hash}; use std::ops::{Deref, DerefMut}; use std::path::PathBuf; use std::rc::Rc; -use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicBool, AtomicUsize}; -use std::time::{SystemTime, Instant}; +use std::sync::{Arc, Mutex}; +use std::time::{Instant, SystemTime}; use style::attr::{AttrIdentifier, AttrValue, LengthOrPercentageOrAuto}; use style::context::QuirksMode; use style::element_state::*; use style::media_queries::MediaList; use style::properties::PropertyDeclarationBlock; use style::selector_parser::{PseudoElement, Snapshot}; -use style::shared_lock::{SharedRwLock as StyleSharedRwLock, Locked as StyleLocked}; +use style::shared_lock::{Locked as StyleLocked, SharedRwLock as StyleSharedRwLock}; use style::stylesheet_set::DocumentStylesheetSet; -use style::stylesheets::{CssRules, FontFaceRule, KeyframesRule, MediaRule, Stylesheet}; -use style::stylesheets::{NamespaceRule, StyleRule, ImportRule, SupportsRule, ViewportRule}; use style::stylesheets::keyframes_rule::Keyframe; +use style::stylesheets::{CssRules, FontFaceRule, KeyframesRule, MediaRule, Stylesheet}; +use style::stylesheets::{ImportRule, NamespaceRule, StyleRule, SupportsRule, ViewportRule}; use style::values::specified::Length; use time::Duration; use uuid::Uuid; @@ -457,7 +461,7 @@ unsafe_no_jsmanaged_fields!(AudioBuffer); unsafe_no_jsmanaged_fields!(AudioContext); unsafe_no_jsmanaged_fields!(NodeId); unsafe_no_jsmanaged_fields!(AnalysisEngine, DistanceModel, PanningModel, ParamType); -unsafe_no_jsmanaged_fields!(Player); +unsafe_no_jsmanaged_fields!(Player); unsafe_no_jsmanaged_fields!(Mutex); unsafe_no_jsmanaged_fields!(RenderApiSender); diff --git a/components/script/dom/bindings/utils.rs b/components/script/dom/bindings/utils.rs index 8579103afd5..177239537ba 100644 --- a/components/script/dom/bindings/utils.rs +++ b/components/script/dom/bindings/utils.rs @@ -14,23 +14,20 @@ use crate::dom::bindings::str::DOMString; use crate::dom::bindings::trace::trace_object; use crate::dom::windowproxy; use js; -use js::JS_CALLEE; use js::glue::{CallJitGetterOp, CallJitMethodOp, CallJitSetterOp, IsWrapper}; use js::glue::{GetCrossCompartmentWrapper, JS_GetReservedSlot, WrapperNew}; +use js::glue::{UnwrapObject, RUST_JSID_TO_INT, RUST_JSID_TO_STRING}; use js::glue::{RUST_FUNCTION_VALUE_TO_JITINFO, RUST_JSID_IS_INT, RUST_JSID_IS_STRING}; -use js::glue::{RUST_JSID_TO_INT, RUST_JSID_TO_STRING, UnwrapObject}; +use js::jsapi::HandleId as RawHandleId; +use js::jsapi::HandleObject as RawHandleObject; +use js::jsapi::MutableHandleObject as RawMutableHandleObject; use js::jsapi::{CallArgs, DOMCallbacks, GetGlobalForObjectCrossCompartment}; use js::jsapi::{Heap, JSAutoCompartment, JSContext}; use js::jsapi::{JSJitInfo, JSObject, JSTracer, JSWrapObjectCallbacks}; use js::jsapi::{JS_EnumerateStandardClasses, JS_GetLatin1StringCharsAndLength}; use js::jsapi::{JS_IsExceptionPending, JS_IsGlobalObject}; use js::jsapi::{JS_ResolveStandardClass, JS_StringHasLatin1Chars, ObjectOpResult}; -use js::jsapi::HandleId as RawHandleId; -use js::jsapi::HandleObject as RawHandleObject; -use js::jsapi::MutableHandleObject as RawMutableHandleObject; use js::jsval::{JSVal, UndefinedValue}; -use js::rust::{GCMethods, ToString, ToWindowProxyIfWindow, get_object_class, is_dom_class}; -use js::rust::{Handle, HandleId, HandleObject, HandleValue, MutableHandleValue}; use js::rust::wrappers::JS_DeletePropertyById; use js::rust::wrappers::JS_ForwardGetPropertyTo; use js::rust::wrappers::JS_GetProperty; @@ -38,6 +35,9 @@ use js::rust::wrappers::JS_GetPrototype; use js::rust::wrappers::JS_HasProperty; use js::rust::wrappers::JS_HasPropertyById; use js::rust::wrappers::JS_SetProperty; +use js::rust::{get_object_class, is_dom_class, GCMethods, ToString, ToWindowProxyIfWindow}; +use js::rust::{Handle, HandleId, HandleObject, HandleValue, MutableHandleValue}; +use js::JS_CALLEE; use libc; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use std::ffi::CString; @@ -172,19 +172,20 @@ pub fn get_array_index_from_id(_cx: *mut JSContext, id: HandleId) -> Option None } // if id is length atom, -1, otherwise - /*return if JSID_IS_ATOM(id) { - let atom = JSID_TO_ATOM(id); - //let s = *GetAtomChars(id); - 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 } - } else { - IdToInt32(cx, id); - }*/} + // return if JSID_IS_ATOM(id) { + // let atom = JSID_TO_ATOM(id); + // //let s = *GetAtomChars(id); + // 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 } + // } else { + // IdToInt32(cx, id); + // } +} /// Find the enum equivelent of a string given by `v` in `pairs`. /// Returns `Err(())` on JSAPI failure (there is a pending exception), and diff --git a/components/script/dom/bindings/xmlname.rs b/components/script/dom/bindings/xmlname.rs index d547355e423..028b23bb987 100644 --- a/components/script/dom/bindings/xmlname.rs +++ b/components/script/dom/bindings/xmlname.rs @@ -6,7 +6,7 @@ use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::str::DOMString; -use html5ever::{Prefix, LocalName, Namespace}; +use html5ever::{LocalName, Namespace, Prefix}; /// Validate a qualified name. See https://dom.spec.whatwg.org/#validate for details. pub fn validate_qualified_name(qualified_name: &str) -> ErrorResult { diff --git a/components/script/dom/biquadfilternode.rs b/components/script/dom/biquadfilternode.rs index ca74d42f2c6..15f5f09e07a 100644 --- a/components/script/dom/biquadfilternode.rs +++ b/components/script/dom/biquadfilternode.rs @@ -5,18 +5,22 @@ use crate::dom::audionode::AudioNode; use crate::dom::audioparam::AudioParam; use crate::dom::baseaudiocontext::BaseAudioContext; -use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ChannelCountMode, ChannelInterpretation}; +use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ + ChannelCountMode, ChannelInterpretation, +}; use crate::dom::bindings::codegen::Bindings::AudioParamBinding::AutomationRate; -use crate::dom::bindings::codegen::Bindings::BiquadFilterNodeBinding::{self, BiquadFilterNodeMethods}; use crate::dom::bindings::codegen::Bindings::BiquadFilterNodeBinding::BiquadFilterOptions; use crate::dom::bindings::codegen::Bindings::BiquadFilterNodeBinding::BiquadFilterType; +use crate::dom::bindings::codegen::Bindings::BiquadFilterNodeBinding::{ + self, BiquadFilterNodeMethods, +}; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::window::Window; use dom_struct::dom_struct; -use servo_media::audio::biquad_filter_node::{BiquadFilterNodeOptions, FilterType}; use servo_media::audio::biquad_filter_node::BiquadFilterNodeMessage; +use servo_media::audio::biquad_filter_node::{BiquadFilterNodeOptions, FilterType}; use servo_media::audio::node::{AudioNodeInit, AudioNodeMessage}; use servo_media::audio::param::ParamType; use std::cell::Cell; @@ -39,9 +43,10 @@ impl BiquadFilterNode { context: &BaseAudioContext, options: &BiquadFilterOptions, ) -> Fallible { - 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 +62,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 +72,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 +82,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 +92,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 +113,11 @@ impl BiquadFilterNode { options: &BiquadFilterOptions, ) -> Fallible> { 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 +158,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 +171,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/blob.rs b/components/script/dom/blob.rs index 41a2971b55d..4842f6b29fa 100644 --- a/components/script/dom/blob.rs +++ b/components/script/dom/blob.rs @@ -7,14 +7,14 @@ use crate::dom::bindings::codegen::Bindings::BlobBinding; use crate::dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; use crate::dom::bindings::codegen::UnionTypes::ArrayBufferOrArrayBufferViewOrBlobOrString; use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; -use net_traits::{CoreResourceMsg, IpcSend}; -use net_traits::blob_url_store::{BlobBuf, get_blob_origin}; +use net_traits::blob_url_store::{get_blob_origin, BlobBuf}; use net_traits::filemanager_thread::{FileManagerThreadMsg, ReadFileProgress, RelativePos}; +use net_traits::{CoreResourceMsg, IpcSend}; use profile_traits::ipc; use std::mem; use std::ops::Index; 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/bluetoothadvertisingevent.rs b/components/script/dom/bluetoothadvertisingevent.rs index f32837ee89c..0ed93ce4ae8 100644 --- a/components/script/dom/bluetoothadvertisingevent.rs +++ b/components/script/dom/bluetoothadvertisingevent.rs @@ -2,8 +2,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::BluetoothAdvertisingEventBinding::{self, BluetoothAdvertisingEventInit}; use crate::dom::bindings::codegen::Bindings::BluetoothAdvertisingEventBinding::BluetoothAdvertisingEventMethods; +use crate::dom::bindings::codegen::Bindings::BluetoothAdvertisingEventBinding::{ + self, BluetoothAdvertisingEventInit, +}; use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; diff --git a/components/script/dom/bluetoothcharacteristicproperties.rs b/components/script/dom/bluetoothcharacteristicproperties.rs index 73b279c0904..05aee319613 100644 --- a/components/script/dom/bluetoothcharacteristicproperties.rs +++ b/components/script/dom/bluetoothcharacteristicproperties.rs @@ -3,9 +3,8 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding; -use crate::dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding:: -BluetoothCharacteristicPropertiesMethods; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding::BluetoothCharacteristicPropertiesMethods; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; diff --git a/components/script/dom/bluetoothdevice.rs b/components/script/dom/bluetoothdevice.rs index 9455f3bb460..0810dff6413 100644 --- a/components/script/dom/bluetoothdevice.rs +++ b/components/script/dom/bluetoothdevice.rs @@ -11,10 +11,10 @@ use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::B use crate::dom::bindings::error::Error; use crate::dom::bindings::error::ErrorResult; use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{DomObject, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; use crate::dom::bindings::str::DOMString; -use crate::dom::bluetooth::{AsyncBluetoothListener, Bluetooth, response_async}; +use crate::dom::bluetooth::{response_async, AsyncBluetoothListener, Bluetooth}; use crate::dom::bluetoothcharacteristicproperties::BluetoothCharacteristicProperties; use crate::dom::bluetoothremotegattcharacteristic::BluetoothRemoteGATTCharacteristic; use crate::dom::bluetoothremotegattdescriptor::BluetoothRemoteGATTDescriptor; @@ -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/bluetoothpermissionresult.rs b/components/script/dom/bluetoothpermissionresult.rs index 048f6e636b9..3aa9d9a19b8 100644 --- a/components/script/dom/bluetoothpermissionresult.rs +++ b/components/script/dom/bluetoothpermissionresult.rs @@ -4,16 +4,20 @@ use bluetooth_traits::{BluetoothRequest, BluetoothResponse}; use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::BluetoothPermissionResultBinding::{self, BluetoothPermissionResultMethods}; +use crate::dom::bindings::codegen::Bindings::BluetoothPermissionResultBinding::{ + self, BluetoothPermissionResultMethods, +}; use crate::dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorBinding::NavigatorMethods; -use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::{PermissionName, PermissionState}; use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionStatusBinding::PermissionStatusMethods; +use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::{ + PermissionName, PermissionState, +}; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use crate::dom::bindings::error::Error; -use crate::dom::bindings::reflector::{DomObject, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; -use crate::dom::bluetooth::{AsyncBluetoothListener, Bluetooth, AllowedBluetoothDevice}; +use crate::dom::bluetooth::{AllowedBluetoothDevice, AsyncBluetoothListener, Bluetooth}; use crate::dom::bluetoothdevice::BluetoothDevice; use crate::dom::globalscope::GlobalScope; use crate::dom::permissionstatus::PermissionStatus; diff --git a/components/script/dom/bluetoothremotegattcharacteristic.rs b/components/script/dom/bluetoothremotegattcharacteristic.rs index dbeddd1ab5b..41732f120f9 100644 --- a/components/script/dom/bluetoothremotegattcharacteristic.rs +++ b/components/script/dom/bluetoothremotegattcharacteristic.rs @@ -2,23 +2,23 @@ * 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/. */ +use bluetooth_traits::blocklist::{uuid_is_blocklisted, Blocklist}; use bluetooth_traits::{BluetoothRequest, BluetoothResponse, GATTType}; -use bluetooth_traits::blocklist::{Blocklist, uuid_is_blocklisted}; use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding:: -BluetoothCharacteristicPropertiesMethods; +use crate::dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding::BluetoothCharacteristicPropertiesMethods; use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTCharacteristicBinding; -use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTCharacteristicBinding:: -BluetoothRemoteGATTCharacteristicMethods; +use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTCharacteristicBinding::BluetoothRemoteGATTCharacteristicMethods; use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods; use crate::dom::bindings::codegen::UnionTypes::ArrayBufferViewOrArrayBuffer; -use crate::dom::bindings::error::Error::{self, InvalidModification, Network, NotSupported, Security}; +use crate::dom::bindings::error::Error::{ + self, InvalidModification, Network, NotSupported, Security, +}; use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{DomObject, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::{ByteString, DOMString}; -use crate::dom::bluetooth::{AsyncBluetoothListener, get_gatt_children, response_async}; +use crate::dom::bluetooth::{get_gatt_children, response_async, AsyncBluetoothListener}; use crate::dom::bluetoothcharacteristicproperties::BluetoothCharacteristicProperties; use crate::dom::bluetoothremotegattservice::BluetoothRemoteGATTService; use crate::dom::bluetoothuuid::{BluetoothDescriptorUUID, BluetoothUUID}; @@ -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..76a113c96e3 100644 --- a/components/script/dom/bluetoothremotegattdescriptor.rs +++ b/components/script/dom/bluetoothremotegattdescriptor.rs @@ -2,22 +2,23 @@ * 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/. */ +use bluetooth_traits::blocklist::{uuid_is_blocklisted, Blocklist}; use bluetooth_traits::{BluetoothRequest, BluetoothResponse}; -use bluetooth_traits::blocklist::{Blocklist, uuid_is_blocklisted}; use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTCharacteristicBinding:: -BluetoothRemoteGATTCharacteristicMethods; +use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTCharacteristicBinding::BluetoothRemoteGATTCharacteristicMethods; use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTDescriptorBinding; use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTDescriptorBinding::BluetoothRemoteGATTDescriptorMethods; use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods; use crate::dom::bindings::codegen::UnionTypes::ArrayBufferViewOrArrayBuffer; use crate::dom::bindings::error::Error::{self, InvalidModification, Network, Security}; -use crate::dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::{ByteString, DOMString}; -use crate::dom::bluetooth::{AsyncBluetoothListener, response_async}; -use crate::dom::bluetoothremotegattcharacteristic::{BluetoothRemoteGATTCharacteristic, MAXIMUM_ATTRIBUTE_LENGTH}; +use crate::dom::bluetooth::{response_async, AsyncBluetoothListener}; +use crate::dom::bluetoothremotegattcharacteristic::{ + BluetoothRemoteGATTCharacteristic, MAXIMUM_ATTRIBUTE_LENGTH, +}; use crate::dom::globalscope::GlobalScope; use crate::dom::promise::Promise; use dom_struct::dom_struct; @@ -166,7 +167,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..dff68c60eca 100644 --- a/components/script/dom/bluetoothremotegattserver.rs +++ b/components/script/dom/bluetoothremotegattserver.rs @@ -8,9 +8,9 @@ use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding; use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; use crate::dom::bindings::error::Error; use crate::dom::bindings::error::ErrorResult; -use crate::dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bluetooth::{AsyncBluetoothListener, get_gatt_children, response_async}; +use crate::dom::bluetooth::{get_gatt_children, response_async, AsyncBluetoothListener}; use crate::dom::bluetoothdevice::BluetoothDevice; use crate::dom::bluetoothuuid::{BluetoothServiceUUID, BluetoothUUID}; use crate::dom::globalscope::GlobalScope; @@ -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/bluetoothremotegattservice.rs b/components/script/dom/bluetoothremotegattservice.rs index c4f032dd356..1aeaf621691 100644 --- a/components/script/dom/bluetoothremotegattservice.rs +++ b/components/script/dom/bluetoothremotegattservice.rs @@ -10,7 +10,7 @@ use crate::dom::bindings::error::Error; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; -use crate::dom::bluetooth::{AsyncBluetoothListener, get_gatt_children}; +use crate::dom::bluetooth::{get_gatt_children, AsyncBluetoothListener}; use crate::dom::bluetoothdevice::BluetoothDevice; use crate::dom::bluetoothuuid::{BluetoothCharacteristicUUID, BluetoothServiceUUID, BluetoothUUID}; use crate::dom::eventtarget::EventTarget; diff --git a/components/script/dom/canvasgradient.rs b/components/script/dom/canvasgradient.rs index c3a8dfa7c4b..1ff600937eb 100644 --- a/components/script/dom/canvasgradient.rs +++ b/components/script/dom/canvasgradient.rs @@ -2,18 +2,20 @@ * 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/. */ -use canvas_traits::canvas::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle}; +use canvas_traits::canvas::{ + CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle, +}; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::CanvasGradientBinding; use crate::dom::bindings::codegen::Bindings::CanvasGradientBinding::CanvasGradientMethods; use crate::dom::bindings::error::{Error, ErrorResult}; use crate::dom::bindings::num::Finite; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::globalscope::GlobalScope; -use cssparser::{Parser, ParserInput, RGBA}; use cssparser::Color as CSSColor; +use cssparser::{Parser, ParserInput, RGBA}; use dom_struct::dom_struct; // https://html.spec.whatwg.org/multipage/#canvasgradient diff --git a/components/script/dom/canvaspattern.rs b/components/script/dom/canvaspattern.rs index fe8de52dc75..d5d18e4fa8b 100644 --- a/components/script/dom/canvaspattern.rs +++ b/components/script/dom/canvaspattern.rs @@ -4,7 +4,7 @@ use canvas_traits::canvas::{FillOrStrokeStyle, RepetitionStyle, SurfaceStyle}; use crate::dom::bindings::codegen::Bindings::CanvasPatternBinding; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::canvasgradient::ToFillOrStrokeStyle; use crate::dom::globalscope::GlobalScope; diff --git a/components/script/dom/canvasrenderingcontext2d.rs b/components/script/dom/canvasrenderingcontext2d.rs index 817250408d2..1bf2a09b50f 100644 --- a/components/script/dom/canvasrenderingcontext2d.rs +++ b/components/script/dom/canvasrenderingcontext2d.rs @@ -2,7 +2,7 @@ * 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/. */ -use canvas_traits::canvas::{Canvas2dMsg, CanvasMsg, CanvasId}; +use canvas_traits::canvas::{Canvas2dMsg, CanvasId, CanvasMsg}; use canvas_traits::canvas::{CompositionOrBlending, FillOrStrokeStyle, FillRule}; use canvas_traits::canvas::{LineCapStyle, LineJoinStyle, LinearGradientStyle}; use canvas_traits::canvas::{RadialGradientStyle, RepetitionStyle}; @@ -18,7 +18,7 @@ use crate::dom::bindings::codegen::UnionTypes::StringOrCanvasGradientOrCanvasPat use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::num::Finite; -use crate::dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom}; use crate::dom::bindings::str::DOMString; use crate::dom::canvasgradient::{CanvasGradient, CanvasGradientStyle, ToFillOrStrokeStyle}; @@ -27,12 +27,12 @@ use crate::dom::element::Element; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlcanvaselement::{CanvasContext, HTMLCanvasElement}; use crate::dom::imagedata::ImageData; -use crate::dom::node::{Node, NodeDamage, window_from_node}; +use crate::dom::node::{window_from_node, Node, NodeDamage}; use crate::unpremultiplytable::UNPREMULTIPLY_TABLE; -use cssparser::{Parser, ParserInput, RGBA}; use cssparser::Color as CSSColor; +use cssparser::{Parser, ParserInput, RGBA}; use dom_struct::dom_struct; -use euclid::{Transform2D, Point2D, Rect, Size2D, vec2}; +use euclid::{vec2, Point2D, Rect, Size2D, Transform2D}; use ipc_channel::ipc::{self, IpcSender}; use net_traits::image::base::PixelFormat; use net_traits::image_cache::CanRequestImages; @@ -45,10 +45,10 @@ use pixels; use profile_traits::ipc as profiled_ipc; use script_traits::ScriptMsg; use servo_url::ServoUrl; -use std::{fmt, mem}; use std::cell::Cell; use std::str::FromStr; use std::sync::Arc; +use std::{fmt, mem}; #[must_root] #[derive(Clone, JSTraceable, MallocSizeOf)] @@ -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, ) -> 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/channelmergernode.rs b/components/script/dom/channelmergernode.rs index 3602b5a7139..88fa3fceaee 100644 --- a/components/script/dom/channelmergernode.rs +++ b/components/script/dom/channelmergernode.rs @@ -4,8 +4,12 @@ use crate::dom::audionode::{AudioNode, MAX_CHANNEL_COUNT}; use crate::dom::baseaudiocontext::BaseAudioContext; -use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ChannelCountMode, ChannelInterpretation}; -use crate::dom::bindings::codegen::Bindings::ChannelMergerNodeBinding::{self, ChannelMergerOptions}; +use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ + ChannelCountMode, ChannelInterpretation, +}; +use crate::dom::bindings::codegen::Bindings::ChannelMergerNodeBinding::{ + self, ChannelMergerOptions, +}; use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; diff --git a/components/script/dom/client.rs b/components/script/dom/client.rs index ec20e59258c..042976e60ac 100644 --- a/components/script/dom/client.rs +++ b/components/script/dom/client.rs @@ -2,9 +2,9 @@ * 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/. */ -use crate::dom::bindings::codegen::Bindings::ClientBinding::{ClientMethods, Wrap}; use crate::dom::bindings::codegen::Bindings::ClientBinding::FrameType; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::codegen::Bindings::ClientBinding::{ClientMethods, Wrap}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{DomRoot, MutNullableDom}; use crate::dom::bindings::str::{DOMString, USVString}; use crate::dom::serviceworker::ServiceWorker; diff --git a/components/script/dom/compositionevent.rs b/components/script/dom/compositionevent.rs index 7763ec41600..1ba8a1bf40a 100644 --- a/components/script/dom/compositionevent.rs +++ b/components/script/dom/compositionevent.rs @@ -2,7 +2,9 @@ * 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/. */ -use crate::dom::bindings::codegen::Bindings::CompositionEventBinding::{self, CompositionEventMethods}; +use crate::dom::bindings::codegen::Bindings::CompositionEventBinding::{ + self, CompositionEventMethods, +}; use crate::dom::bindings::codegen::Bindings::UIEventBinding::UIEventBinding::UIEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::reflect_dom_object; diff --git a/components/script/dom/crypto.rs b/components/script/dom/crypto.rs index a9a8efe2b4a..a1c3f590e3c 100644 --- a/components/script/dom/crypto.rs +++ b/components/script/dom/crypto.rs @@ -6,15 +6,15 @@ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::CryptoBinding; use crate::dom::bindings::codegen::Bindings::CryptoBinding::CryptoMethods; use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; -use js::jsapi::{JSContext, JSObject}; use js::jsapi::Type; +use js::jsapi::{JSContext, JSObject}; use js::rust::CustomAutoRooterGuard; use js::typedarray::ArrayBufferView; -use servo_rand::{ServoRng, Rng}; +use servo_rand::{Rng, ServoRng}; use std::ptr::NonNull; unsafe_no_jsmanaged_fields!(ServoRng); diff --git a/components/script/dom/css.rs b/components/script/dom/css.rs index a4539c17f76..10f0bf9ae6d 100644 --- a/components/script/dom/css.rs +++ b/components/script/dom/css.rs @@ -9,12 +9,12 @@ use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::window::Window; use crate::dom::worklet::Worklet; -use cssparser::{Parser, ParserInput, serialize_identifier}; +use cssparser::{serialize_identifier, Parser, ParserInput}; use dom_struct::dom_struct; use style::context::QuirksMode; use style::parser::ParserContext; +use style::stylesheets::supports_rule::{parse_condition_or_declaration, Declaration}; use style::stylesheets::CssRuleType; -use style::stylesheets::supports_rule::{Declaration, parse_condition_or_declaration}; use style_traits::ParsingMode; #[dom_struct] diff --git a/components/script/dom/cssconditionrule.rs b/components/script/dom/cssconditionrule.rs index 6b839b6ef4a..812a23cf2fc 100644 --- a/components/script/dom/cssconditionrule.rs +++ b/components/script/dom/cssconditionrule.rs @@ -11,7 +11,7 @@ use crate::dom::cssstylesheet::CSSStyleSheet; use crate::dom::csssupportsrule::CSSSupportsRule; use dom_struct::dom_struct; use servo_arc::Arc; -use style::shared_lock::{SharedRwLock, Locked}; +use style::shared_lock::{Locked, SharedRwLock}; use style::stylesheets::CssRules as StyleCssRules; #[dom_struct] diff --git a/components/script/dom/cssgroupingrule.rs b/components/script/dom/cssgroupingrule.rs index c7295f46b85..f0010aa0e64 100644 --- a/components/script/dom/cssgroupingrule.rs +++ b/components/script/dom/cssgroupingrule.rs @@ -13,7 +13,7 @@ use crate::dom::cssrulelist::{CSSRuleList, RulesSource}; use crate::dom::cssstylesheet::CSSStyleSheet; use dom_struct::dom_struct; use servo_arc::Arc; -use style::shared_lock::{SharedRwLock, Locked}; +use style::shared_lock::{Locked, SharedRwLock}; use style::stylesheets::CssRules as StyleCssRules; #[dom_struct] diff --git a/components/script/dom/csskeyframerule.rs b/components/script/dom/csskeyframerule.rs index 948e5938fe3..4f253ea2572 100644 --- a/components/script/dom/csskeyframerule.rs +++ b/components/script/dom/csskeyframerule.rs @@ -2,9 +2,11 @@ * 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/. */ -use crate::dom::bindings::codegen::Bindings::CSSKeyframeRuleBinding::{self, CSSKeyframeRuleMethods}; +use crate::dom::bindings::codegen::Bindings::CSSKeyframeRuleBinding::{ + self, CSSKeyframeRuleMethods, +}; use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{DomObject, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; use crate::dom::bindings::str::DOMString; use crate::dom::cssrule::{CSSRule, SpecificCSSRule}; diff --git a/components/script/dom/csskeyframesrule.rs b/components/script/dom/csskeyframesrule.rs index 27280cc651e..54b1780e069 100644 --- a/components/script/dom/csskeyframesrule.rs +++ b/components/script/dom/csskeyframesrule.rs @@ -6,7 +6,7 @@ use crate::dom::bindings::codegen::Bindings::CSSKeyframesRuleBinding; use crate::dom::bindings::codegen::Bindings::CSSKeyframesRuleBinding::CSSKeyframesRuleMethods; use crate::dom::bindings::error::ErrorResult; use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{DomObject, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::{DomRoot, MutNullableDom}; use crate::dom::bindings::str::DOMString; use crate::dom::csskeyframerule::CSSKeyframeRule; @@ -18,7 +18,7 @@ use cssparser::{Parser, ParserInput}; use dom_struct::dom_struct; use servo_arc::Arc; use style::shared_lock::{Locked, ToCssWithGuard}; -use style::stylesheets::keyframes_rule::{KeyframesRule, Keyframe, KeyframeSelector}; +use style::stylesheets::keyframes_rule::{Keyframe, KeyframeSelector, KeyframesRule}; use style::values::KeyframesName; #[dom_struct] diff --git a/components/script/dom/cssmediarule.rs b/components/script/dom/cssmediarule.rs index fc7608a476f..3704168dd7b 100644 --- a/components/script/dom/cssmediarule.rs +++ b/components/script/dom/cssmediarule.rs @@ -5,7 +5,7 @@ use crate::dom::bindings::codegen::Bindings::CSSMediaRuleBinding; use crate::dom::bindings::codegen::Bindings::CSSMediaRuleBinding::CSSMediaRuleMethods; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; -use crate::dom::bindings::reflector::{DomObject, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::{DomRoot, MutNullableDom}; use crate::dom::bindings::str::DOMString; use crate::dom::cssconditionrule::CSSConditionRule; diff --git a/components/script/dom/cssrulelist.rs b/components/script/dom/cssrulelist.rs index c5889eb066c..870a85866e8 100644 --- a/components/script/dom/cssrulelist.rs +++ b/components/script/dom/cssrulelist.rs @@ -6,7 +6,7 @@ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::CSSRuleListBinding; use crate::dom::bindings::codegen::Bindings::CSSRuleListBinding::CSSRuleListMethods; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; use crate::dom::csskeyframerule::CSSKeyframeRule; use crate::dom::cssrule::CSSRule; diff --git a/components/script/dom/cssstyledeclaration.rs b/components/script/dom/cssstyledeclaration.rs index 455bcbdd08f..bc3fbe0f655 100644 --- a/components/script/dom/cssstyledeclaration.rs +++ b/components/script/dom/cssstyledeclaration.rs @@ -2,23 +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/. */ -use crate::dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::{self, CSSStyleDeclarationMethods}; +use crate::dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::{ + self, CSSStyleDeclarationMethods, +}; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::cssrule::CSSRule; use crate::dom::element::Element; -use crate::dom::node::{Node, window_from_node, document_from_node}; +use crate::dom::node::{document_from_node, window_from_node, Node}; use crate::dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use servo_url::ServoUrl; use style::attr::AttrValue; -use style::properties::{Importance, PropertyDeclarationBlock, PropertyId, LonghandId, ShorthandId}; -use style::properties::{parse_one_declaration_into, parse_style_attribute, SourcePropertyDeclaration}; +use style::properties::{ + parse_one_declaration_into, parse_style_attribute, SourcePropertyDeclaration, +}; +use style::properties::{ + Importance, LonghandId, PropertyDeclarationBlock, PropertyId, ShorthandId, +}; use style::selector_parser::PseudoElement; use style::shared_lock::Locked; use style_traits::ParsingMode; @@ -157,7 +163,8 @@ impl CSSStyleOwner { .style_stylesheet() .contents .url_data - .read()).clone(), + .read()) + .clone(), } } } diff --git a/components/script/dom/cssstylerule.rs b/components/script/dom/cssstylerule.rs index 662ea8bb542..0e9758f25fb 100644 --- a/components/script/dom/cssstylerule.rs +++ b/components/script/dom/cssstylerule.rs @@ -5,22 +5,22 @@ use crate::dom::bindings::codegen::Bindings::CSSStyleRuleBinding::{self, CSSStyleRuleMethods}; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{DomObject, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; use crate::dom::bindings::str::DOMString; use crate::dom::cssrule::{CSSRule, SpecificCSSRule}; use crate::dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner}; use crate::dom::cssstylesheet::CSSStyleSheet; use crate::dom::window::Window; -use cssparser::{Parser as CssParser, ParserInput as CssParserInput}; use cssparser::ToCss; +use cssparser::{Parser as CssParser, ParserInput as CssParserInput}; use dom_struct::dom_struct; use selectors::parser::SelectorList; use servo_arc::Arc; use std::mem; use style::selector_parser::SelectorParser; use style::shared_lock::{Locked, ToCssWithGuard}; -use style::stylesheets::{StyleRule, Origin}; +use style::stylesheets::{Origin, StyleRule}; #[dom_struct] pub struct CSSStyleRule { diff --git a/components/script/dom/cssstylevalue.rs b/components/script/dom/cssstylevalue.rs index 668c8bbec98..bb19d351543 100644 --- a/components/script/dom/cssstylevalue.rs +++ b/components/script/dom/cssstylevalue.rs @@ -4,8 +4,8 @@ use crate::dom::bindings::codegen::Bindings::CSSStyleValueBinding::CSSStyleValueMethods; use crate::dom::bindings::codegen::Bindings::CSSStyleValueBinding::Wrap; -use crate::dom::bindings::reflector::Reflector; use crate::dom::bindings::reflector::reflect_dom_object; +use crate::dom::bindings::reflector::Reflector; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::globalscope::GlobalScope; diff --git a/components/script/dom/csssupportsrule.rs b/components/script/dom/csssupportsrule.rs index 17005ce0aec..b1a1e6b5be4 100644 --- a/components/script/dom/csssupportsrule.rs +++ b/components/script/dom/csssupportsrule.rs @@ -4,7 +4,7 @@ use crate::dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; -use crate::dom::bindings::reflector::{DomObject, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::cssconditionrule::CSSConditionRule; @@ -16,8 +16,8 @@ use dom_struct::dom_struct; use servo_arc::Arc; use style::parser::ParserContext; use style::shared_lock::{Locked, ToCssWithGuard}; -use style::stylesheets::{CssRuleType, SupportsRule}; use style::stylesheets::supports_rule::SupportsCondition; +use style::stylesheets::{CssRuleType, SupportsRule}; use style_traits::{ParsingMode, ToCss}; #[dom_struct] @@ -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..8de16faf1d6 100644 --- a/components/script/dom/customelementregistry.rs +++ b/components/script/dom/customelementregistry.rs @@ -11,10 +11,14 @@ use crate::dom::bindings::codegen::Bindings::CustomElementRegistryBinding::Eleme use crate::dom::bindings::codegen::Bindings::ElementBinding::ElementMethods; use crate::dom::bindings::codegen::Bindings::FunctionBinding::Function; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; -use crate::dom::bindings::conversions::{ConversionResult, FromJSValConvertible, StringificationBehavior}; -use crate::dom::bindings::error::{Error, ErrorResult, Fallible, report_pending_exception, throw_dom_exception}; +use crate::dom::bindings::conversions::{ + ConversionResult, FromJSValConvertible, StringificationBehavior, +}; +use crate::dom::bindings::error::{ + report_pending_exception, throw_dom_exception, Error, ErrorResult, Fallible, +}; use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; @@ -22,7 +26,7 @@ use crate::dom::domexception::{DOMErrorName, DOMException}; use crate::dom::element::{CustomElementState, Element}; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{document_from_node, Node, window_from_node}; +use crate::dom::node::{document_from_node, window_from_node, Node}; use crate::dom::promise::Promise; use crate::dom::window::Window; use crate::microtask::Microtask; @@ -31,11 +35,11 @@ use dom_struct::dom_struct; use html5ever::{LocalName, Namespace, Prefix}; use js::conversions::ToJSValConvertible; use js::glue::UnwrapObject; -use js::jsapi::{Heap, IsCallable, IsConstructor, HandleValueArray}; +use js::jsapi::{HandleValueArray, Heap, IsCallable, IsConstructor}; use js::jsapi::{JSAutoCompartment, JSContext, JSObject}; use js::jsval::{JSVal, NullValue, ObjectValue, UndefinedValue}; +use js::rust::wrappers::{Construct1, JS_GetProperty, JS_SameValue}; use js::rust::{HandleObject, HandleValue, MutableHandleValue}; -use js::rust::wrappers::{JS_GetProperty, Construct1, JS_SameValue}; use std::cell::Cell; use std::collections::{HashMap, VecDeque}; use std::mem; @@ -97,7 +101,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..afe0908c543 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -4,8 +4,8 @@ use crate::devtools; use crate::dom::abstractworker::{SimpleWorkerErrorHandler, WorkerScriptMsg}; +use crate::dom::abstractworkerglobalscope::{run_worker_event_loop, WorkerEventLoopMethods}; use crate::dom::abstractworkerglobalscope::{SendableWorkerScriptChan, WorkerThreadWorkerChan}; -use crate::dom::abstractworkerglobalscope::{WorkerEventLoopMethods, run_worker_event_loop}; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding; use crate::dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding::DedicatedWorkerGlobalScopeMethods; @@ -22,28 +22,28 @@ use crate::dom::globalscope::GlobalScope; use crate::dom::messageevent::MessageEvent; use crate::dom::worker::{TrustedWorkerAddress, Worker}; use crate::dom::workerglobalscope::WorkerGlobalScope; -use crate::script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort, new_rt_and_cx, Runtime}; use crate::script_runtime::ScriptThreadEventCategory::WorkerEvent; +use crate::script_runtime::{new_rt_and_cx, CommonScriptMsg, Runtime, ScriptChan, ScriptPort}; use crate::task_queue::{QueuedTask, QueuedTaskConversion, TaskQueue}; use crate::task_source::TaskSourceName; use devtools_traits::DevtoolScriptControlMsg; use dom_struct::dom_struct; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use ipc_channel::router::ROUTER; -use js::jsapi::{JSAutoCompartment, JSContext}; use js::jsapi::JS_AddInterruptCallback; +use js::jsapi::{JSAutoCompartment, JSContext}; use js::jsval::UndefinedValue; use js::rust::HandleValue; use msg::constellation_msg::TopLevelBrowsingContextId; -use net_traits::{IpcSend, load_whole_resource}; use net_traits::request::{CredentialsMode, Destination, RequestInit}; +use net_traits::{load_whole_resource, IpcSend}; use script_traits::{TimerEvent, TimerSource, WorkerGlobalScopeInit, WorkerScriptLoadOrigin}; -use servo_channel::{channel, route_ipc_receiver_to_new_servo_sender, Sender, Receiver}; +use servo_channel::{channel, route_ipc_receiver_to_new_servo_sender, Receiver, Sender}; use servo_rand::random; use servo_url::ServoUrl; use std::mem::replace; -use std::sync::Arc; use std::sync::atomic::AtomicBool; +use std::sync::Arc; use std::thread; use style::thread_state::{self, ThreadState}; @@ -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 { @@ -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/dissimilaroriginlocation.rs b/components/script/dom/dissimilaroriginlocation.rs index feea9d93b21..e2111008eb3 100644 --- a/components/script/dom/dissimilaroriginlocation.rs +++ b/components/script/dom/dissimilaroriginlocation.rs @@ -5,8 +5,8 @@ use crate::dom::bindings::codegen::Bindings::DissimilarOriginLocationBinding; use crate::dom::bindings::codegen::Bindings::DissimilarOriginLocationBinding::DissimilarOriginLocationMethods; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::reflector::Reflector; use crate::dom::bindings::reflector::reflect_dom_object; +use crate::dom::bindings::reflector::Reflector; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::bindings::str::USVString; diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index 9ce096e2e65..a8df59ca21c 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -4,32 +4,38 @@ use crate::cookie_rs; use crate::document_loader::{DocumentLoader, LoadType}; -use crate::dom::activation::{ActivationSource, synthetic_click_activation}; +use crate::dom::activation::{synthetic_click_activation, ActivationSource}; use crate::dom::attr::Attr; use crate::dom::beforeunloadevent::BeforeUnloadEvent; use crate::dom::bindings::callback::ExceptionHandling; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEventBinding::BeforeUnloadEventMethods; use crate::dom::bindings::codegen::Bindings::DocumentBinding; -use crate::dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, DocumentReadyState}; use crate::dom::bindings::codegen::Bindings::DocumentBinding::ElementCreationOptions; +use crate::dom::bindings::codegen::Bindings::DocumentBinding::{ + DocumentMethods, DocumentReadyState, +}; use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElementBinding::HTMLIFrameElementMethods; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use crate::dom::bindings::codegen::Bindings::NodeFilterBinding::NodeFilter; use crate::dom::bindings::codegen::Bindings::PerformanceBinding::PerformanceMethods; use crate::dom::bindings::codegen::Bindings::TouchBinding::TouchMethods; -use crate::dom::bindings::codegen::Bindings::WindowBinding::{FrameRequestCallback, ScrollBehavior, WindowMethods}; +use crate::dom::bindings::codegen::Bindings::WindowBinding::{ + FrameRequestCallback, ScrollBehavior, WindowMethods, +}; use crate::dom::bindings::codegen::UnionTypes::NodeOrString; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId}; use crate::dom::bindings::num::Finite; use crate::dom::bindings::refcounted::{Trusted, TrustedPromise}; -use crate::dom::bindings::reflector::{DomObject, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom, RootedReference}; use crate::dom::bindings::str::{DOMString, USVString}; -use crate::dom::bindings::xmlname::{namespace_from_domstring, validate_and_extract, xml_name_type}; use crate::dom::bindings::xmlname::XMLName::InvalidXMLName; +use crate::dom::bindings::xmlname::{ + namespace_from_domstring, validate_and_extract, xml_name_type, +}; use crate::dom::closeevent::CloseEvent; use crate::dom::comment::Comment; use crate::dom::cssstylesheet::CSSStyleSheet; @@ -38,8 +44,10 @@ use crate::dom::customevent::CustomEvent; use crate::dom::documentfragment::DocumentFragment; use crate::dom::documenttype::DocumentType; use crate::dom::domimplementation::DOMImplementation; -use crate::dom::element::{Element, ElementCreator, ElementPerformFullscreenEnter, ElementPerformFullscreenExit}; use crate::dom::element::CustomElementCreationMode; +use crate::dom::element::{ + Element, ElementCreator, ElementPerformFullscreenEnter, ElementPerformFullscreenExit, +}; use crate::dom::errorevent::ErrorEvent; use crate::dom::event::{Event, EventBubbles, EventCancelable, EventDefault, EventStatus}; use crate::dom::eventtarget::EventTarget; @@ -65,9 +73,9 @@ use crate::dom::keyboardevent::KeyboardEvent; use crate::dom::location::Location; use crate::dom::messageevent::MessageEvent; use crate::dom::mouseevent::MouseEvent; -use crate::dom::node::{self, CloneChildrenFlag, document_from_node, window_from_node}; -use crate::dom::node::{Node, NodeDamage, NodeFlags, LayoutNodeHelpers}; use crate::dom::node::VecPreOrderInsertionHelper; +use crate::dom::node::{self, document_from_node, window_from_node, CloneChildrenFlag}; +use crate::dom::node::{LayoutNodeHelpers, Node, NodeDamage, NodeFlags}; use crate::dom::nodeiterator::NodeIterator; use crate::dom::nodelist::NodeList; use crate::dom::pagetransitionevent::PageTransitionEvent; @@ -102,18 +110,21 @@ use euclid::Point2D; use html5ever::{LocalName, Namespace, QualName}; use hyper_serde::Serde; use ipc_channel::ipc::{self, IpcSender}; -use js::jsapi::{JSContext, JSObject, JSRuntime}; use js::jsapi::JS_GetRuntime; +use js::jsapi::{JSContext, JSObject, JSRuntime}; use keyboard_types::{Key, KeyState, Modifiers}; -use metrics::{InteractiveFlag, InteractiveMetrics, InteractiveWindow, ProfilerMetadataFactory, ProgressiveWebMetric}; +use metrics::{ + InteractiveFlag, InteractiveMetrics, InteractiveWindow, ProfilerMetadataFactory, + ProgressiveWebMetric, +}; use mime::{self, Mime}; use msg::constellation_msg::BrowsingContextId; -use net_traits::{FetchResponseMsg, IpcSend, ReferrerPolicy}; -use net_traits::CookieSource::NonHTTP; -use net_traits::CoreResourceMsg::{GetCookiesForUrl, SetCookiesForUrl}; use net_traits::pub_domains::is_pub_domain; use net_traits::request::RequestInit; use net_traits::response::HttpsState; +use net_traits::CookieSource::NonHTTP; +use net_traits::CoreResourceMsg::{GetCookiesForUrl, SetCookiesForUrl}; +use net_traits::{FetchResponseMsg, IpcSend, ReferrerPolicy}; use num_traits::ToPrimitive; use profile_traits::ipc as profile_ipc; use profile_traits::time::{TimerMetadata, TimerMetadataFrameType, TimerMetadataReflowType}; @@ -127,8 +138,8 @@ use servo_config::prefs::PREFS; use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl}; use std::borrow::ToOwned; use std::cell::{Cell, Ref, RefMut}; -use std::collections::{HashMap, HashSet, VecDeque}; use std::collections::hash_map::Entry::{Occupied, Vacant}; +use std::collections::{HashMap, HashSet, VecDeque}; use std::default::Default; use std::fmt; use std::mem; @@ -143,10 +154,10 @@ use style::selector_parser::{RestyleDamage, Snapshot}; use style::shared_lock::{SharedRwLock as StyleSharedRwLock, SharedRwLockReadGuard}; use style::str::{split_html_space_chars, str_join}; use style::stylesheet_set::DocumentStylesheetSet; -use style::stylesheets::{CssRule, Stylesheet, Origin, OriginSet}; +use style::stylesheets::{CssRule, Origin, OriginSet, Stylesheet}; use time; -use url::Host; use url::percent_encoding::percent_decode; +use url::Host; /// The number of times we are allowed to see spurious `requestAnimationFrame()` calls before /// falling back to fake ones. @@ -539,7 +550,8 @@ impl Document { ); }), self.window.upcast(), - ).unwrap(); + ) + .unwrap(); } } else { self.window().suspend(); @@ -1904,7 +1916,8 @@ impl Document { } }), self.window.upcast(), - ).unwrap(); + ) + .unwrap(); // Step 8. let document = Trusted::new(self); @@ -1938,7 +1951,8 @@ impl Document { ); }), self.window.upcast(), - ).unwrap(); + ) + .unwrap(); } // Step 9. @@ -2780,14 +2794,16 @@ impl Document { owner .upcast::() .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 +3637,8 @@ impl DocumentMethods for Document { .child_elements() .find(|node| { node.namespace() == &ns!(svg) && node.local_name() == &local_name!("title") - }).map(DomRoot::upcast::) + }) + .map(DomRoot::upcast::) } else { // Step 2. root.upcast::() @@ -3726,7 +3743,8 @@ impl DocumentMethods for Document { HTMLElementTypeId::HTMLFrameSetElement, )) => true, _ => false, - }).map(|node| DomRoot::downcast(node).unwrap()) + }) + .map(|node| DomRoot::downcast(node).unwrap()) }) } @@ -3947,16 +3965,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::() - .resource_threads() - .send(SetCookiesForUrl(self.url(), cookies, NonHTTP)); + let _ = self + .window + .upcast::() + .resource_threads() + .send(SetCookiesForUrl(self.url(), cookies, NonHTTP)); Ok(()) } @@ -4158,7 +4178,8 @@ impl DocumentMethods for Document { node::from_untrusted_node_address(js_runtime, untrusted_node_address) }; DomRoot::downcast::(node) - }).collect(); + }) + .collect(); // Step 4 if let Some(root_element) = self.GetDocumentElement() { @@ -4172,7 +4193,11 @@ impl DocumentMethods for Document { } // https://html.spec.whatwg.org/multipage/#dom-document-open - fn Open(&self, _unused1: Option, _unused2: Option) -> Fallible> { + fn Open( + &self, + _unused1: Option, + _unused2: Option, + ) -> Fallible> { // Step 1 if !self.is_html_document() { return Err(Error::InvalidState); @@ -4266,12 +4291,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> { + fn Open_( + &self, + url: DOMString, + target: DOMString, + features: DOMString, + ) -> Fallible> { // 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 +4329,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/documentfragment.rs b/components/script/dom/documentfragment.rs index 43b7a8d4c5a..b347380e972 100644 --- a/components/script/dom/documentfragment.rs +++ b/components/script/dom/documentfragment.rs @@ -13,7 +13,7 @@ use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::Element; use crate::dom::htmlcollection::HTMLCollection; -use crate::dom::node::{Node, window_from_node}; +use crate::dom::node::{window_from_node, Node}; use crate::dom::nodelist::NodeList; use crate::dom::window::Window; use dom_struct::dom_struct; diff --git a/components/script/dom/domexception.rs b/components/script/dom/domexception.rs index 623a5b3adf2..e61f76caf96 100644 --- a/components/script/dom/domexception.rs +++ b/components/script/dom/domexception.rs @@ -5,7 +5,7 @@ use crate::dom::bindings::codegen::Bindings::DOMExceptionBinding; use crate::dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionConstants; use crate::dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::globalscope::GlobalScope; diff --git a/components/script/dom/domimplementation.rs b/components/script/dom/domimplementation.rs index 6ebc5b6fe08..29a3e595793 100644 --- a/components/script/dom/domimplementation.rs +++ b/components/script/dom/domimplementation.rs @@ -5,16 +5,18 @@ use crate::document_loader::DocumentLoader; use crate::dom::bindings::codegen::Bindings::DOMImplementationBinding; use crate::dom::bindings::codegen::Bindings::DOMImplementationBinding::DOMImplementationMethods; -use crate::dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, ElementCreationOptions}; +use crate::dom::bindings::codegen::Bindings::DocumentBinding::{ + DocumentMethods, ElementCreationOptions, +}; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::bindings::xmlname::{namespace_from_domstring, validate_qualified_name}; -use crate::dom::document::{Document, HasBrowsingContext, IsHTMLDocument}; use crate::dom::document::DocumentSource; +use crate::dom::document::{Document, HasBrowsingContext, IsHTMLDocument}; use crate::dom::documenttype::DocumentType; use crate::dom::htmlbodyelement::HTMLBodyElement; use crate::dom::htmlheadelement::HTMLHeadElement; diff --git a/components/script/dom/dommatrix.rs b/components/script/dom/dommatrix.rs index 2baf094e869..4e4cf650f9e 100644 --- a/components/script/dom/dommatrix.rs +++ b/components/script/dom/dommatrix.rs @@ -2,13 +2,17 @@ * 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/. */ -use crate::dom::bindings::codegen::Bindings::DOMMatrixBinding::{Wrap, DOMMatrixMethods, DOMMatrixInit}; +use crate::dom::bindings::codegen::Bindings::DOMMatrixBinding::{ + DOMMatrixInit, DOMMatrixMethods, Wrap, +}; use crate::dom::bindings::codegen::Bindings::DOMMatrixReadOnlyBinding::DOMMatrixReadOnlyMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; -use crate::dom::dommatrixreadonly::{dommatrixinit_to_matrix, DOMMatrixReadOnly, entries_to_matrix}; +use crate::dom::dommatrixreadonly::{ + dommatrixinit_to_matrix, entries_to_matrix, DOMMatrixReadOnly, +}; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; use euclid::Transform3D; @@ -295,7 +299,8 @@ impl DOMMatrixMethods for DOMMatrix { // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-multiplyself fn MultiplySelf(&self, other: &DOMMatrixInit) -> Fallible> { // Steps 1-3. - self.upcast::().multiply_self(other) + self.upcast::() + .multiply_self(other) // Step 4. .and(Ok(DomRoot::from_ref(&self))) } @@ -303,7 +308,8 @@ impl DOMMatrixMethods for DOMMatrix { // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-premultiplyself fn PreMultiplySelf(&self, other: &DOMMatrixInit) -> Fallible> { // Steps 1-3. - self.upcast::().pre_multiply_self(other) + self.upcast::() + .pre_multiply_self(other) // Step 4. .and(Ok(DomRoot::from_ref(&self))) } diff --git a/components/script/dom/dommatrixreadonly.rs b/components/script/dom/dommatrixreadonly.rs index 65278b1f7d1..8edd6222480 100644 --- a/components/script/dom/dommatrixreadonly.rs +++ b/components/script/dom/dommatrixreadonly.rs @@ -4,7 +4,9 @@ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::DOMMatrixBinding::{DOMMatrixInit, DOMMatrixMethods}; -use crate::dom::bindings::codegen::Bindings::DOMMatrixReadOnlyBinding::{DOMMatrixReadOnlyMethods, Wrap}; +use crate::dom::bindings::codegen::Bindings::DOMMatrixReadOnlyBinding::{ + DOMMatrixReadOnlyMethods, Wrap, +}; use crate::dom::bindings::codegen::Bindings::DOMPointBinding::DOMPointInit; use crate::dom::bindings::error; use crate::dom::bindings::error::Fallible; @@ -14,11 +16,11 @@ use crate::dom::dommatrix::DOMMatrix; use crate::dom::dompoint::DOMPoint; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; -use euclid::{Transform3D, Angle}; -use js::jsapi::{JSObject, JSContext}; +use euclid::{Angle, Transform3D}; +use js::jsapi::{JSContext, JSObject}; use js::rust::CustomAutoRooterGuard; -use js::typedarray::{Float32Array, Float64Array}; use js::typedarray::CreateWith; +use js::typedarray::{Float32Array, Float64Array}; use std::cell::{Cell, Ref}; use std::f64; use std::ptr; diff --git a/components/script/dom/domparser.rs b/components/script/dom/domparser.rs index 334137499e7..8ded7107698 100644 --- a/components/script/dom/domparser.rs +++ b/components/script/dom/domparser.rs @@ -12,11 +12,11 @@ use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Te use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; -use crate::dom::document::{Document, HasBrowsingContext, IsHTMLDocument}; use crate::dom::document::DocumentSource; +use crate::dom::document::{Document, HasBrowsingContext, IsHTMLDocument}; use crate::dom::servoparser::ServoParser; use crate::dom::window::Window; use dom_struct::dom_struct; diff --git a/components/script/dom/dompoint.rs b/components/script/dom/dompoint.rs index 456153b6504..c0d89f8420d 100644 --- a/components/script/dom/dompoint.rs +++ b/components/script/dom/dompoint.rs @@ -2,7 +2,9 @@ * 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/. */ -use crate::dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap}; +use crate::dom::bindings::codegen::Bindings::DOMPointBinding::{ + DOMPointInit, DOMPointMethods, Wrap, +}; use crate::dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::DOMPointReadOnlyMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::reflect_dom_object; diff --git a/components/script/dom/dompointreadonly.rs b/components/script/dom/dompointreadonly.rs index ea6414aa186..ecda5c4e0b4 100644 --- a/components/script/dom/dompointreadonly.rs +++ b/components/script/dom/dompointreadonly.rs @@ -2,9 +2,11 @@ * 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/. */ -use crate::dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::{DOMPointReadOnlyMethods, Wrap}; +use crate::dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::{ + DOMPointReadOnlyMethods, Wrap, +}; use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; diff --git a/components/script/dom/domquad.rs b/components/script/dom/domquad.rs index 3d0cb09b733..f65088dde8d 100644 --- a/components/script/dom/domquad.rs +++ b/components/script/dom/domquad.rs @@ -6,7 +6,7 @@ use crate::dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOM use crate::dom::bindings::codegen::Bindings::DOMQuadBinding::{DOMQuadInit, DOMQuadMethods, Wrap}; use crate::dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::DOMRectInit; use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::dompoint::DOMPoint; use crate::dom::domrect::DOMRect; diff --git a/components/script/dom/domrectreadonly.rs b/components/script/dom/domrectreadonly.rs index e1bb8252b8d..96170f6a489 100644 --- a/components/script/dom/domrectreadonly.rs +++ b/components/script/dom/domrectreadonly.rs @@ -2,9 +2,11 @@ * 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/. */ -use crate::dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::{DOMRectReadOnlyMethods, Wrap}; +use crate::dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::{ + DOMRectReadOnlyMethods, Wrap, +}; use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; diff --git a/components/script/dom/domstringmap.rs b/components/script/dom/domstringmap.rs index d62b4fd49f9..10da1af9299 100644 --- a/components/script/dom/domstringmap.rs +++ b/components/script/dom/domstringmap.rs @@ -5,7 +5,7 @@ use crate::dom::bindings::codegen::Bindings::DOMStringMapBinding; use crate::dom::bindings::codegen::Bindings::DOMStringMapBinding::DOMStringMapMethods; use crate::dom::bindings::error::ErrorResult; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::htmlelement::HTMLElement; diff --git a/components/script/dom/domtokenlist.rs b/components/script/dom/domtokenlist.rs index 4c74b69d3a8..902197795ff 100644 --- a/components/script/dom/domtokenlist.rs +++ b/components/script/dom/domtokenlist.rs @@ -6,7 +6,7 @@ use crate::dom::attr::Attr; use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding; use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::element::Element; diff --git a/components/script/dom/element.rs b/components/script/dom/element.rs index 2600f0cc575..8f65f49b7df 100644 --- a/components/script/dom/element.rs +++ b/components/script/dom/element.rs @@ -15,8 +15,8 @@ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindings::FunctionBinding::Function; use crate::dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTemplateElementMethods; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; -use crate::dom::bindings::codegen::Bindings::WindowBinding::{ScrollBehavior, ScrollToOptions}; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; +use crate::dom::bindings::codegen::Bindings::WindowBinding::{ScrollBehavior, ScrollToOptions}; use crate::dom::bindings::codegen::UnionTypes::NodeOrString; use crate::dom::bindings::conversions::DerivedFrom; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; @@ -25,11 +25,15 @@ use crate::dom::bindings::refcounted::{Trusted, TrustedPromise}; use crate::dom::bindings::reflector::DomObject; use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom, RootedReference}; use crate::dom::bindings::str::DOMString; -use crate::dom::bindings::xmlname::{namespace_from_domstring, validate_and_extract, xml_name_type}; use crate::dom::bindings::xmlname::XMLName::InvalidXMLName; +use crate::dom::bindings::xmlname::{ + namespace_from_domstring, validate_and_extract, xml_name_type, +}; use crate::dom::characterdata::CharacterData; use crate::dom::create::create_element; -use crate::dom::customelementregistry::{CallbackReaction, CustomElementDefinition, CustomElementReaction}; +use crate::dom::customelementregistry::{ + CallbackReaction, CustomElementDefinition, CustomElementReaction, +}; use crate::dom::document::{Document, LayoutDocumentHelpers}; use crate::dom::documentfragment::DocumentFragment; use crate::dom::domrect::DOMRect; @@ -59,41 +63,43 @@ use crate::dom::htmlstyleelement::HTMLStyleElement; use crate::dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementLayoutHelpers}; use crate::dom::htmltableelement::{HTMLTableElement, HTMLTableElementLayoutHelpers}; use crate::dom::htmltablerowelement::{HTMLTableRowElement, HTMLTableRowElementLayoutHelpers}; -use crate::dom::htmltablesectionelement::{HTMLTableSectionElement, HTMLTableSectionElementLayoutHelpers}; +use crate::dom::htmltablesectionelement::{ + HTMLTableSectionElement, HTMLTableSectionElementLayoutHelpers, +}; use crate::dom::htmltemplateelement::HTMLTemplateElement; use crate::dom::htmltextareaelement::{HTMLTextAreaElement, LayoutHTMLTextAreaElementHelpers}; use crate::dom::mutationobserver::{Mutation, MutationObserver}; use crate::dom::namednodemap::NamedNodeMap; +use crate::dom::node::{document_from_node, window_from_node}; use crate::dom::node::{ChildrenMutation, LayoutNodeHelpers, Node}; use crate::dom::node::{NodeDamage, NodeFlags, UnbindContext}; -use crate::dom::node::{document_from_node, window_from_node}; use crate::dom::nodelist::NodeList; use crate::dom::promise::Promise; use crate::dom::servoparser::ServoParser; use crate::dom::text::Text; use crate::dom::validation::Validatable; -use crate::dom::virtualmethods::{VirtualMethods, vtable_for}; +use crate::dom::virtualmethods::{vtable_for, VirtualMethods}; use crate::dom::window::ReflowReason; use crate::script_thread::ScriptThread; use crate::stylesheet_loader::StylesheetOwner; use crate::task::TaskOnce; use devtools_traits::AttrInfo; use dom_struct::dom_struct; -use html5ever::{Prefix, LocalName, Namespace, QualName}; use html5ever::serialize; use html5ever::serialize::SerializeOpts; use html5ever::serialize::TraversalScope; use html5ever::serialize::TraversalScope::{ChildrenOnly, IncludeNode}; +use html5ever::{LocalName, Namespace, Prefix, QualName}; use js::jsapi::Heap; use js::jsval::JSVal; use msg::constellation_msg::InputMethodType; use net_traits::request::CorsSettings; use ref_filter_map::ref_filter_map; use script_layout_interface::message::ReflowGoal; -use selectors::Element as SelectorsElement; -use selectors::attr::{AttrSelectorOperation, NamespaceConstraint, CaseSensitivity}; +use selectors::attr::{AttrSelectorOperation, CaseSensitivity, NamespaceConstraint}; use selectors::matching::{ElementSelectorFlags, MatchingContext}; use selectors::sink::Push; +use selectors::Element as SelectorsElement; use servo_arc::Arc; use servo_atoms::Atom; use std::borrow::Cow; @@ -103,24 +109,28 @@ use std::fmt; use std::mem; use std::rc::Rc; use std::str::FromStr; -use style::CaseSensitivityExt; use style::applicable_declarations::ApplicableDeclarationBlock; use style::attr::{AttrValue, LengthOrPercentageOrAuto}; use style::context::QuirksMode; use style::dom_apis; use style::element_state::ElementState; use style::invalidation::element::restyle_hints::RestyleHint; -use style::properties::{ComputedValues, Importance, PropertyDeclaration}; -use style::properties::{PropertyDeclarationBlock, parse_style_attribute}; -use style::properties::longhands::{self, background_image, border_spacing, font_family, font_size}; +use style::properties::longhands::{ + self, background_image, border_spacing, font_family, font_size, +}; use style::properties::longhands::{overflow_x, overflow_y}; +use style::properties::{parse_style_attribute, PropertyDeclarationBlock}; +use style::properties::{ComputedValues, Importance, PropertyDeclaration}; use style::rule_tree::CascadeLevel; -use style::selector_parser::{NonTSPseudoClass, PseudoElement, RestyleDamage, SelectorImpl, SelectorParser}; use style::selector_parser::extended_filtering; -use style::shared_lock::{SharedRwLock, Locked}; +use style::selector_parser::{ + NonTSPseudoClass, PseudoElement, RestyleDamage, SelectorImpl, SelectorParser, +}; +use style::shared_lock::{Locked, SharedRwLock}; use style::thread_state; +use style::values::{computed, specified}; use style::values::{CSSFloat, Either}; -use style::values::{specified, computed}; +use style::CaseSensitivityExt; use xml5ever::serialize as xmlSerialize; use xml5ever::serialize::SerializeOpts as XmlSerializeOpts; use xml5ever::serialize::TraversalScope as XmlTraversalScope; @@ -456,7 +466,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 +502,8 @@ impl RawLayoutElementHelpers for Element { } else { None } - }).collect() + }) + .collect() } } @@ -2014,7 +2026,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 +2779,7 @@ impl<'a> SelectorsElement for DomRoot { #[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> { @@ -3102,7 +3113,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/event.rs b/components/script/dom/event.rs index d7151dbdcc1..2cf3b0b2bc8 100644 --- a/components/script/dom/event.rs +++ b/components/script/dom/event.rs @@ -9,7 +9,7 @@ use crate::dom::bindings::codegen::Bindings::EventBinding::{EventConstants, Even use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::refcounted::Trusted; -use crate::dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{DomRoot, MutNullableDom, RootedReference}; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; diff --git a/components/script/dom/eventsource.rs b/components/script/dom/eventsource.rs index cd2136c72fa..b77cb5c34b2 100644 --- a/components/script/dom/eventsource.rs +++ b/components/script/dom/eventsource.rs @@ -3,11 +3,13 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::EventSourceBinding::{EventSourceInit, EventSourceMethods, Wrap}; +use crate::dom::bindings::codegen::Bindings::EventSourceBinding::{ + EventSourceInit, EventSourceMethods, Wrap, +}; use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::refcounted::Trusted; -use crate::dom::bindings::reflector::{DomObject, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::event::Event; @@ -28,10 +30,10 @@ use js::conversions::ToJSValConvertible; use js::jsapi::JSAutoCompartment; use js::jsval::UndefinedValue; use mime::{self, Mime}; -use net_traits::{CoreResourceMsg, FetchChannels, FetchMetadata}; -use net_traits::{FetchResponseMsg, FetchResponseListener, NetworkError}; use net_traits::request::{CacheMode, CorsSettings, CredentialsMode}; use net_traits::request::{RequestInit, RequestMode}; +use net_traits::{CoreResourceMsg, FetchChannels, FetchMetadata}; +use net_traits::{FetchResponseListener, FetchResponseMsg, NetworkError}; use servo_atoms::Atom; use servo_url::ServoUrl; use std::cell::Cell; @@ -40,7 +42,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 +180,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 +342,15 @@ impl FetchResponseListener for EventSourceContext { match meta.content_type { None => self.fail_the_connection(), Some(ct) => { - if >::into(ct.into_inner()) == mime::TEXT_EVENT_STREAM { + if >::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 +508,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 +551,8 @@ impl EventSource { .send(CoreResourceMsg::Fetch( request, FetchChannels::ResponseMsg(action_sender, Some(cancel_receiver)), - )).unwrap(); + )) + .unwrap(); // Step 13 Ok(ev) } @@ -614,8 +623,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 +635,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..3c1a1dd3381 100644 --- a/components/script/dom/eventtarget.rs +++ b/components/script/dom/eventtarget.rs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::beforeunloadevent::BeforeUnloadEvent; -use crate::dom::bindings::callback::{CallbackContainer, ExceptionHandling, CallbackFunction}; +use crate::dom::bindings::callback::{CallbackContainer, CallbackFunction, ExceptionHandling}; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEventMethods; use crate::dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods; @@ -20,9 +20,9 @@ use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::codegen::UnionTypes::AddEventListenerOptionsOrBoolean; use crate::dom::bindings::codegen::UnionTypes::EventListenerOptionsOrBoolean; use crate::dom::bindings::codegen::UnionTypes::EventOrString; -use crate::dom::bindings::error::{Error, Fallible, report_pending_exception}; +use crate::dom::bindings::error::{report_pending_exception, Error, Fallible}; use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::element::Element; @@ -34,14 +34,14 @@ use crate::dom::virtualmethods::VirtualMethods; use crate::dom::window::Window; use dom_struct::dom_struct; use fnv::FnvHasher; -use js::jsapi::{JS_GetFunctionObject, JSAutoCompartment, JSFunction}; -use js::rust::{AutoObjectVectorWrapper, CompileOptionsWrapper}; +use js::jsapi::{JSAutoCompartment, JSFunction, JS_GetFunctionObject}; use js::rust::wrappers::CompileFunction; +use js::rust::{AutoObjectVectorWrapper, CompileOptionsWrapper}; use libc::{c_char, size_t}; use servo_atoms::Atom; use servo_url::ServoUrl; -use std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; +use std::collections::HashMap; use std::default::Default; use std::ffi::CString; use std::hash::BuildHasherDefault; @@ -302,7 +302,8 @@ impl EventListeners { } else { None } - }).collect() + }) + .collect() } fn has_listeners(&self) -> bool { diff --git a/components/script/dom/file.rs b/components/script/dom/file.rs index 3046e122417..978460855c1 100644 --- a/components/script/dom/file.rs +++ b/components/script/dom/file.rs @@ -10,7 +10,7 @@ use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; -use crate::dom::blob::{Blob, BlobImpl, blob_parts_to_bytes}; +use crate::dom::blob::{blob_parts_to_bytes, Blob, BlobImpl}; use crate::dom::globalscope::GlobalScope; use crate::dom::window::Window; use dom_struct::dom_struct; diff --git a/components/script/dom/filelist.rs b/components/script/dom/filelist.rs index 0049f8fca4a..241305c71a4 100644 --- a/components/script/dom/filelist.rs +++ b/components/script/dom/filelist.rs @@ -4,7 +4,7 @@ use crate::dom::bindings::codegen::Bindings::FileListBinding; use crate::dom::bindings::codegen::Bindings::FileListBinding::FileListMethods; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::file::File; use crate::dom::window::Window; diff --git a/components/script/dom/filereader.rs b/components/script/dom/filereader.rs index 885ff56901d..c10f7688b40 100644 --- a/components/script/dom/filereader.rs +++ b/components/script/dom/filereader.rs @@ -5,12 +5,14 @@ use base64; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; -use crate::dom::bindings::codegen::Bindings::FileReaderBinding::{self, FileReaderConstants, FileReaderMethods}; +use crate::dom::bindings::codegen::Bindings::FileReaderBinding::{ + self, FileReaderConstants, FileReaderMethods, +}; use crate::dom::bindings::codegen::UnionTypes::StringOrObject; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::refcounted::Trusted; -use crate::dom::bindings::reflector::{DomObject, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::{DomRoot, MutNullableDom}; use crate::dom::bindings::str::DOMString; use crate::dom::bindings::trace::RootedTraceableBox; @@ -21,8 +23,8 @@ use crate::dom::eventtarget::EventTarget; use crate::dom::globalscope::GlobalScope; use crate::dom::progressevent::ProgressEvent; use crate::task::TaskCanceller; -use crate::task_source::{TaskSource, TaskSourceName}; use crate::task_source::file_reading::{FileReadingTask, FileReadingTaskSource}; +use crate::task_source::{TaskSource, TaskSourceName}; use dom_struct::dom_struct; use encoding_rs::{Encoding, UTF_8}; use js::jsapi::Heap; @@ -465,7 +467,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..9738cfed73b 100644 --- a/components/script/dom/filereadersync.rs +++ b/components/script/dom/filereadersync.rs @@ -3,9 +3,11 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; -use crate::dom::bindings::codegen::Bindings::FileReaderSyncBinding::{FileReaderSyncBinding, FileReaderSyncMethods}; +use crate::dom::bindings::codegen::Bindings::FileReaderSyncBinding::{ + FileReaderSyncBinding, FileReaderSyncMethods, +}; use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::blob::Blob; @@ -100,7 +102,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..3109b9c67d9 100644 --- a/components/script/dom/formdata.rs +++ b/components/script/dom/formdata.rs @@ -9,17 +9,17 @@ use crate::dom::bindings::codegen::UnionTypes::FileOrUSVString; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::iterable::Iterable; -use crate::dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::{DOMString, USVString}; use crate::dom::blob::{Blob, BlobImpl}; use crate::dom::file::File; use crate::dom::globalscope::GlobalScope; -use crate::dom::htmlformelement::{HTMLFormElement, FormDatumValue, FormDatum}; +use crate::dom::htmlformelement::{FormDatum, FormDatumValue, HTMLFormElement}; use dom_struct::dom_struct; use html5ever::LocalName; -use std::collections::BTreeMap; use std::collections::btree_map::Entry::{Occupied, Vacant}; +use std::collections::BTreeMap; use std::iter; #[dom_struct] @@ -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..40754b7baf5 100644 --- a/components/script/dom/gainnode.rs +++ b/components/script/dom/gainnode.rs @@ -5,9 +5,13 @@ use crate::dom::audionode::AudioNode; use crate::dom::audioparam::AudioParam; use crate::dom::baseaudiocontext::BaseAudioContext; -use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ChannelCountMode, ChannelInterpretation}; +use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ + ChannelCountMode, ChannelInterpretation, +}; use crate::dom::bindings::codegen::Bindings::AudioParamBinding::AutomationRate; -use crate::dom::bindings::codegen::Bindings::GainNodeBinding::{self, GainNodeMethods, GainOptions}; +use crate::dom::bindings::codegen::Bindings::GainNodeBinding::{ + self, GainNodeMethods, GainOptions, +}; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::{Dom, DomRoot}; @@ -48,9 +52,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/gamepad.rs b/components/script/dom/gamepad.rs index 24177b70bfc..6994e16c4c4 100644 --- a/components/script/dom/gamepad.rs +++ b/components/script/dom/gamepad.rs @@ -6,7 +6,7 @@ use crate::dom::bindings::codegen::Bindings::GamepadBinding; use crate::dom::bindings::codegen::Bindings::GamepadBinding::GamepadMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::num::Finite; -use crate::dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::event::Event; @@ -17,7 +17,7 @@ use crate::dom::globalscope::GlobalScope; use crate::dom::vrpose::VRPose; use dom_struct::dom_struct; use js::jsapi::{Heap, JSContext, JSObject}; -use js::typedarray::{Float64Array, CreateWith}; +use js::typedarray::{CreateWith, Float64Array}; use std::cell::Cell; use std::ptr; use std::ptr::NonNull; diff --git a/components/script/dom/gamepadbutton.rs b/components/script/dom/gamepadbutton.rs index 8162aefc845..57d50994c75 100644 --- a/components/script/dom/gamepadbutton.rs +++ b/components/script/dom/gamepadbutton.rs @@ -5,7 +5,7 @@ use crate::dom::bindings::codegen::Bindings::GamepadButtonBinding; use crate::dom::bindings::codegen::Bindings::GamepadButtonBinding::GamepadButtonMethods; use crate::dom::bindings::num::Finite; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; diff --git a/components/script/dom/gamepadbuttonlist.rs b/components/script/dom/gamepadbuttonlist.rs index 87608789fed..175b7c7aeef 100644 --- a/components/script/dom/gamepadbuttonlist.rs +++ b/components/script/dom/gamepadbuttonlist.rs @@ -4,7 +4,7 @@ use crate::dom::bindings::codegen::Bindings::GamepadButtonListBinding; use crate::dom::bindings::codegen::Bindings::GamepadButtonListBinding::GamepadButtonListMethods; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot, RootedReference}; use crate::dom::gamepadbutton::GamepadButton; use crate::dom::globalscope::GlobalScope; diff --git a/components/script/dom/gamepadevent.rs b/components/script/dom/gamepadevent.rs index e25b1de6731..c96c3e021bd 100644 --- a/components/script/dom/gamepadevent.rs +++ b/components/script/dom/gamepadevent.rs @@ -7,7 +7,7 @@ use crate::dom::bindings::codegen::Bindings::GamepadEventBinding; use crate::dom::bindings::codegen::Bindings::GamepadEventBinding::GamepadEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{DomObject, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::event::Event; diff --git a/components/script/dom/gamepadlist.rs b/components/script/dom/gamepadlist.rs index f207f8316a0..b158cc3891c 100644 --- a/components/script/dom/gamepadlist.rs +++ b/components/script/dom/gamepadlist.rs @@ -5,7 +5,7 @@ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::GamepadListBinding; use crate::dom::bindings::codegen::Bindings::GamepadListBinding::GamepadListMethods; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::gamepad::Gamepad; use crate::dom::globalscope::GlobalScope; diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 9e06a707fa3..96d4131f581 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -7,11 +7,11 @@ use crate::dom::bindings::codegen::Bindings::EventSourceBinding::EventSourceBind use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::codegen::Bindings::WorkerGlobalScopeBinding::WorkerGlobalScopeMethods; use crate::dom::bindings::conversions::root_from_object; -use crate::dom::bindings::error::{ErrorInfo, report_pending_exception}; +use crate::dom::bindings::error::{report_pending_exception, ErrorInfo}; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::DomObject; use crate::dom::bindings::root::{DomRoot, MutNullableDom}; -use crate::dom::bindings::settings_stack::{AutoEntryScript, entry_global, incumbent_global}; +use crate::dom::bindings::settings_stack::{entry_global, incumbent_global, AutoEntryScript}; use crate::dom::bindings::str::DOMString; use crate::dom::bindings::weakref::DOMTracker; use crate::dom::crypto::Crypto; @@ -28,43 +28,43 @@ use crate::microtask::{Microtask, MicrotaskQueue}; use crate::script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort}; use crate::script_thread::{MainThreadScriptChan, ScriptThread}; use crate::task::TaskCanceller; -use crate::task_source::TaskSourceName; use crate::task_source::dom_manipulation::DOMManipulationTaskSource; use crate::task_source::file_reading::FileReadingTaskSource; use crate::task_source::networking::NetworkingTaskSource; use crate::task_source::performance_timeline::PerformanceTimelineTaskSource; use crate::task_source::remote_event::RemoteEventTaskSource; use crate::task_source::websocket::WebsocketTaskSource; +use crate::task_source::TaskSourceName; use crate::timers::{IsInterval, OneshotTimerCallback, OneshotTimerHandle}; use crate::timers::{OneshotTimers, TimerCallback}; use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId}; use dom_struct::dom_struct; use ipc_channel::ipc::IpcSender; -use js::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL}; use js::glue::{IsWrapper, UnwrapObject}; -use js::jsapi::{CurrentGlobalOrNull, GetGlobalForObjectCrossCompartment}; -use js::jsapi::{Heap, HandleObject}; -use js::jsapi::{JSAutoCompartment, JSContext}; use js::jsapi::JSObject; +use js::jsapi::{CurrentGlobalOrNull, GetGlobalForObjectCrossCompartment}; +use js::jsapi::{HandleObject, Heap}; +use js::jsapi::{JSAutoCompartment, JSContext}; use js::panic::maybe_resume_unwind; -use js::rust::{CompileOptionsWrapper, Runtime, get_object_class}; -use js::rust::{HandleValue, MutableHandleValue}; use js::rust::wrappers::Evaluate2; +use js::rust::{get_object_class, CompileOptionsWrapper, Runtime}; +use js::rust::{HandleValue, MutableHandleValue}; +use js::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL}; use libc; use msg::constellation_msg::PipelineId; -use net_traits::{CoreResourceThread, ResourceThreads, IpcSend}; +use net_traits::{CoreResourceThread, IpcSend, ResourceThreads}; use profile_traits::{mem as profile_mem, time as profile_time}; use script_traits::{MsDuration, ScriptToConstellationChan, TimerEvent}; use script_traits::{TimerEventId, TimerSchedulerMsg, TimerSource}; use servo_url::{MutableOrigin, ServoUrl}; use std::cell::Cell; -use std::collections::HashMap; use std::collections::hash_map::Entry; +use std::collections::HashMap; use std::ffi::CString; use std::rc::Rc; -use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -use time::{Timespec, get_time}; +use std::sync::Arc; +use time::{get_time, Timespec}; #[derive(JSTraceable)] pub struct AutoCloseWorker(Arc); @@ -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..c7c71fb7dde 100644 --- a/components/script/dom/headers.rs +++ b/components/script/dom/headers.rs @@ -3,12 +3,14 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMethods, HeadersWrap}; +use crate::dom::bindings::codegen::Bindings::HeadersBinding::{ + HeadersInit, HeadersMethods, HeadersWrap, +}; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::iterable::Iterable; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::{ByteString, is_token}; +use crate::dom::bindings::str::{is_token, ByteString}; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; use http::header::{self, HeaderMap as HyperHeaders, HeaderName, HeaderValue}; @@ -87,14 +89,19 @@ impl HeadersMethods for Headers { } // Step 7 let mut combined_value: Vec = 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 +136,11 @@ impl HeadersMethods for Headers { fn Get(&self, name: ByteString) -> Fallible> { // 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 +178,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 +195,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 +261,10 @@ impl Headers { // https://fetch.spec.whatwg.org/#concept-header-extract-mime-type pub fn extract_mime_type(&self) -> Vec { - 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 +312,12 @@ fn is_cors_safelisted_request_content_type(value: &[u8]) -> bool { let value_mime_result: Result = 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/history.rs b/components/script/dom/history.rs index b23b4a2d330..da0e1c325b8 100644 --- a/components/script/dom/history.rs +++ b/components/script/dom/history.rs @@ -8,7 +8,7 @@ use crate::dom::bindings::codegen::Bindings::LocationBinding::LocationBinding::L use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::{DOMString, USVString}; use crate::dom::bindings::structuredclone::StructuredCloneData; diff --git a/components/script/dom/htmlanchorelement.rs b/components/script/dom/htmlanchorelement.rs index b6c45b33cfd..73f16a8340a 100644 --- a/components/script/dom/htmlanchorelement.rs +++ b/components/script/dom/htmlanchorelement.rs @@ -21,7 +21,7 @@ use crate::dom::eventtarget::EventTarget; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmlimageelement::HTMLImageElement; use crate::dom::mouseevent::MouseEvent; -use crate::dom::node::{Node, document_from_node}; +use crate::dom::node::{document_from_node, Node}; use crate::dom::urlhelper::UrlHelper; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; diff --git a/components/script/dom/htmlareaelement.rs b/components/script/dom/htmlareaelement.rs index 686740ef818..1a167bd3b94 100644 --- a/components/script/dom/htmlareaelement.rs +++ b/components/script/dom/htmlareaelement.rs @@ -16,7 +16,7 @@ use crate::dom::event::Event; use crate::dom::eventtarget::EventTarget; use crate::dom::htmlanchorelement::follow_hyperlink; use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{Node, document_from_node}; +use crate::dom::node::{document_from_node, Node}; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use euclid::Point2D; diff --git a/components/script/dom/htmlbaseelement.rs b/components/script/dom/htmlbaseelement.rs index 141d74f3223..33ba9886b48 100644 --- a/components/script/dom/htmlbaseelement.rs +++ b/components/script/dom/htmlbaseelement.rs @@ -11,7 +11,7 @@ use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::{AttributeMutation, Element}; use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{Node, UnbindContext, document_from_node}; +use crate::dom::node::{document_from_node, Node, UnbindContext}; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; diff --git a/components/script/dom/htmlbodyelement.rs b/components/script/dom/htmlbodyelement.rs index a72906e1337..b3bf5e6a76e 100644 --- a/components/script/dom/htmlbodyelement.rs +++ b/components/script/dom/htmlbodyelement.rs @@ -3,16 +3,18 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::attr::Attr; -use crate::dom::bindings::codegen::Bindings::HTMLBodyElementBinding::{self, HTMLBodyElementMethods}; +use crate::dom::bindings::codegen::Bindings::HTMLBodyElementBinding::{ + self, HTMLBodyElementMethods, +}; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::root::{LayoutDom, DomRoot}; +use crate::dom::bindings::root::{DomRoot, LayoutDom}; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::{AttributeMutation, Element, RawLayoutElementHelpers}; use crate::dom::eventtarget::EventTarget; use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{Node, document_from_node, window_from_node}; +use crate::dom::node::{document_from_node, window_from_node, Node}; use crate::dom::virtualmethods::VirtualMethods; use cssparser::RGBA; use dom_struct::dom_struct; diff --git a/components/script/dom/htmlbuttonelement.rs b/components/script/dom/htmlbuttonelement.rs index c7e28a672c1..b954c4a7d34 100755 --- a/components/script/dom/htmlbuttonelement.rs +++ b/components/script/dom/htmlbuttonelement.rs @@ -2,7 +2,7 @@ * 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/. */ -use crate::dom::activation::{Activatable, ActivationSource, synthetic_click_activation}; +use crate::dom::activation::{synthetic_click_activation, Activatable, ActivationSource}; use crate::dom::attr::Attr; use crate::dom::bindings::codegen::Bindings::HTMLButtonElementBinding; use crate::dom::bindings::codegen::Bindings::HTMLButtonElementBinding::HTMLButtonElementMethods; @@ -15,13 +15,13 @@ use crate::dom::event::Event; use crate::dom::eventtarget::EventTarget; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmlfieldsetelement::HTMLFieldSetElement; +use crate::dom::htmlformelement::HTMLFormElement; use crate::dom::htmlformelement::{FormControl, FormDatum, FormDatumValue}; use crate::dom::htmlformelement::{FormSubmitter, ResetFrom, SubmittedFrom}; -use crate::dom::htmlformelement::HTMLFormElement; -use crate::dom::node::{Node, UnbindContext, document_from_node, window_from_node}; +use crate::dom::node::{document_from_node, window_from_node, Node, UnbindContext}; use crate::dom::nodelist::NodeList; use crate::dom::validation::Validatable; -use crate::dom::validitystate::{ValidityState, ValidationFlags}; +use crate::dom::validitystate::{ValidationFlags, ValidityState}; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; @@ -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..0661f5717f0 100644 --- a/components/script/dom/htmlcanvaselement.rs +++ b/components/script/dom/htmlcanvaselement.rs @@ -3,12 +3,14 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use base64; -use canvas_traits::canvas::{CanvasMsg, CanvasId, FromScriptMsg}; +use canvas_traits::canvas::{CanvasId, CanvasMsg, FromScriptMsg}; use canvas_traits::webgl::WebGLVersion; use crate::dom::attr::Attr; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::HTMLCanvasElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLCanvasElementBinding::{HTMLCanvasElementMethods, RenderingContext}; +use crate::dom::bindings::codegen::Bindings::HTMLCanvasElementBinding::{ + HTMLCanvasElementMethods, RenderingContext, +}; use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLContextAttributes; use crate::dom::bindings::conversions::ConversionResult; use crate::dom::bindings::error::{Error, Fallible}; @@ -16,20 +18,24 @@ use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::DomObject; use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom}; use crate::dom::bindings::str::{DOMString, USVString}; -use crate::dom::canvasrenderingcontext2d::{CanvasRenderingContext2D, LayoutCanvasRenderingContext2DHelpers}; +use crate::dom::canvasrenderingcontext2d::{ + CanvasRenderingContext2D, LayoutCanvasRenderingContext2DHelpers, +}; use crate::dom::document::Document; use crate::dom::element::{AttributeMutation, Element, RawLayoutElementHelpers}; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{Node, window_from_node}; +use crate::dom::node::{window_from_node, Node}; use crate::dom::virtualmethods::VirtualMethods; use crate::dom::webgl2renderingcontext::WebGL2RenderingContext; -use crate::dom::webglrenderingcontext::{LayoutCanvasWebGLRenderingContextHelpers, WebGLRenderingContext}; +use crate::dom::webglrenderingcontext::{ + LayoutCanvasWebGLRenderingContextHelpers, WebGLRenderingContext, +}; use dom_struct::dom_struct; use euclid::{Rect, Size2D}; use html5ever::{LocalName, Prefix}; -use image::ColorType; use image::png::PNGEncoder; +use image::ColorType; use js::error::throw_type_error; use js::jsapi::JSContext; use js::rust::HandleValue; @@ -302,7 +308,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)) @@ -440,8 +446,8 @@ impl<'a> From<&'a WebGLContextAttributes> for GLContextAttributes { pub mod utils { use crate::dom::window::Window; - use net_traits::image_cache::{ImageResponse, UsePlaceholder, ImageOrMetadataAvailable}; use net_traits::image_cache::CanRequestImages; + use net_traits::image_cache::{ImageOrMetadataAvailable, ImageResponse, UsePlaceholder}; use servo_url::ServoUrl; pub fn request_image_from_cache(window: &Window, url: ServoUrl) -> ImageResponse { diff --git a/components/script/dom/htmlcollection.rs b/components/script/dom/htmlcollection.rs index cb2853e1307..99d3c4775b8 100644 --- a/components/script/dom/htmlcollection.rs +++ b/components/script/dom/htmlcollection.rs @@ -5,13 +5,13 @@ use crate::dom::bindings::codegen::Bindings::HTMLCollectionBinding; use crate::dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMethods; use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{Reflector, reflect_dom_object}; +use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; use crate::dom::bindings::str::DOMString; use crate::dom::bindings::trace::JSTraceable; use crate::dom::bindings::xmlname::namespace_from_domstring; use crate::dom::element::Element; -use crate::dom::node::{Node, document_from_node}; +use crate::dom::node::{document_from_node, Node}; use crate::dom::window::Window; use dom_struct::dom_struct; use html5ever::{LocalName, QualName}; diff --git a/components/script/dom/htmldatalistelement.rs b/components/script/dom/htmldatalistelement.rs index de7230a441d..9c58b94695a 100644 --- a/components/script/dom/htmldatalistelement.rs +++ b/components/script/dom/htmldatalistelement.rs @@ -11,7 +11,7 @@ use crate::dom::element::Element; use crate::dom::htmlcollection::{CollectionFilter, HTMLCollection}; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmloptionelement::HTMLOptionElement; -use crate::dom::node::{Node, window_from_node}; +use crate::dom::node::{window_from_node, Node}; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; diff --git a/components/script/dom/htmldetailselement.rs b/components/script/dom/htmldetailselement.rs index b3c8fadbc43..80d4c1caa98 100644 --- a/components/script/dom/htmldetailselement.rs +++ b/components/script/dom/htmldetailselement.rs @@ -12,7 +12,7 @@ use crate::dom::document::Document; use crate::dom::element::AttributeMutation; use crate::dom::eventtarget::EventTarget; use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{Node, window_from_node}; +use crate::dom::node::{window_from_node, Node}; use crate::dom::virtualmethods::VirtualMethods; use crate::task_source::TaskSource; use dom_struct::dom_struct; diff --git a/components/script/dom/htmldialogelement.rs b/components/script/dom/htmldialogelement.rs index e54ef512ac6..36edbefa9cb 100644 --- a/components/script/dom/htmldialogelement.rs +++ b/components/script/dom/htmldialogelement.rs @@ -12,7 +12,7 @@ use crate::dom::document::Document; use crate::dom::element::Element; use crate::dom::eventtarget::EventTarget; use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{Node, window_from_node}; +use crate::dom::node::{window_from_node, Node}; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; diff --git a/components/script/dom/htmlelement.rs b/components/script/dom/htmlelement.rs index 5b29b8957f3..c3702a0357a 100644 --- a/components/script/dom/htmlelement.rs +++ b/components/script/dom/htmlelement.rs @@ -2,7 +2,7 @@ * 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/. */ -use crate::dom::activation::{ActivationSource, synthetic_click_activation}; +use crate::dom::activation::{synthetic_click_activation, ActivationSource}; use crate::dom::attr::Attr; use crate::dom::bindings::codegen::Bindings::ElementBinding::ElementMethods; use crate::dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; @@ -11,8 +11,8 @@ use crate::dom::bindings::codegen::Bindings::HTMLElementBinding::HTMLElementMeth use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::error::{Error, ErrorResult}; -use crate::dom::bindings::inheritance::{ElementTypeId, HTMLElementTypeId, NodeTypeId}; use crate::dom::bindings::inheritance::Castable; +use crate::dom::bindings::inheritance::{ElementTypeId, HTMLElementTypeId, NodeTypeId}; use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom, RootedReference}; use crate::dom::bindings::str::DOMString; use crate::dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner}; @@ -27,8 +27,8 @@ use crate::dom::htmlframesetelement::HTMLFrameSetElement; use crate::dom::htmlhtmlelement::HTMLHtmlElement; use crate::dom::htmlinputelement::{HTMLInputElement, InputType}; use crate::dom::htmllabelelement::HTMLLabelElement; -use crate::dom::node::{Node, NodeFlags}; use crate::dom::node::{document_from_node, window_from_node}; +use crate::dom::node::{Node, NodeFlags}; use crate::dom::nodelist::NodeList; use crate::dom::text::Text; use crate::dom::virtualmethods::VirtualMethods; @@ -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