diff options
Diffstat (limited to 'components')
125 files changed, 1081 insertions, 932 deletions
diff --git a/components/canvas_traits/lib.rs b/components/canvas_traits/lib.rs index 38da38ae6e1..41115b39db1 100644 --- a/components/canvas_traits/lib.rs +++ b/components/canvas_traits/lib.rs @@ -66,13 +66,13 @@ pub enum FromPaintMsg { } impl Serialize for FromPaintMsg { - fn serialize<S>(&self, _: &mut S) -> Result<(),S::Error> where S: Serializer { + fn serialize<S>(&self, _: &mut S) -> Result<(), S::Error> where S: Serializer { panic!("can't serialize a `FromPaintMsg`!") } } impl Deserialize for FromPaintMsg { - fn deserialize<D>(_: &mut D) -> Result<FromPaintMsg,D::Error> where D: Deserializer { + fn deserialize<D>(_: &mut D) -> Result<FromPaintMsg, D::Error> where D: Deserializer { panic!("can't deserialize a `FromPaintMsg`!") } } diff --git a/components/compositing/compositor.rs b/components/compositing/compositor.rs index 91e885c880e..9a561b6b7fa 100644 --- a/components/compositing/compositor.rs +++ b/components/compositing/compositor.rs @@ -52,7 +52,7 @@ use url::Url; use util::geometry::{Au, PagePx, ScreenPx, ViewportPx}; use util::opts; -const BUFFER_MAP_SIZE : usize = 10000000; +const BUFFER_MAP_SIZE: usize = 10000000; /// Holds the state when running reftests that determines when it is /// safe to save the output image. @@ -163,8 +163,8 @@ pub struct IOCompositor<Window: WindowMethods> { } pub struct ScrollEvent { - delta: TypedPoint2D<DevicePixel,f32>, - cursor: TypedPoint2D<DevicePixel,i32>, + delta: TypedPoint2D<DevicePixel, f32>, + cursor: TypedPoint2D<DevicePixel, i32>, } #[derive(PartialEq)] @@ -249,7 +249,7 @@ pub fn reporter_name() -> String { impl<Window: WindowMethods> IOCompositor<Window> { fn new(window: Rc<Window>, - sender: Box<CompositorProxy+Send>, + sender: Box<CompositorProxy + Send>, receiver: Box<CompositorReceiver>, constellation_chan: ConstellationChan, time_profiler_chan: time::ProfilerChan, @@ -312,7 +312,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { } pub fn create(window: Rc<Window>, - sender: Box<CompositorProxy+Send>, + sender: Box<CompositorProxy + Send>, receiver: Box<CompositorReceiver>, constellation_chan: ConstellationChan, time_profiler_chan: time::ProfilerChan, @@ -401,7 +401,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { (Msg::AssignPaintedBuffers(pipeline_id, epoch, replies, frame_tree_id), ShutdownState::NotShuttingDown) => { - for (layer_id, new_layer_buffer_set) in replies.into_iter() { + for (layer_id, new_layer_buffer_set) in replies { self.assign_painted_buffers(pipeline_id, layer_id, new_layer_buffer_set, @@ -1033,7 +1033,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { fn process_pending_scroll_events(&mut self) { let had_scroll_events = self.pending_scroll_events.len() > 0; for scroll_event in std_mem::replace(&mut self.pending_scroll_events, - Vec::new()).into_iter() { + Vec::new()) { let delta = scroll_event.delta / self.scene.scale; let cursor = scroll_event.cursor.as_f32() / self.scene.scale; @@ -1073,7 +1073,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { .unwrap() .push((extra_layer_data.id, visible_rect)); - for kid in layer.children.borrow().iter() { + for kid in &*layer.children.borrow() { process_layer(&*kid, window_size, new_display_ports) } } @@ -1246,7 +1246,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { let scale = self.device_pixels_per_page_px(); let mut results: HashMap<PipelineId, Vec<PaintRequest>> = HashMap::new(); - for (layer, mut layer_requests) in requests.into_iter() { + for (layer, mut layer_requests) in requests { let pipeline_id = layer.pipeline_id(); let current_epoch = self.pipeline_details.get(&pipeline_id).unwrap().current_epoch; layer.extra_data.borrow_mut().requested_epoch = current_epoch; @@ -1293,7 +1293,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { pipeline.script_chan.send(ConstellationControlMsg::Viewport(pipeline.id.clone(), layer_rect)).unwrap(); } - for kid in layer.children().iter() { + for kid in &*layer.children() { self.send_viewport_rect_for_layer(kid.clone()); } } @@ -1329,7 +1329,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { let pipeline_requests = self.convert_buffer_requests_to_pipeline_requests_map(layers_and_requests); - for (pipeline_id, requests) in pipeline_requests.into_iter() { + for (pipeline_id, requests) in pipeline_requests { let msg = ChromeToPaintMsg::Paint(requests, self.frame_tree_id); let _ = self.get_pipeline(pipeline_id).chrome_to_paint_chan.send(msg); } @@ -1357,7 +1357,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { return true; } - for child in layer.children().iter() { + for child in &*layer.children() { if self.does_layer_have_outstanding_paint_messages(child) { return true; } @@ -1659,7 +1659,7 @@ impl<Window: WindowMethods> IOCompositor<Window> { *layer.bounds.borrow(), *layer.masks_to_bounds.borrow(), layer.establishes_3d_context); - for kid in layer.children().iter() { + for kid in &*layer.children() { self.dump_layer_tree_with_indent(&**kid, level + 1) } } @@ -1674,7 +1674,7 @@ fn find_layer_with_pipeline_and_layer_id_for_layer(layer: Rc<Layer<CompositorDat return Some(layer); } - for kid in layer.children().iter() { + for kid in &*layer.children() { let result = find_layer_with_pipeline_and_layer_id_for_layer(kid.clone(), pipeline_id, layer_id); @@ -1708,7 +1708,7 @@ impl<Window> CompositorEventListener for IOCompositor<Window> where Window: Wind } // Handle any messages coming from the windowing system. - for message in messages.into_iter() { + for message in messages { self.handle_window_message(message); } diff --git a/components/compositing/compositor_layer.rs b/components/compositing/compositor_layer.rs index 3b4ea12a9f2..82297f6f8fd 100644 --- a/components/compositing/compositor_layer.rs +++ b/components/compositing/compositor_layer.rs @@ -250,7 +250,7 @@ impl CompositorLayer for Layer<CompositorData> { compositor: &mut IOCompositor<Window>) where Window: WindowMethods { self.clear(compositor); - for kid in self.children().iter() { + for kid in &*self.children() { kid.clear_all_tiles(compositor); } } @@ -273,7 +273,7 @@ impl CompositorLayer for Layer<CompositorData> { } None => { // Wasn't found, recurse into child layers - for kid in self.children().iter() { + for kid in &*self.children() { kid.remove_root_layer_with_pipeline_id(compositor, pipeline_id); } } @@ -288,7 +288,7 @@ impl CompositorLayer for Layer<CompositorData> { // Traverse children first so that layers are removed // bottom up - allowing each layer being removed to properly // clean up any tiles it owns. - for kid in self.children().iter() { + for kid in &*self.children() { kid.collect_old_layers(compositor, pipeline_id, new_layers); } @@ -324,12 +324,12 @@ impl CompositorLayer for Layer<CompositorData> { /// This is used during shutdown, when we know the paint task is going away. fn forget_all_tiles(&self) { let tiles = self.collect_buffers(); - for tile in tiles.into_iter() { + for tile in tiles { let mut tile = tile; tile.mark_wont_leak() } - for kid in self.children().iter() { + for kid in &*self.children() { kid.forget_all_tiles(); } } @@ -341,7 +341,7 @@ impl CompositorLayer for Layer<CompositorData> { // Allow children to scroll. let scroll_offset = self.extra_data.borrow().scroll_offset; let new_cursor = cursor - scroll_offset; - for child in self.children().iter() { + for child in &*self.children() { let child_bounds = child.bounds.borrow(); if child_bounds.contains(&new_cursor) { let result = child.handle_scroll_event(delta, new_cursor - child_bounds.origin); @@ -365,7 +365,7 @@ impl CompositorLayer for Layer<CompositorData> { let content_size = calculate_content_size_for_layer(self); let min_x = (layer_size.width - content_size.width).get().min(0.0); let min_y = (layer_size.height - content_size.height).get().min(0.0); - let new_offset : TypedPoint2D<LayerPixel, f32> = + let new_offset: TypedPoint2D<LayerPixel, f32> = Point2D::new(Length::new(new_offset.x.get().clamp(&min_x, &0.0)), Length::new(new_offset.y.get().clamp(&min_y, &0.0))); @@ -378,7 +378,7 @@ impl CompositorLayer for Layer<CompositorData> { self.extra_data.borrow_mut().scroll_offset = new_offset; let mut result = false; - for child in self.children().iter() { + for child in &*self.children() { result |= child.scroll_layer_and_all_child_layers(new_offset); } @@ -429,7 +429,7 @@ impl CompositorLayer for Layer<CompositorData> { } let offset_for_children = new_offset + self.extra_data.borrow().scroll_offset; - for child in self.children().iter() { + for child in &*self.children() { result |= child.scroll_layer_and_all_child_layers(offset_for_children); } diff --git a/components/compositing/compositor_task.rs b/components/compositing/compositor_task.rs index d559630bfcf..fcf745a9bc2 100644 --- a/components/compositing/compositor_task.rs +++ b/components/compositing/compositor_task.rs @@ -37,7 +37,7 @@ pub trait CompositorProxy : 'static + Send { /// Sends a message to the compositor. fn send(&self, msg: Msg); /// Clones the compositor proxy. - fn clone_compositor_proxy(&self) -> Box<CompositorProxy+'static+Send>; + fn clone_compositor_proxy(&self) -> Box<CompositorProxy + 'static + Send>; } /// The port that the compositor receives messages on. As above, this is a trait supplied by the @@ -88,7 +88,7 @@ pub fn run_script_listener_thread(compositor_proxy: Box<CompositorProxy + 'stati } /// Implementation of the abstract `PaintListener` interface. -impl PaintListener for Box<CompositorProxy+'static+Send> { +impl PaintListener for Box<CompositorProxy + 'static + Send> { fn native_display(&mut self) -> Option<NativeDisplay> { let (chan, port) = channel(); self.send(Msg::GetNativeDisplay(chan)); @@ -204,7 +204,7 @@ pub enum Msg { } impl Debug for Msg { - fn fmt(&self, f: &mut Formatter) -> Result<(),Error> { + fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { match *self { Msg::Exit(..) => write!(f, "Exit"), Msg::ShutdownComplete(..) => write!(f, "ShutdownComplete"), @@ -240,7 +240,7 @@ pub struct CompositorTask; impl CompositorTask { pub fn create<Window>(window: Option<Rc<Window>>, - sender: Box<CompositorProxy+Send>, + sender: Box<CompositorProxy + Send>, receiver: Box<CompositorReceiver>, constellation_chan: ConstellationChan, time_profiler_chan: time::ProfilerChan, diff --git a/components/compositing/constellation.rs b/components/compositing/constellation.rs index 9794d23af50..5d214f397f6 100644 --- a/components/compositing/constellation.rs +++ b/components/compositing/constellation.rs @@ -219,7 +219,7 @@ enum ExitPipelineMode { } impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { - pub fn start(compositor_proxy: Box<CompositorProxy+Send>, + pub fn start(compositor_proxy: Box<CompositorProxy + Send>, resource_task: ResourceTask, image_cache_task: ImageCacheTask, font_cache_task: FontCacheTask, @@ -1019,7 +1019,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> { fn load_url_for_webdriver(&mut self, pipeline_id: PipelineId, - load_data:LoadData, + load_data: LoadData, reply: IpcSender<webdriver_msg::LoadStatus>) { let new_pipeline_id = self.load_url(pipeline_id, load_data); if let Some(id) = new_pipeline_id { diff --git a/components/compositing/pipeline.rs b/components/compositing/pipeline.rs index 6d398b6f42b..9eedfff8f5a 100644 --- a/components/compositing/pipeline.rs +++ b/components/compositing/pipeline.rs @@ -67,23 +67,23 @@ impl Pipeline { /// Starts a paint task, layout task, and possibly a script task. /// Returns the channels wrapped in a struct. /// If script_pipeline is not None, then subpage_id must also be not None. - pub fn create<LTF,STF>(id: PipelineId, - parent_info: Option<(PipelineId, SubpageId)>, - constellation_chan: ConstellationChan, - compositor_proxy: Box<CompositorProxy+'static+Send>, - devtools_chan: Option<Sender<DevtoolsControlMsg>>, - image_cache_task: ImageCacheTask, - font_cache_task: FontCacheTask, - resource_task: ResourceTask, - storage_task: StorageTask, - time_profiler_chan: time::ProfilerChan, - mem_profiler_chan: profile_mem::ProfilerChan, - window_rect: Option<TypedRect<PagePx, f32>>, - script_chan: Option<Sender<ConstellationControlMsg>>, - load_data: LoadData, - device_pixel_ratio: ScaleFactor<ViewportPx, DevicePixel, f32>) - -> (Pipeline, PipelineContent) - where LTF: LayoutTaskFactory, STF:ScriptTaskFactory { + pub fn create<LTF, STF>(id: PipelineId, + parent_info: Option<(PipelineId, SubpageId)>, + constellation_chan: ConstellationChan, + compositor_proxy: Box<CompositorProxy + 'static + Send>, + devtools_chan: Option<Sender<DevtoolsControlMsg>>, + image_cache_task: ImageCacheTask, + font_cache_task: FontCacheTask, + resource_task: ResourceTask, + storage_task: StorageTask, + time_profiler_chan: time::ProfilerChan, + mem_profiler_chan: profile_mem::ProfilerChan, + window_rect: Option<TypedRect<PagePx, f32>>, + script_chan: Option<Sender<ConstellationControlMsg>>, + load_data: LoadData, + device_pixel_ratio: ScaleFactor<ViewportPx, DevicePixel, f32>) + -> (Pipeline, PipelineContent) + where LTF: LayoutTaskFactory, STF: ScriptTaskFactory { let (layout_to_paint_chan, layout_to_paint_port) = util::ipc::optional_ipc_channel(); let (chrome_to_paint_chan, chrome_to_paint_port) = channel(); let (paint_shutdown_chan, paint_shutdown_port) = channel(); @@ -305,7 +305,7 @@ pub struct PipelineContent { } impl PipelineContent { - pub fn start_all<LTF,STF>(mut self) where LTF: LayoutTaskFactory, STF: ScriptTaskFactory { + pub fn start_all<LTF, STF>(mut self) where LTF: LayoutTaskFactory, STF: ScriptTaskFactory { let layout_pair = ScriptTaskFactory::create_layout_channel(None::<&mut STF>); let (script_to_compositor_chan, script_to_compositor_port) = ipc::channel().unwrap(); diff --git a/components/compositing/scrolling.rs b/components/compositing/scrolling.rs index e9b533d9f1a..f19a8b9b9da 100644 --- a/components/compositing/scrolling.rs +++ b/components/compositing/scrolling.rs @@ -30,7 +30,7 @@ enum ToScrollingTimerMsg { } impl ScrollingTimerProxy { - pub fn new(compositor_proxy: Box<CompositorProxy+Send>) -> ScrollingTimerProxy { + pub fn new(compositor_proxy: Box<CompositorProxy + Send>) -> ScrollingTimerProxy { let (to_scrolling_timer_sender, to_scrolling_timer_receiver) = channel(); Builder::new().spawn(move || { let mut scrolling_timer = ScrollingTimer { diff --git a/components/compositing/surface_map.rs b/components/compositing/surface_map.rs index 76bf729d9e5..190ae536684 100644 --- a/components/compositing/surface_map.rs +++ b/components/compositing/surface_map.rs @@ -69,7 +69,7 @@ impl SurfaceMap { } pub fn insert_surfaces(&mut self, display: &NativeDisplay, surfaces: Vec<NativeSurface>) { - for surface in surfaces.into_iter() { + for surface in surfaces { self.insert(display, surface); } } diff --git a/components/compositing/windowing.rs b/components/compositing/windowing.rs index 5e815f79677..71ef9b15e11 100644 --- a/components/compositing/windowing.rs +++ b/components/compositing/windowing.rs @@ -75,7 +75,7 @@ pub enum WindowEvent { } impl Debug for WindowEvent { - fn fmt(&self, f: &mut Formatter) -> Result<(),Error> { + fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { match *self { WindowEvent::Idle => write!(f, "Idle"), WindowEvent::Refresh => write!(f, "Refresh"), @@ -130,7 +130,7 @@ pub trait WindowMethods { /// This is part of the windowing system because its implementation often involves OS-specific /// magic to wake the up window's event loop. fn create_compositor_channel(_: &Option<Rc<Self>>) - -> (Box<CompositorProxy+Send>, Box<CompositorReceiver>); + -> (Box<CompositorProxy + Send>, Box<CompositorReceiver>); /// Requests that the window system prepare a composite. Typically this will involve making /// some type of platform-specific graphics context current. Returns true if the composite may diff --git a/components/devtools/actor.rs b/components/devtools/actor.rs index a4201214727..8cc9a2231ed 100644 --- a/components/devtools/actor.rs +++ b/components/devtools/actor.rs @@ -86,8 +86,8 @@ impl Actor + Send { /// A list of known, owned actors. pub struct ActorRegistry { - actors: HashMap<String, Box<Actor+Send>>, - new_actors: RefCell<Vec<Box<Actor+Send>>>, + actors: HashMap<String, Box<Actor + Send>>, + new_actors: RefCell<Vec<Box<Actor + Send>>>, old_actors: RefCell<Vec<String>>, script_actors: RefCell<HashMap<String, String>>, shareable: Option<Arc<Mutex<ActorRegistry>>>, @@ -150,7 +150,7 @@ impl ActorRegistry { } pub fn actor_to_script(&self, actor: String) -> String { - for (key, value) in self.script_actors.borrow().iter() { + for (key, value) in &*self.script_actors.borrow() { println!("checking {}", value); if *value == actor { return key.to_string(); @@ -167,11 +167,11 @@ impl ActorRegistry { } /// Add an actor to the registry of known actors that can receive messages. - pub fn register(&mut self, actor: Box<Actor+Send>) { + pub fn register(&mut self, actor: Box<Actor + Send>) { self.actors.insert(actor.name().to_string(), actor); } - pub fn register_later(&self, actor: Box<Actor+Send>) { + pub fn register_later(&self, actor: Box<Actor + Send>) { let mut actors = self.new_actors.borrow_mut(); actors.push(actor); } @@ -213,7 +213,7 @@ impl ActorRegistry { } let old_actors = replace(&mut *self.old_actors.borrow_mut(), vec!()); - for name in old_actors.into_iter() { + for name in old_actors { self.drop_actor(name); } Ok(()) diff --git a/components/devtools/actors/inspector.rs b/components/devtools/actors/inspector.rs index c8508cebefa..1c17b71439e 100644 --- a/components/devtools/actors/inspector.rs +++ b/components/devtools/actors/inspector.rs @@ -93,7 +93,7 @@ impl Actor for HighlighterActor { } #[derive(RustcEncodable)] -struct ModifyAttributeReply{ +struct ModifyAttributeReply { from: String, } @@ -119,7 +119,7 @@ impl Actor for NodeActor { registry.actor_to_script(target.to_string()), modifications)) .unwrap(); - let reply = ModifyAttributeReply{ + let reply = ModifyAttributeReply { from: self.name(), }; stream.write_json_packet(&reply); diff --git a/components/devtools/lib.rs b/components/devtools/lib.rs index bc1d09c7a14..e6d10abc313 100644 --- a/components/devtools/lib.rs +++ b/components/devtools/lib.rs @@ -297,7 +297,7 @@ fn run_server(sender: Sender<DevtoolsControlMsg>, columnNumber: console_message.columnNumber, }, }; - for stream in console_actor.streams.borrow_mut().iter_mut() { + for mut stream in &mut *console_actor.streams.borrow_mut() { stream.write_json_packet(&msg); } } diff --git a/components/devtools_traits/lib.rs b/components/devtools_traits/lib.rs index fa562744a33..b7ef2ebf5c4 100644 --- a/components/devtools_traits/lib.rs +++ b/components/devtools_traits/lib.rs @@ -192,8 +192,8 @@ impl Decodable for Modification { fn decode<D: Decoder>(d: &mut D) -> Result<Modification, D::Error> { d.read_struct("Modification", 2, |d| Ok(Modification { - attributeName: try!(d.read_struct_field("attributeName", 0, |d| Decodable::decode(d))), - newValue: match d.read_struct_field("newValue", 1, |d| Decodable::decode(d)) { + attributeName: try!(d.read_struct_field("attributeName", 0, Decodable::decode)), + newValue: match d.read_struct_field("newValue", 1, Decodable::decode) { Ok(opt) => opt, Err(_) => None } diff --git a/components/gfx/display_list/mod.rs b/components/gfx/display_list/mod.rs index f8d9d6ec8d4..f7478f91cc8 100644 --- a/components/gfx/display_list/mod.rs +++ b/components/gfx/display_list/mod.rs @@ -213,7 +213,7 @@ impl DisplayList { }; doit(&(self.all_display_items())); - if self.children.len() != 0 { + if !self.children.is_empty() { println!("{} Children stacking contexts list length: {}", indentation, self.children.len()); @@ -340,7 +340,7 @@ impl StackingContext { } // Step 3: Positioned descendants with negative z-indices. - for positioned_kid in positioned_children.iter() { + for positioned_kid in &*positioned_children { if positioned_kid.z_index >= 0 { break } @@ -382,7 +382,7 @@ impl StackingContext { } // Step 9: Positioned descendants with nonnegative, numeric z-indices. - for positioned_kid in positioned_children.iter() { + for positioned_kid in &*positioned_children { if positioned_kid.z_index < 0 { continue } @@ -471,11 +471,11 @@ impl StackingContext { mut point: Point2D<Au>, result: &mut Vec<DisplayItemMetadata>, topmost_only: bool) { - fn hit_test_in_list<'a,I>(point: Point2D<Au>, - result: &mut Vec<DisplayItemMetadata>, - topmost_only: bool, - iterator: I) - where I: Iterator<Item=&'a DisplayItem> { + fn hit_test_in_list<'a, I>(point: Point2D<Au>, + result: &mut Vec<DisplayItemMetadata>, + topmost_only: bool, + iterator: I) + where I: Iterator<Item=&'a DisplayItem> { for item in iterator { // TODO(pcwalton): Use a precise algorithm here. This will allow us to properly hit // test elements with `border-radius`, for example. @@ -554,12 +554,12 @@ impl StackingContext { // borders. // // TODO(pcwalton): Step 6: Inlines that generate stacking contexts. - for display_list in [ + for display_list in &[ &self.display_list.positioned_content, &self.display_list.content, &self.display_list.floats, &self.display_list.block_backgrounds_and_borders, - ].iter() { + ] { hit_test_in_list(point, result, topmost_only, display_list.iter().rev()); if topmost_only && !result.is_empty() { return @@ -614,7 +614,7 @@ pub fn find_stacking_context_with_layer_id(this: &Arc<StackingContext>, layer_id Some(_) | None => {} } - for kid in this.display_list.children.iter() { + for kid in &this.display_list.children { match find_stacking_context_with_layer_id(kid, layer_id) { Some(stacking_context) => return Some(stacking_context), None => {} @@ -755,7 +755,7 @@ impl ClippingRegion { #[inline] pub fn bounding_rect(&self) -> Rect<Au> { let mut rect = self.main; - for complex in self.complex.iter() { + for complex in &*self.complex { rect = rect.union(&complex.rect) } rect @@ -1016,7 +1016,7 @@ pub enum BoxShadowClipMode { pub enum DisplayItemIterator<'a> { Empty, - Parent(linked_list::Iter<'a,DisplayItem>), + Parent(linked_list::Iter<'a, DisplayItem>), } impl<'a> Iterator for DisplayItemIterator<'a> { diff --git a/components/gfx/display_list/optimizer.rs b/components/gfx/display_list/optimizer.rs index 37661ce6402..71f275a1bb6 100644 --- a/components/gfx/display_list/optimizer.rs +++ b/components/gfx/display_list/optimizer.rs @@ -45,10 +45,10 @@ impl DisplayListOptimizer { } /// Adds display items that intersect the visible rect to `result_list`. - fn add_in_bounds_display_items<'a,I>(&self, - result_list: &mut LinkedList<DisplayItem>, - display_items: I) - where I: Iterator<Item=&'a DisplayItem> { + fn add_in_bounds_display_items<'a, I>(&self, + result_list: &mut LinkedList<DisplayItem>, + display_items: I) + where I: Iterator<Item=&'a DisplayItem> { for display_item in display_items { if self.visible_rect.intersects(&display_item.base().bounds) && display_item.base().clip.might_intersect_rect(&self.visible_rect) { @@ -58,10 +58,10 @@ impl DisplayListOptimizer { } /// Adds child stacking contexts whose boundaries intersect the visible rect to `result_list`. - fn add_in_bounds_stacking_contexts<'a,I>(&self, - result_list: &mut LinkedList<Arc<StackingContext>>, - stacking_contexts: I) - where I: Iterator<Item=&'a Arc<StackingContext>> { + fn add_in_bounds_stacking_contexts<'a, I>(&self, + result_list: &mut LinkedList<Arc<StackingContext>>, + stacking_contexts: I) + where I: Iterator<Item=&'a Arc<StackingContext>> { for stacking_context in stacking_contexts { if stacking_context.layer.is_none() { // Transform this stacking context to get it into the same space as diff --git a/components/gfx/font.rs b/components/gfx/font.rs index 17625dc7fe4..a2022ead6f2 100644 --- a/components/gfx/font.rs +++ b/components/gfx/font.rs @@ -95,8 +95,8 @@ pub struct Font { pub requested_pt_size: Au, pub actual_pt_size: Au, pub shaper: Option<Shaper>, - pub shape_cache: HashCache<ShapeCacheEntry,Arc<GlyphStore>>, - pub glyph_advance_cache: HashCache<u32,FractionalPixel>, + pub shape_cache: HashCache<ShapeCacheEntry, Arc<GlyphStore>>, + pub glyph_advance_cache: HashCache<u32, FractionalPixel>, } bitflags! { diff --git a/components/gfx/font_context.rs b/components/gfx/font_context.rs index 7d5a26fe06f..089bc72a789 100644 --- a/components/gfx/font_context.rs +++ b/components/gfx/font_context.rs @@ -82,7 +82,7 @@ pub struct FontContext { paint_font_cache: Vec<PaintFontCacheEntry>, layout_font_group_cache: - HashMap<LayoutFontGroupCacheKey,Rc<FontGroup>,DefaultState<FnvHasher>>, + HashMap<LayoutFontGroupCacheKey, Rc<FontGroup>, DefaultState<FnvHasher>>, } impl FontContext { @@ -273,7 +273,7 @@ impl FontContext { } let paint_font = Rc::new(RefCell::new(create_scaled_font(template, pt_size))); - self.paint_font_cache.push(PaintFontCacheEntry{ + self.paint_font_cache.push(PaintFontCacheEntry { font: paint_font.clone(), pt_size: pt_size, identifier: template.identifier.clone(), diff --git a/components/gfx/paint_context.rs b/components/gfx/paint_context.rs index f70d8a03cd3..c0e09245056 100644 --- a/components/gfx/paint_context.rs +++ b/components/gfx/paint_context.rs @@ -244,6 +244,7 @@ impl<'a> PaintContext<'a> { self.draw_dashed_border_segment(direction, bounds, border, + radius, color_select, DashSize::DottedBorder); } @@ -251,6 +252,7 @@ impl<'a> PaintContext<'a> { self.draw_dashed_border_segment(direction, bounds, border, + radius, color_select, DashSize::DashedBorder); } @@ -291,6 +293,7 @@ impl<'a> PaintContext<'a> { self.draw_dashed_border_segment(Direction::Right, bounds, &border, + radius, color, DashSize::DottedBorder); } @@ -298,6 +301,7 @@ impl<'a> PaintContext<'a> { self.draw_dashed_border_segment(Direction::Right, bounds, &border, + radius, color, DashSize::DashedBorder); } @@ -333,7 +337,12 @@ impl<'a> PaintContext<'a> { radii: &BorderRadii<AzFloat>, color: Color) { let mut path_builder = self.draw_target.create_path_builder(); - self.create_border_path_segment(&mut path_builder, bounds, direction, border, radii); + self.create_border_path_segment(&mut path_builder, + bounds, + direction, + border, + radii, + BorderPathDrawingMode::EntireBorder); let draw_options = DrawOptions::new(1.0, CompositionOp::Over, AntialiasMode::None); self.draw_target.fill(&path_builder.finish(), Pattern::Color(ColorPattern::new(color)).to_pattern_ref(), @@ -432,7 +441,8 @@ impl<'a> PaintContext<'a> { bounds: &Rect<f32>, direction: Direction, border: &SideOffsets2D<f32>, - radius: &BorderRadii<AzFloat>) { + radius: &BorderRadii<AzFloat>, + mode: BorderPathDrawingMode) { // T = top, B = bottom, L = left, R = right let box_TL = bounds.origin; @@ -475,8 +485,13 @@ impl<'a> PaintContext<'a> { let corner_TL = edge_TL + dx_if(radius.top_left == 0., -border.left); let corner_TR = edge_TR + dx_if(radius.top_right == 0., border.right); - path_builder.move_to(corner_TL); - path_builder.line_to(corner_TR); + match mode { + BorderPathDrawingMode::EntireBorder => { + path_builder.move_to(corner_TL); + path_builder.line_to(corner_TR); + } + BorderPathDrawingMode::CornersOnly => path_builder.move_to(corner_TR), + } if radius.top_right != 0. { // the origin is the center of the arcs we're about to draw. @@ -489,8 +504,13 @@ impl<'a> PaintContext<'a> { path_builder.arc(origin, distance_to_elbow, rad_TR, rad_T, true); } - path_builder.line_to(edge_BR); - path_builder.line_to(edge_BL); + match mode { + BorderPathDrawingMode::EntireBorder => { + path_builder.line_to(edge_BR); + path_builder.line_to(edge_BL); + } + BorderPathDrawingMode::CornersOnly => path_builder.move_to(edge_BL), + } if radius.top_left != 0. { let origin = edge_TL + Point2D::new(-(border.left - radius.top_left).max(0.), @@ -510,8 +530,13 @@ impl<'a> PaintContext<'a> { let corner_TL = edge_TL + dy_if(radius.top_left == 0., -border.top); let corner_BL = edge_BL + dy_if(radius.bottom_left == 0., border.bottom); - path_builder.move_to(corner_BL); - path_builder.line_to(corner_TL); + match mode { + BorderPathDrawingMode::EntireBorder => { + path_builder.move_to(corner_BL); + path_builder.line_to(corner_TL); + } + BorderPathDrawingMode::CornersOnly => path_builder.move_to(corner_TL), + } if radius.top_left != 0. { let origin = edge_TL + Point2D::new(radius.top_left, @@ -522,8 +547,13 @@ impl<'a> PaintContext<'a> { path_builder.arc(origin, distance_to_elbow, rad_TL, rad_L, true); } - path_builder.line_to(edge_TR); - path_builder.line_to(edge_BR); + match mode { + BorderPathDrawingMode::EntireBorder => { + path_builder.line_to(edge_TR); + path_builder.line_to(edge_BR); + } + BorderPathDrawingMode::CornersOnly => path_builder.move_to(edge_BR), + } if radius.bottom_left != 0. { let origin = edge_BL + @@ -544,8 +574,13 @@ impl<'a> PaintContext<'a> { let corner_TR = edge_TR + dy_if(radius.top_right == 0., -border.top); let corner_BR = edge_BR + dy_if(radius.bottom_right == 0., border.bottom); - path_builder.move_to(edge_BL); - path_builder.line_to(edge_TL); + match mode { + BorderPathDrawingMode::EntireBorder => { + path_builder.move_to(edge_BL); + path_builder.line_to(edge_TL); + } + BorderPathDrawingMode::CornersOnly => path_builder.move_to(edge_TL), + } if radius.top_right != 0. { let origin = edge_TR + Point2D::new(-radius.top_right, @@ -556,8 +591,13 @@ impl<'a> PaintContext<'a> { path_builder.arc(origin, radius.top_right, rad_TR, rad_R, false); } - path_builder.line_to(corner_TR); - path_builder.line_to(corner_BR); + match mode { + BorderPathDrawingMode::EntireBorder => { + path_builder.line_to(corner_TR); + path_builder.line_to(corner_BR); + } + BorderPathDrawingMode::CornersOnly => path_builder.move_to(corner_BR), + } if radius.bottom_right != 0. { let origin = edge_BR + @@ -578,8 +618,13 @@ impl<'a> PaintContext<'a> { let corner_BR = edge_BR + dx_if(radius.bottom_right == 0., border.right); let corner_BL = edge_BL + dx_if(radius.bottom_left == 0., -border.left); - path_builder.move_to(edge_TL); - path_builder.line_to(edge_TR); + match mode { + BorderPathDrawingMode::EntireBorder => { + path_builder.move_to(edge_TL); + path_builder.line_to(edge_TR); + } + BorderPathDrawingMode::CornersOnly => path_builder.move_to(edge_TR), + } if radius.bottom_right != 0. { let origin = edge_BR + Point2D::new((border.right - radius.bottom_right).max(0.), @@ -590,8 +635,13 @@ impl<'a> PaintContext<'a> { path_builder.arc(origin, radius.bottom_right, rad_BR, rad_B, false); } - path_builder.line_to(corner_BR); - path_builder.line_to(corner_BL); + match mode { + BorderPathDrawingMode::EntireBorder => { + path_builder.line_to(corner_BR); + path_builder.line_to(corner_BL); + } + BorderPathDrawingMode::CornersOnly => path_builder.move_to(corner_BL), + } if radius.bottom_left != 0. { let origin = edge_BL - Point2D::new((border.left - radius.bottom_left).max(0.), @@ -660,6 +710,7 @@ impl<'a> PaintContext<'a> { direction: Direction, bounds: &Rect<Au>, border: &SideOffsets2D<f32>, + radius: &BorderRadii<AzFloat>, color: Color, dash_size: DashSize) { let rect = bounds.to_nearest_azure_rect(); @@ -680,26 +731,26 @@ impl<'a> PaintContext<'a> { let (start, end) = match direction { Direction::Top => { let y = rect.origin.y + border.top * 0.5; - let start = Point2D::new(rect.origin.x, y); - let end = Point2D::new(rect.origin.x + rect.size.width, y); + let start = Point2D::new(rect.origin.x + radius.top_left, y); + let end = Point2D::new(rect.origin.x + rect.size.width - radius.top_right, y); (start, end) } Direction::Left => { let x = rect.origin.x + border.left * 0.5; - let start = Point2D::new(x, rect.origin.y + rect.size.height); - let end = Point2D::new(x, rect.origin.y + border.top); + let start = Point2D::new(x, rect.origin.y + rect.size.height - radius.bottom_left); + let end = Point2D::new(x, rect.origin.y + border.top.max(radius.top_left)); (start, end) } Direction::Right => { let x = rect.origin.x + rect.size.width - border.right * 0.5; - let start = Point2D::new(x, rect.origin.y); - let end = Point2D::new(x, rect.origin.y + rect.size.height); + let start = Point2D::new(x, rect.origin.y + radius.top_right); + let end = Point2D::new(x, rect.origin.y + rect.size.height - radius.bottom_right); (start, end) } Direction::Bottom => { let y = rect.origin.y + rect.size.height - border.bottom * 0.5; - let start = Point2D::new(rect.origin.x + rect.size.width, y); - let end = Point2D::new(rect.origin.x + border.left, y); + let start = Point2D::new(rect.origin.x + rect.size.width - radius.bottom_right, y); + let end = Point2D::new(rect.origin.x + border.left.max(radius.bottom_left), y); (start, end) } }; @@ -709,6 +760,19 @@ impl<'a> PaintContext<'a> { PatternRef::Color(&ColorPattern::new(color)), &stroke_opts, &draw_opts); + + if radii_apply_to_border_direction(direction, radius) { + let mut path_builder = self.draw_target.create_path_builder(); + self.create_border_path_segment(&mut path_builder, + &rect, + direction, + border, + radius, + BorderPathDrawingMode::CornersOnly); + self.draw_target.fill(&path_builder.finish(), + Pattern::Color(ColorPattern::new(color)).to_pattern_ref(), + &draw_opts); + } } fn draw_solid_border_segment(&self, @@ -751,11 +815,11 @@ impl<'a> PaintContext<'a> { border: &SideOffsets2D<f32>, radius: &BorderRadii<AzFloat>, color: Color) { - let scaled_border = SideOffsets2D::new((1.0/3.0) * border.top, - (1.0/3.0) * border.right, - (1.0/3.0) * border.bottom, - (1.0/3.0) * border.left); - let inner_scaled_bounds = self.compute_scaled_bounds(bounds, border, 2.0/3.0); + let scaled_border = SideOffsets2D::new((1.0 / 3.0) * border.top, + (1.0 / 3.0) * border.right, + (1.0 / 3.0) * border.bottom, + (1.0 / 3.0) * border.left); + let inner_scaled_bounds = self.compute_scaled_bounds(bounds, border, 2.0 / 3.0); // draw the outer portion of the double border. self.draw_solid_border_segment(direction, bounds, &scaled_border, radius, color); // draw the inner portion of the double border. @@ -786,7 +850,7 @@ impl<'a> PaintContext<'a> { let lighter_color; let mut darker_color = color::black(); if color != darker_color { - darker_color = self.scale_color(color, if is_groove { 1.0/3.0 } else { 2.0/3.0 }); + darker_color = self.scale_color(color, if is_groove { 1.0 / 3.0 } else { 2.0 / 3.0 }); lighter_color = color; } else { // You can't scale black color (i.e. 'scaled = 0 * scale', equals black). @@ -832,10 +896,10 @@ impl<'a> PaintContext<'a> { if color != scaled_color { scaled_color = match direction { Direction::Top | Direction::Left => { - self.scale_color(color, if is_inset { 2.0/3.0 } else { 1.0 }) + self.scale_color(color, if is_inset { 2.0 / 3.0 } else { 1.0 }) } Direction::Right | Direction::Bottom => { - self.scale_color(color, if is_inset { 1.0 } else { 2.0/3.0 }) + self.scale_color(color, if is_inset { 1.0 } else { 2.0 / 3.0 }) } }; } else { @@ -1476,3 +1540,19 @@ impl TemporaryDrawTarget { } } + +#[derive(Copy, Clone, PartialEq)] +enum BorderPathDrawingMode { + EntireBorder, + CornersOnly, +} + +fn radii_apply_to_border_direction(direction: Direction, radius: &BorderRadii<AzFloat>) -> bool { + match (direction, radius.top_left, radius.top_right, radius.bottom_left, radius.bottom_right) { + (Direction::Top, a, b, _, _) | + (Direction::Right, _, a, _, b) | + (Direction::Bottom, _, _, a, b) | + (Direction::Left, a, _, b, _) => a != 0.0 || b != 0.0, + } +} + diff --git a/components/gfx/paint_task.rs b/components/gfx/paint_task.rs index 6e8b84ae4c5..175a7b040f1 100644 --- a/components/gfx/paint_task.rs +++ b/components/gfx/paint_task.rs @@ -233,7 +233,7 @@ impl<C> PaintTask<C> where C: PaintListener + Send + 'static { let mut replies = Vec::new(); for PaintRequest { buffer_requests, scale, layer_id, epoch, layer_kind } - in requests.into_iter() { + in requests { if self.current_epoch == Some(epoch) { self.paint(&mut replies, buffer_requests, scale, layer_id, layer_kind); } else { @@ -393,7 +393,7 @@ impl<C> PaintTask<C> where C: PaintListener + Send + 'static { } }; - for kid in stacking_context.display_list.children.iter() { + for kid in &stacking_context.display_list.children { build(properties, &**kid, &page_position, &transform, &perspective, next_parent_id) } } @@ -659,12 +659,12 @@ enum MsgFromWorkerThread { } pub static THREAD_TINT_COLORS: [Color; 8] = [ - Color { r: 6.0/255.0, g: 153.0/255.0, b: 198.0/255.0, a: 0.7 }, - Color { r: 255.0/255.0, g: 212.0/255.0, b: 83.0/255.0, a: 0.7 }, - Color { r: 116.0/255.0, g: 29.0/255.0, b: 109.0/255.0, a: 0.7 }, - Color { r: 204.0/255.0, g: 158.0/255.0, b: 199.0/255.0, a: 0.7 }, - Color { r: 242.0/255.0, g: 46.0/255.0, b: 121.0/255.0, a: 0.7 }, - Color { r: 116.0/255.0, g: 203.0/255.0, b: 196.0/255.0, a: 0.7 }, - Color { r: 255.0/255.0, g: 249.0/255.0, b: 201.0/255.0, a: 0.7 }, - Color { r: 137.0/255.0, g: 196.0/255.0, b: 78.0/255.0, a: 0.7 }, + Color { r: 6.0 / 255.0, g: 153.0 / 255.0, b: 198.0 / 255.0, a: 0.7 }, + Color { r: 255.0 / 255.0, g: 212.0 / 255.0, b: 83.0 / 255.0, a: 0.7 }, + Color { r: 116.0 / 255.0, g: 29.0 / 255.0, b: 109.0 / 255.0, a: 0.7 }, + Color { r: 204.0 / 255.0, g: 158.0 / 255.0, b: 199.0 / 255.0, a: 0.7 }, + Color { r: 242.0 / 255.0, g: 46.0 / 255.0, b: 121.0 / 255.0, a: 0.7 }, + Color { r: 116.0 / 255.0, g: 203.0 / 255.0, b: 196.0 / 255.0, a: 0.7 }, + Color { r: 255.0 / 255.0, g: 249.0 / 255.0, b: 201.0 / 255.0, a: 0.7 }, + Color { r: 137.0 / 255.0, g: 196.0 / 255.0, b: 78.0 / 255.0, a: 0.7 }, ]; diff --git a/components/gfx/platform/freetype/font_list.rs b/components/gfx/platform/freetype/font_list.rs index 4084087fc54..48534016cac 100644 --- a/components/gfx/platform/freetype/font_list.rs +++ b/components/gfx/platform/freetype/font_list.rs @@ -8,17 +8,11 @@ extern crate freetype; extern crate fontconfig; use fontconfig::fontconfig::{FcChar8, FcResultMatch, FcSetSystem}; -use fontconfig::fontconfig::{ - FcConfigGetCurrent, FcConfigGetFonts, - FcConfigSubstitute, FcDefaultSubstitute, - FcFontMatch, - FcNameParse, FcPatternGetString, - FcPatternDestroy, FcFontSetDestroy, - FcMatchPattern, - FcPatternCreate, FcPatternAddString, - FcFontSetList, FcObjectSetCreate, FcObjectSetDestroy, - FcObjectSetAdd, FcPatternGetInteger -}; +use fontconfig::fontconfig::{FcConfigGetCurrent, FcConfigGetFonts, FcConfigSubstitute}; +use fontconfig::fontconfig::{FcDefaultSubstitute, FcFontMatch, FcNameParse, FcPatternGetString}; +use fontconfig::fontconfig::{FcPatternDestroy, FcFontSetDestroy, FcMatchPattern, FcPatternCreate}; +use fontconfig::fontconfig::{FcPatternAddString, FcFontSetList, FcObjectSetCreate, FcObjectSetDestroy}; +use fontconfig::fontconfig::{FcObjectSetAdd, FcPatternGetInteger}; use util::str::c_str_to_string; diff --git a/components/gfx/platform/macos/font_template.rs b/components/gfx/platform/macos/font_template.rs index 7e8229babe1..96be6a22f5f 100644 --- a/components/gfx/platform/macos/font_template.rs +++ b/components/gfx/platform/macos/font_template.rs @@ -89,7 +89,7 @@ impl Deserialize for CachedCTFont { type Value = CachedCTFont; #[inline] - fn visit_none<E>(&mut self) -> Result<CachedCTFont,E> where E: Error { + fn visit_none<E>(&mut self) -> Result<CachedCTFont, E> where E: Error { Ok(CachedCTFont(Mutex::new(None))) } } diff --git a/components/gfx/text/glyph.rs b/components/gfx/text/glyph.rs index 75017144155..29918e5d2d9 100644 --- a/components/gfx/text/glyph.rs +++ b/components/gfx/text/glyph.rs @@ -394,7 +394,7 @@ impl<'a> DetailedGlyphStore { // Thar be dragons here. You have been warned. (Tips accepted.) let mut unsorted_records: Vec<DetailedGlyphRecord> = vec!(); mem::swap(&mut self.detail_lookup, &mut unsorted_records); - let mut mut_records : Vec<DetailedGlyphRecord> = unsorted_records; + let mut mut_records: Vec<DetailedGlyphRecord> = unsorted_records; mut_records.sort_by(|a, b| { if a < b { Ordering::Less diff --git a/components/gfx/text/text_run.rs b/components/gfx/text/text_run.rs index dbdb913f25e..258766ac08e 100644 --- a/components/gfx/text/text_run.rs +++ b/components/gfx/text/text_run.rs @@ -46,7 +46,7 @@ pub struct NaturalWordSliceIterator<'a> { struct CharIndexComparator; -impl Comparator<CharIndex,GlyphRun> for CharIndexComparator { +impl Comparator<CharIndex, GlyphRun> for CharIndexComparator { fn compare(&self, key: &CharIndex, value: &GlyphRun) -> Ordering { if *key < value.range.begin() { Ordering::Less diff --git a/components/layout/animation.rs b/components/layout/animation.rs index f22865592c3..ab11433fdfa 100644 --- a/components/layout/animation.rs +++ b/components/layout/animation.rs @@ -29,7 +29,7 @@ pub fn start_transitions_if_applicable(new_animations_sender: &Sender<Animation> for i in 0..new_style.get_animation().transition_property.0.len() { // Create any property animations, if applicable. let property_animations = PropertyAnimation::from_transition(i, old_style, new_style); - for property_animation in property_animations.into_iter() { + for property_animation in property_animations { // Set the property to the initial value. property_animation.update(new_style, 0.0); @@ -65,7 +65,7 @@ pub fn process_new_animations(rw_data: &mut LayoutTaskData, pipeline_id: Pipelin } // Add new running animations. - for new_running_animation in new_running_animations.into_iter() { + for new_running_animation in new_running_animations { match running_animations.entry(OpaqueNode(new_running_animation.node)) { Entry::Vacant(entry) => { entry.insert(vec![new_running_animation]); @@ -93,7 +93,7 @@ pub fn process_new_animations(rw_data: &mut LayoutTaskData, pipeline_id: Pipelin /// Recalculates style for a set of animations. This does *not* run with the DOM lock held. pub fn recalc_style_for_animations(flow: &mut Flow, - animations: &HashMap<OpaqueNode,Vec<Animation>>) { + animations: &HashMap<OpaqueNode, Vec<Animation>>) { let mut damage = RestyleDamage::empty(); flow.mutate_fragments(&mut |fragment| { if let Some(ref animations) = animations.get(&OpaqueNode(fragment.node.id())) { diff --git a/components/layout/block.rs b/components/layout/block.rs index fdfec58e776..420802bed43 100644 --- a/components/layout/block.rs +++ b/components/layout/block.rs @@ -451,7 +451,7 @@ impl<'a> PreorderFlowTraversal for AbsoluteAssignBSizesTraversal<'a> { } } - let block = flow.as_block(); + let block = flow.as_mut_block(); debug_assert!(block.base.flags.contains(IS_ABSOLUTELY_POSITIONED)); if !block.base.restyle_damage.intersects(REFLOW_OUT_OF_FLOW | REFLOW) { return @@ -708,9 +708,9 @@ impl BlockFlow { /// Return true if this has a replaced fragment. /// - /// Text, Images, Inline Block and - // Canvas (https://html.spec.whatwg.org/multipage/#replaced-elements) - // fragments are considered as replaced fragments + /// Text, Images, Inline Block and Canvas + /// (https://html.spec.whatwg.org/multipage/#replaced-elements) fragments are considered as + /// replaced fragments. fn is_replaced_content(&self) -> bool { match self.fragment.specific { SpecificFragmentInfo::ScannedText(_) | @@ -845,7 +845,7 @@ impl BlockFlow { if flow::base(kid).flags.is_float() { flow::mut_base(kid).position.start.b = cur_b; { - let kid_block = kid.as_block(); + let kid_block = kid.as_mut_block(); kid_block.float.as_mut().unwrap().float_ceiling = margin_collapse_info.current_float_ceiling(); } @@ -1384,7 +1384,7 @@ impl BlockFlow { } if kid.is_block_flow() { - let kid_block = kid.as_block(); + let kid_block = kid.as_mut_block(); kid_block.inline_size_of_preceding_left_floats = inline_size_of_preceding_left_floats; kid_block.inline_size_of_preceding_right_floats = @@ -1409,7 +1409,7 @@ impl BlockFlow { // necessary because any percentages are relative to the containing block, which only // we know. if kid.is_inline_flow() { - kid.as_inline().first_line_indentation = + kid.as_mut_inline().first_line_indentation = specified(self.fragment.style().get_inheritedtext().text_indent, containing_block_size); } @@ -1501,11 +1501,11 @@ impl Flow for BlockFlow { FlowClass::Block } - fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow { + fn as_mut_block<'a>(&'a mut self) -> &'a mut BlockFlow { self } - fn as_immutable_block<'a>(&'a self) -> &'a BlockFlow { + fn as_block<'a>(&'a self) -> &'a BlockFlow { self } @@ -2839,4 +2839,3 @@ impl ISizeAndMarginsComputer for FloatReplaced { MaybeAuto::Specified(fragment.content_inline_size()) } } - diff --git a/components/layout/construct.rs b/components/layout/construct.rs index a918e35463b..e90d46a00ca 100644 --- a/components/layout/construct.rs +++ b/components/layout/construct.rs @@ -17,10 +17,8 @@ use block::BlockFlow; use context::LayoutContext; use data::{HAS_NEWLY_CONSTRUCTED_FLOW, LayoutDataWrapper}; use floats::FloatKind; -use flow::{Descendants, AbsDescendants}; -use flow::{Flow, ImmutableFlowUtils, MutableFlowUtils, MutableOwnedFlowUtils}; -use flow::{IS_ABSOLUTELY_POSITIONED}; -use flow; +use flow::{self, AbsoluteDescendants, Flow, ImmutableFlowUtils, IS_ABSOLUTELY_POSITIONED}; +use flow::{MutableFlowUtils, MutableOwnedFlowUtils}; use flow_ref::FlowRef; use fragment::{Fragment, GeneratedContentInfo, IframeFragmentInfo}; use fragment::{CanvasFragmentInfo, ImageFragmentInfo, InlineAbsoluteFragmentInfo}; @@ -72,7 +70,7 @@ pub enum ConstructionResult { /// This node contributed a flow at the proper position in the tree. /// Nothing more needs to be done for this node. It has bubbled up fixed /// and absolute descendant flows that have a containing block above it. - Flow(FlowRef, AbsDescendants), + Flow(FlowRef, AbsoluteDescendants), /// This node contributed some object or objects that will be needed to construct a proper flow /// later up the tree, but these objects have not yet found their home. @@ -120,9 +118,6 @@ pub struct InlineFragmentsConstructionResult { /// Any fragments that succeed the {ib} splits. pub fragments: IntermediateInlineFragments, - - /// Any absolute descendants that we're bubbling up. - pub abs_descendants: AbsDescendants, } /// Represents an {ib} split that has not yet found the containing block that it belongs to. This @@ -167,14 +162,14 @@ pub struct IntermediateInlineFragments { pub fragments: LinkedList<Fragment>, /// The list of absolute descendants of those inline fragments. - pub absolute_descendants: AbsDescendants, + pub absolute_descendants: AbsoluteDescendants, } impl IntermediateInlineFragments { fn new() -> IntermediateInlineFragments { IntermediateInlineFragments { fragments: LinkedList::new(), - absolute_descendants: Descendants::new(), + absolute_descendants: AbsoluteDescendants::new(), } } @@ -424,6 +419,7 @@ impl<'a> FlowConstructor<'a> { fragment_accumulator: InlineFragmentsAccumulator, flow: &mut FlowRef, flow_list: &mut Vec<FlowRef>, + absolute_descendants: &mut AbsoluteDescendants, node: &ThreadSafeLayoutNode) { let mut fragments = fragment_accumulator.to_intermediate_inline_fragments(); if fragments.is_empty() { @@ -432,7 +428,8 @@ impl<'a> FlowConstructor<'a> { strip_ignorable_whitespace_from_start(&mut fragments.fragments); strip_ignorable_whitespace_from_end(&mut fragments.fragments); - if fragments.is_empty() { + if fragments.fragments.is_empty() { + absolute_descendants.push_descendants(fragments.absolute_descendants); return } @@ -469,14 +466,21 @@ impl<'a> FlowConstructor<'a> { } // Set up absolute descendants as necessary. - let contains_positioned_fragments = inline_flow_ref.contains_positioned_fragments(); - if contains_positioned_fragments { - // This is the containing block for all the absolute descendants. - inline_flow_ref.set_absolute_descendants(fragments.absolute_descendants); - } + // + // TODO(pcwalton): The inline flow itself may need to become the containing block for + // absolute descendants in order to handle cases like: + // + // <div> + // <span style="position: relative"> + // <span style="position: absolute; ..."></span> + // </span> + // </div> + // + // See the comment above `flow::AbsoluteDescendantInfo` for more information. + absolute_descendants.push_descendants(fragments.absolute_descendants); { - let inline_flow = inline_flow_ref.as_inline(); + let inline_flow = inline_flow_ref.as_mut_inline(); let (ascent, descent) = @@ -503,7 +507,7 @@ impl<'a> FlowConstructor<'a> { node: &ThreadSafeLayoutNode, kid: ThreadSafeLayoutNode, inline_fragment_accumulator: &mut InlineFragmentsAccumulator, - abs_descendants: &mut Descendants) { + abs_descendants: &mut AbsoluteDescendants) { match kid.swap_out_construction_result() { ConstructionResult::None => {} ConstructionResult::Flow(mut kid_flow, kid_abs_descendants) => { @@ -512,7 +516,7 @@ impl<'a> FlowConstructor<'a> { if flow.is_table() && kid_flow.is_table_caption() { self.set_flow_construction_result(&kid, ConstructionResult::Flow(kid_flow, - Descendants::new())) + AbsoluteDescendants::new())) } else if flow.need_anonymous_flow(&*kid_flow) { consecutive_siblings.push(kid_flow) } else { @@ -520,11 +524,14 @@ impl<'a> FlowConstructor<'a> { // handle {ib} splits. debug!("flushing {} inline box(es) to flow A", inline_fragment_accumulator.fragments.fragments.len()); - self.flush_inline_fragments_to_flow_or_list( + let old_inline_fragment_accumulator = mem::replace(inline_fragment_accumulator, - InlineFragmentsAccumulator::new()), + InlineFragmentsAccumulator::new()); + self.flush_inline_fragments_to_flow_or_list( + old_inline_fragment_accumulator, flow, consecutive_siblings, + abs_descendants, node); if !consecutive_siblings.is_empty() { let consecutive_siblings = mem::replace(consecutive_siblings, vec!()); @@ -539,10 +546,9 @@ impl<'a> FlowConstructor<'a> { InlineFragmentsConstructionResult { splits, fragments: successor_fragments, - abs_descendants: kid_abs_descendants, })) => { // Add any {ib} splits. - for split in splits.into_iter() { + for split in splits { // Pull apart the {ib} split object and push its predecessor fragments // onto the list. let InlineBlockSplit { @@ -554,11 +560,14 @@ impl<'a> FlowConstructor<'a> { // Flush any inline fragments that we were gathering up. debug!("flushing {} inline box(es) to flow A", inline_fragment_accumulator.fragments.fragments.len()); + let old_inline_fragment_accumulator = + mem::replace(inline_fragment_accumulator, + InlineFragmentsAccumulator::new()); self.flush_inline_fragments_to_flow_or_list( - mem::replace(inline_fragment_accumulator, - InlineFragmentsAccumulator::new()), + old_inline_fragment_accumulator, flow, consecutive_siblings, + &mut inline_fragment_accumulator.fragments.absolute_descendants, node); // Push the flow generated by the {ib} split onto our list of @@ -572,7 +581,6 @@ impl<'a> FlowConstructor<'a> { // Add the fragments to the list we're maintaining. inline_fragment_accumulator.push_all(successor_fragments); - abs_descendants.push_descendants(kid_abs_descendants); } ConstructionResult::ConstructionItem(ConstructionItem::Whitespace( whitespace_node, @@ -614,7 +622,7 @@ impl<'a> FlowConstructor<'a> { inline_fragment_accumulator.fragments.push_all(initial_fragments); // List of absolute descendants, in tree order. - let mut abs_descendants = Descendants::new(); + let mut abs_descendants = AbsoluteDescendants::new(); for kid in node.children() { if kid.get_pseudo_element_type() != PseudoElementType::Normal { self.process(&kid); @@ -634,6 +642,7 @@ impl<'a> FlowConstructor<'a> { self.flush_inline_fragments_to_flow_or_list(inline_fragment_accumulator, &mut flow, &mut consecutive_siblings, + &mut abs_descendants, node); if !consecutive_siblings.is_empty() { self.generate_anonymous_missing_child(consecutive_siblings, &mut flow, node); @@ -649,7 +658,7 @@ impl<'a> FlowConstructor<'a> { // This is the containing block for all the absolute descendants. flow.set_absolute_descendants(abs_descendants); - abs_descendants = Descendants::new(); + abs_descendants = AbsoluteDescendants::new(); if is_absolutely_positioned { // This is now the only absolute flow in the subtree which hasn't yet // reached its CB. @@ -713,7 +722,7 @@ impl<'a> FlowConstructor<'a> { let mut style = (*style).clone(); properties::modify_style_for_text(&mut style); - for content_item in text_content.into_iter() { + for content_item in text_content { let specific = match content_item { ContentItem::String(string) => { let info = UnscannedTextFragmentInfo::from_text(string); @@ -756,7 +765,7 @@ impl<'a> FlowConstructor<'a> { node: &ThreadSafeLayoutNode, fragment_accumulator: &mut InlineFragmentsAccumulator, opt_inline_block_splits: &mut LinkedList<InlineBlockSplit>) { - for split in splits.into_iter() { + for split in splits { let InlineBlockSplit { predecessors, flow: kid_flow @@ -784,7 +793,7 @@ impl<'a> FlowConstructor<'a> { let mut fragment_accumulator = InlineFragmentsAccumulator::from_inline_node(node); fragment_accumulator.bidi_control_chars = bidi_control_chars(&*node.style()); - let mut abs_descendants = Descendants::new(); + let mut abs_descendants = AbsoluteDescendants::new(); // Concatenate all the fragments of our kids, creating {ib} splits as necessary. for kid in node.children() { @@ -793,7 +802,7 @@ impl<'a> FlowConstructor<'a> { } match kid.swap_out_construction_result() { ConstructionResult::None => {} - ConstructionResult::Flow(mut flow, kid_abs_descendants) => { + ConstructionResult::Flow(flow, kid_abs_descendants) => { if !flow::base(&*flow).flags.contains(IS_ABSOLUTELY_POSITIONED) { // {ib} split. Flush the accumulator to our new split and make a new // accumulator to hold any subsequent fragments we come across. @@ -830,7 +839,6 @@ impl<'a> FlowConstructor<'a> { InlineFragmentsConstructionResult { splits, fragments: successors, - abs_descendants: kid_abs_descendants, })) => { // Bubble up {ib} splits. @@ -841,7 +849,6 @@ impl<'a> FlowConstructor<'a> { // Push residual fragments. fragment_accumulator.push_all(successors); - abs_descendants.push_descendants(kid_abs_descendants); } ConstructionResult::ConstructionItem(ConstructionItem::Whitespace( whitespace_node, @@ -869,11 +876,11 @@ impl<'a> FlowConstructor<'a> { // Finally, make a new construction result. if opt_inline_block_splits.len() > 0 || !fragment_accumulator.fragments.is_empty() || abs_descendants.len() > 0 { + fragment_accumulator.fragments.absolute_descendants.push_descendants(abs_descendants); let construction_item = ConstructionItem::InlineFragments( InlineFragmentsConstructionResult { splits: opt_inline_block_splits, fragments: fragment_accumulator.to_intermediate_inline_fragments(), - abs_descendants: abs_descendants, }); ConstructionResult::ConstructionItem(construction_item) } else { @@ -924,7 +931,6 @@ impl<'a> FlowConstructor<'a> { ConstructionItem::InlineFragments(InlineFragmentsConstructionResult { splits: LinkedList::new(), fragments: fragments, - abs_descendants: Descendants::new(), }); ConstructionResult::ConstructionItem(construction_item) } @@ -950,12 +956,12 @@ impl<'a> FlowConstructor<'a> { let mut fragment_accumulator = InlineFragmentsAccumulator::from_inline_node_and_style(node, modified_style); fragment_accumulator.fragments.fragments.push_back(fragment); + fragment_accumulator.fragments.absolute_descendants.push_descendants(abs_descendants); let construction_item = ConstructionItem::InlineFragments(InlineFragmentsConstructionResult { splits: LinkedList::new(), fragments: fragment_accumulator.to_intermediate_inline_fragments(), - abs_descendants: abs_descendants, }); ConstructionResult::ConstructionItem(construction_item) } @@ -976,12 +982,12 @@ impl<'a> FlowConstructor<'a> { let mut fragment_accumulator = InlineFragmentsAccumulator::from_inline_node(node); fragment_accumulator.fragments.fragments.push_back(fragment); + fragment_accumulator.fragments.absolute_descendants.push_descendants(abs_descendants); let construction_item = ConstructionItem::InlineFragments(InlineFragmentsConstructionResult { splits: LinkedList::new(), fragments: fragment_accumulator.to_intermediate_inline_fragments(), - abs_descendants: abs_descendants, }); ConstructionResult::ConstructionItem(construction_item) } @@ -1009,7 +1015,7 @@ impl<'a> FlowConstructor<'a> { // Only flows that are table captions are matched here. for kid in node.children() { match kid.swap_out_construction_result() { - ConstructionResult::Flow(mut kid_flow, _) => { + ConstructionResult::Flow(kid_flow, _) => { if kid_flow.is_table_caption() && kid_flow.as_block() .fragment @@ -1032,7 +1038,7 @@ impl<'a> FlowConstructor<'a> { node: &ThreadSafeLayoutNode) { let mut anonymous_flow = flow.generate_missing_child_flow(node); let mut consecutive_siblings = vec!(); - for kid_flow in child_flows.into_iter() { + for kid_flow in child_flows { if anonymous_flow.need_anonymous_flow(&*kid_flow) { consecutive_siblings.push(kid_flow); continue; @@ -1069,8 +1075,8 @@ impl<'a> FlowConstructor<'a> { // First populate the table flow with its children. let construction_result = self.build_flow_for_block_like(table_flow, node); - let mut abs_descendants = Descendants::new(); - let mut fixed_descendants = Descendants::new(); + let mut abs_descendants = AbsoluteDescendants::new(); + let mut fixed_descendants = AbsoluteDescendants::new(); // The order of the caption and the table are not necessarily the same order as in the DOM // tree. All caption blocks are placed before or after the table flow, depending on the @@ -1102,7 +1108,7 @@ impl<'a> FlowConstructor<'a> { // This is the containing block for all the absolute descendants. wrapper_flow.set_absolute_descendants(abs_descendants); - abs_descendants = Descendants::new(); + abs_descendants = AbsoluteDescendants::new(); if is_fixed_positioned { // Send itself along with the other fixed descendants. @@ -1267,7 +1273,7 @@ impl<'a> FlowConstructor<'a> { let mut flow = FlowRef::new(flow as Box<Flow>); flow.finish(); - ConstructionResult::Flow(flow, Descendants::new()) + ConstructionResult::Flow(flow, AbsoluteDescendants::new()) } /// Attempts to perform incremental repair to account for recent changes to this node. This diff --git a/components/layout/context.rs b/components/layout/context.rs index 96fdc31beac..cfb58ccb3d4 100644 --- a/components/layout/context.rs +++ b/components/layout/context.rs @@ -124,7 +124,7 @@ pub struct SharedLayoutContext { pub visible_rects: Arc<HashMap<LayerId, Rect<Au>, DefaultState<FnvHasher>>>, /// The animations that are currently running. - pub running_animations: Arc<HashMap<OpaqueNode,Vec<Animation>>>, + pub running_animations: Arc<HashMap<OpaqueNode, Vec<Animation>>>, /// Why is this reflow occurring pub goal: ReflowGoal, diff --git a/components/layout/css/matching.rs b/components/layout/css/matching.rs index 1392fea7067..c5a2d86b249 100644 --- a/components/layout/css/matching.rs +++ b/components/layout/css/matching.rs @@ -139,7 +139,7 @@ impl<'a> Hash for ApplicableDeclarationsCacheQuery<'a> { static APPLICABLE_DECLARATIONS_CACHE_SIZE: usize = 32; pub struct ApplicableDeclarationsCache { - cache: SimpleHashCache<ApplicableDeclarationsCacheEntry,Arc<ComputedValues>>, + cache: SimpleHashCache<ApplicableDeclarationsCacheEntry, Arc<ComputedValues>>, } impl ApplicableDeclarationsCache { diff --git a/components/layout/display_list_builder.rs b/components/layout/display_list_builder.rs index 06e6e004865..8710c519de0 100644 --- a/components/layout/display_list_builder.rs +++ b/components/layout/display_list_builder.rs @@ -45,10 +45,10 @@ use std::sync::Arc; use std::sync::mpsc::channel; use std::f32; use style::computed_values::filter::Filter; -use style::computed_values::{background_attachment, background_clip, background_origin, - background_repeat, background_size}; -use style::computed_values::{border_style, image_rendering, overflow_x, position, - visibility, transform, transform_style}; +use style::computed_values::{background_attachment, background_clip, background_origin}; +use style::computed_values::{background_repeat, background_size}; +use style::computed_values::{border_style, image_rendering, overflow_x, position}; +use style::computed_values::{visibility, transform, transform_style}; use style::properties::ComputedValues; use style::properties::style_structs::Border; use style::values::RGBA; @@ -1108,7 +1108,7 @@ impl FragmentDisplayListBuilding for Fragment { }, None => IpcSharedMemory::from_byte(0xFFu8, width * height * 4), }; - display_list.content.push_back(DisplayItem::ImageClass(box ImageDisplayItem{ + display_list.content.push_back(DisplayItem::ImageClass(box ImageDisplayItem { base: BaseDisplayItem::new(stacking_relative_content_box, DisplayItemMetadata::new(self.node, &*self.style, diff --git a/components/layout/flow.rs b/components/layout/flow.rs index d7dab549958..95866d04b5f 100644 --- a/components/layout/flow.rs +++ b/components/layout/flow.rs @@ -76,95 +76,97 @@ pub trait Flow: fmt::Debug + Sync { /// Returns the class of flow that this is. fn class(&self) -> FlowClass; - /// If this is a block flow, returns the underlying object, borrowed immutably. Fails - /// otherwise. - fn as_immutable_block<'a>(&'a self) -> &'a BlockFlow { - panic!("called as_immutable_block() on a non-block flow") - } - /// If this is a block flow, returns the underlying object. Fails otherwise. - fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow { - debug!("called as_block() on a flow of type {:?}", self.class()); + fn as_block<'a>(&'a self) -> &'a BlockFlow { panic!("called as_block() on a non-block flow") } - /// If this is an inline flow, returns the underlying object, borrowed immutably. Fails - /// otherwise. - fn as_immutable_inline<'a>(&'a self) -> &'a InlineFlow { - panic!("called as_immutable_inline() on a non-inline flow") + /// If this is a block flow, returns the underlying object, borrowed mutably. Fails otherwise. + fn as_mut_block<'a>(&'a mut self) -> &'a mut BlockFlow { + debug!("called as_mut_block() on a flow of type {:?}", self.class()); + panic!("called as_mut_block() on a non-block flow") } /// If this is an inline flow, returns the underlying object. Fails otherwise. - fn as_inline<'a>(&'a mut self) -> &'a mut InlineFlow { + fn as_inline<'a>(&'a self) -> &'a InlineFlow { panic!("called as_inline() on a non-inline flow") } + /// If this is an inline flow, returns the underlying object, borrowed mutably. Fails + /// otherwise. + fn as_mut_inline<'a>(&'a mut self) -> &'a mut InlineFlow { + panic!("called as_mut_inline() on a non-inline flow") + } + + /// If this is a table wrapper flow, returns the underlying object, borrowed mutably. Fails + /// otherwise. + fn as_mut_table_wrapper<'a>(&'a mut self) -> &'a mut TableWrapperFlow { + panic!("called as_mut_table_wrapper() on a non-tablewrapper flow") + } + /// If this is a table wrapper flow, returns the underlying object. Fails otherwise. - fn as_table_wrapper<'a>(&'a mut self) -> &'a mut TableWrapperFlow { + fn as_table_wrapper<'a>(&'a self) -> &'a TableWrapperFlow { panic!("called as_table_wrapper() on a non-tablewrapper flow") } - /// If this is a table wrapper flow, returns the underlying object, borrowed immutably. Fails - /// otherwise. - fn as_immutable_table_wrapper<'a>(&'a self) -> &'a TableWrapperFlow { - panic!("called as_immutable_table_wrapper() on a non-tablewrapper flow") + /// If this is a table flow, returns the underlying object, borrowed mutably. Fails otherwise. + fn as_mut_table<'a>(&'a mut self) -> &'a mut TableFlow { + panic!("called as_mut_table() on a non-table flow") } /// If this is a table flow, returns the underlying object. Fails otherwise. - fn as_table<'a>(&'a mut self) -> &'a mut TableFlow { + fn as_table<'a>(&'a self) -> &'a TableFlow { panic!("called as_table() on a non-table flow") } - /// If this is a table flow, returns the underlying object, borrowed immutably. Fails otherwise. - fn as_immutable_table<'a>(&'a self) -> &'a TableFlow { - panic!("called as_table() on a non-table flow") + /// If this is a table colgroup flow, returns the underlying object, borrowed mutably. Fails + /// otherwise. + fn as_mut_table_colgroup<'a>(&'a mut self) -> &'a mut TableColGroupFlow { + panic!("called as_mut_table_colgroup() on a non-tablecolgroup flow") } - /// If this is a table colgroup flow, returns the underlying object. Fails otherwise. - fn as_table_colgroup<'a>(&'a mut self) -> &'a mut TableColGroupFlow { - panic!("called as_table_colgroup() on a non-tablecolgroup flow") + /// If this is a table rowgroup flow, returns the underlying object, borrowed mutably. Fails + /// otherwise. + fn as_mut_table_rowgroup<'a>(&'a mut self) -> &'a mut TableRowGroupFlow { + panic!("called as_mut_table_rowgroup() on a non-tablerowgroup flow") } /// If this is a table rowgroup flow, returns the underlying object. Fails otherwise. - fn as_table_rowgroup<'a>(&'a mut self) -> &'a mut TableRowGroupFlow { + fn as_table_rowgroup<'a>(&'a self) -> &'a TableRowGroupFlow { panic!("called as_table_rowgroup() on a non-tablerowgroup flow") } - /// If this is a table rowgroup flow, returns the underlying object, borrowed immutably. Fails + /// If this is a table row flow, returns the underlying object, borrowed mutably. Fails /// otherwise. - fn as_immutable_table_rowgroup<'a>(&'a self) -> &'a TableRowGroupFlow { - panic!("called as_table_rowgroup() on a non-tablerowgroup flow") + fn as_mut_table_row<'a>(&'a mut self) -> &'a mut TableRowFlow { + panic!("called as_mut_table_row() on a non-tablerow flow") } /// If this is a table row flow, returns the underlying object. Fails otherwise. - fn as_table_row<'a>(&'a mut self) -> &'a mut TableRowFlow { + fn as_table_row<'a>(&'a self) -> &'a TableRowFlow { panic!("called as_table_row() on a non-tablerow flow") } - /// If this is a table row flow, returns the underlying object, borrowed immutably. Fails + /// If this is a table cell flow, returns the underlying object, borrowed mutably. Fails /// otherwise. - fn as_immutable_table_row<'a>(&'a self) -> &'a TableRowFlow { - panic!("called as_table_row() on a non-tablerow flow") + fn as_mut_table_caption<'a>(&'a mut self) -> &'a mut TableCaptionFlow { + panic!("called as_mut_table_caption() on a non-tablecaption flow") } - /// If this is a table cell flow, returns the underlying object. Fails otherwise. - fn as_table_caption<'a>(&'a mut self) -> &'a mut TableCaptionFlow { - panic!("called as_table_caption() on a non-tablecaption flow") - } - - /// If this is a table cell flow, returns the underlying object. Fails otherwise. - fn as_table_cell<'a>(&'a mut self) -> &'a mut TableCellFlow { - panic!("called as_table_cell() on a non-tablecell flow") + /// If this is a table cell flow, returns the underlying object, borrowed mutably. Fails + /// otherwise. + fn as_mut_table_cell<'a>(&'a mut self) -> &'a mut TableCellFlow { + panic!("called as_mut_table_cell() on a non-tablecell flow") } - /// If this is a multicol flow, returns the underlying object. Fails otherwise. - fn as_multicol<'a>(&'a mut self) -> &'a mut MulticolFlow { - panic!("called as_multicol() on a non-multicol flow") + /// If this is a multicol flow, returns the underlying object, borrowed mutably. Fails + /// otherwise. + fn as_mut_multicol<'a>(&'a mut self) -> &'a mut MulticolFlow { + panic!("called as_mut_multicol() on a non-multicol flow") } - /// If this is a table cell flow, returns the underlying object, borrowed immutably. Fails - /// otherwise. - fn as_immutable_table_cell<'a>(&'a self) -> &'a TableCellFlow { + /// If this is a table cell flow, returns the underlying object. Fails otherwise. + fn as_table_cell<'a>(&'a self) -> &'a TableCellFlow { panic!("called as_table_cell() on a non-tablecell flow") } @@ -244,7 +246,7 @@ pub trait Flow: fmt::Debug + Sync { match self.class() { FlowClass::Block | FlowClass::TableCaption | - FlowClass::TableCell if base(self).children.len() != 0 => { + FlowClass::TableCell if !base(self).children.is_empty() => { // FIXME(#2795): Get the real container size. let container_size = Size2D::zero(); for kid in mut_base(self).children.iter_mut() { @@ -468,10 +470,10 @@ pub trait MutableFlowUtils { // Traversals /// Traverses the tree in preorder. - fn traverse_preorder<T:PreorderFlowTraversal>(self, traversal: &T); + fn traverse_preorder<T: PreorderFlowTraversal>(self, traversal: &T); /// Traverses the tree in postorder. - fn traverse_postorder<T:PostorderFlowTraversal>(self, traversal: &T); + fn traverse_postorder<T: PostorderFlowTraversal>(self, traversal: &T); /// Traverse the Absolute flow tree in preorder. /// @@ -499,7 +501,7 @@ pub trait MutableOwnedFlowUtils { /// Set absolute descendants for this flow. /// /// Set this flow as the Containing Block for all the absolute descendants. - fn set_absolute_descendants(&mut self, abs_descendants: AbsDescendants); + fn set_absolute_descendants(&mut self, abs_descendants: AbsoluteDescendants); } #[derive(RustcEncodable, PartialEq, Debug)] @@ -694,19 +696,17 @@ impl FlowFlags { } } -/// The Descendants of a flow. -/// -/// Also, details about their position wrt this flow. +/// Absolutely-positioned descendants of this flow. #[derive(Clone)] -pub struct Descendants { +pub struct AbsoluteDescendants { /// Links to every descendant. This must be private because it is unsafe to leak `FlowRef`s to /// layout. - descendant_links: Vec<FlowRef>, + descendant_links: Vec<AbsoluteDescendantInfo>, } -impl Descendants { - pub fn new() -> Descendants { - Descendants { +impl AbsoluteDescendants { + pub fn new() -> AbsoluteDescendants { + AbsoluteDescendants { descendant_links: Vec::new(), } } @@ -720,40 +720,63 @@ impl Descendants { } pub fn push(&mut self, given_descendant: FlowRef) { - self.descendant_links.push(given_descendant); + self.descendant_links.push(AbsoluteDescendantInfo { + flow: given_descendant, + }); } /// Push the given descendants on to the existing descendants. /// /// Ignore any static y offsets, because they are None before layout. - pub fn push_descendants(&mut self, given_descendants: Descendants) { - for elem in given_descendants.descendant_links.into_iter() { + pub fn push_descendants(&mut self, given_descendants: AbsoluteDescendants) { + for elem in given_descendants.descendant_links { self.descendant_links.push(elem); } } /// Return an iterator over the descendant flows. - pub fn iter<'a>(&'a mut self) -> DescendantIter<'a> { - DescendantIter { + pub fn iter<'a>(&'a mut self) -> AbsoluteDescendantIter<'a> { + AbsoluteDescendantIter { iter: self.descendant_links.iter_mut(), } } } -pub type AbsDescendants = Descendants; +/// TODO(pcwalton): This structure is going to need a flag to record whether the absolute +/// descendants have reached their containing block yet. The reason is so that we can handle cases +/// like the following: +/// +/// <div> +/// <span id=a style="position: absolute; ...">foo</span> +/// <span style="position: relative"> +/// <span id=b style="position: absolute; ...">bar</span> +/// </span> +/// </div> +/// +/// When we go to create the `InlineFlow` for the outer `div`, our absolute descendants will +/// be `a` and `b`. At this point, we need a way to distinguish between the two, because the +/// containing block for `a` will be different from the containing block for `b`. Specifically, +/// the latter's containing block is the inline flow itself, while the former's containing +/// block is going to be some parent of the outer `div`. Hence we need this flag as a way to +/// distinguish the two; it will be false for `a` and true for `b`. +#[derive(Clone)] +pub struct AbsoluteDescendantInfo { + /// The absolute descendant flow in question. + flow: FlowRef, +} -pub struct DescendantIter<'a> { - iter: IterMut<'a, FlowRef>, +pub struct AbsoluteDescendantIter<'a> { + iter: IterMut<'a, AbsoluteDescendantInfo>, } -impl<'a> Iterator for DescendantIter<'a> { +impl<'a> Iterator for AbsoluteDescendantIter<'a> { type Item = &'a mut (Flow + 'a); fn next(&mut self) -> Option<&'a mut (Flow + 'a)> { - self.iter.next().map(|flow| &mut **flow) + self.iter.next().map(|info| &mut *info.flow) } } -pub type DescendantOffsetIter<'a> = Zip<DescendantIter<'a>, IterMut<'a, Au>>; +pub type AbsoluteDescendantOffsetIter<'a> = Zip<AbsoluteDescendantIter<'a>, IterMut<'a, Au>>; /// Information needed to compute absolute (i.e. viewport-relative) flow positions (not to be /// confused with absolutely-positioned flows). @@ -837,7 +860,7 @@ pub struct BaseFlow { /// Details about descendants with position 'absolute' or 'fixed' for which we are the /// containing block. This is in tree order. This includes any direct children. - pub abs_descendants: AbsDescendants, + pub abs_descendants: AbsoluteDescendants, /// The inline-size of the block container of this flow. Used for computing percentage and /// automatic values for `width`. @@ -917,21 +940,13 @@ impl Encodable for BaseFlow { try!(e.emit_struct_field("class", 0, |e| c.class().encode(e))); e.emit_struct_field("data", 1, |e| { match c.class() { - FlowClass::Block => c.as_immutable_block().encode(e), - FlowClass::Inline => c.as_immutable_inline().encode(e), - FlowClass::Table => c.as_immutable_table().encode(e), - FlowClass::TableWrapper => { - c.as_immutable_table_wrapper().encode(e) - } - FlowClass::TableRowGroup => { - c.as_immutable_table_rowgroup().encode(e) - } - FlowClass::TableRow => { - c.as_immutable_table_row().encode(e) - } - FlowClass::TableCell => { - c.as_immutable_table_cell().encode(e) - } + FlowClass::Block => c.as_block().encode(e), + FlowClass::Inline => c.as_inline().encode(e), + FlowClass::Table => c.as_table().encode(e), + FlowClass::TableWrapper => c.as_table_wrapper().encode(e), + FlowClass::TableRowGroup => c.as_table_rowgroup().encode(e), + FlowClass::TableRow => c.as_table_row().encode(e), + FlowClass::TableCell => c.as_table_cell().encode(e), _ => { Ok(()) } // TODO: Support captions } }) @@ -1034,7 +1049,7 @@ impl BaseFlow { floats: Floats::new(writing_mode), collapsible_margins: CollapsibleMargins::new(), stacking_relative_position: Point2D::zero(), - abs_descendants: Descendants::new(), + abs_descendants: AbsoluteDescendants::new(), block_container_inline_size: Au(0), block_container_writing_mode: writing_mode, block_container_explicit_block_size: None, @@ -1301,7 +1316,7 @@ impl<'a> ImmutableFlowUtils for &'a (Flow + 'a) { impl<'a> MutableFlowUtils for &'a mut (Flow + 'a) { /// Traverses the tree in preorder. - fn traverse_preorder<T:PreorderFlowTraversal>(self, traversal: &T) { + fn traverse_preorder<T: PreorderFlowTraversal>(self, traversal: &T) { if traversal.should_process(self) { traversal.process(self); } @@ -1312,7 +1327,7 @@ impl<'a> MutableFlowUtils for &'a mut (Flow + 'a) { } /// Traverses the tree in postorder. - fn traverse_postorder<T:PostorderFlowTraversal>(self, traversal: &T) { + fn traverse_postorder<T: PostorderFlowTraversal>(self, traversal: &T) { for kid in child_iter(self) { kid.traverse_postorder(traversal); } @@ -1367,7 +1382,7 @@ impl MutableOwnedFlowUtils for FlowRef { /// This is called during flow construction, so nothing else can be accessing the descendant /// flows. This is enforced by the fact that we have a mutable `FlowRef`, which only flow /// construction is allowed to possess. - fn set_absolute_descendants(&mut self, abs_descendants: AbsDescendants) { + fn set_absolute_descendants(&mut self, abs_descendants: AbsoluteDescendants) { let this = self.clone(); let base = mut_base(&mut **self); base.abs_descendants = abs_descendants; @@ -1414,7 +1429,10 @@ impl ContainingBlockLink { panic!("Link to containing block not established; perhaps you forgot to call \ `set_absolute_descendants`?") } - Some(ref link) => link.upgrade().unwrap().generated_containing_block_size(for_flow), + Some(ref link) => { + let flow = link.upgrade().unwrap(); + flow.generated_containing_block_size(for_flow) + } } } @@ -1428,7 +1446,9 @@ impl ContainingBlockLink { Some(ref link) => { let flow = link.upgrade().unwrap(); if flow.is_block_like() { - flow.as_immutable_block().explicit_block_containing_size(layout_context) + flow.as_block().explicit_block_containing_size(layout_context) + } else if flow.is_inline_flow() { + Some(flow.as_inline().minimum_block_size_above_baseline) } else { None } @@ -1446,7 +1466,7 @@ impl OpaqueFlow { #[allow(unsafe_code)] pub fn from_flow(flow: &Flow) -> OpaqueFlow { unsafe { - let object = mem::transmute::<&Flow,raw::TraitObject>(flow); + let object = mem::transmute::<&Flow, raw::TraitObject>(flow); OpaqueFlow(object.data as usize) } } diff --git a/components/layout/fragment.rs b/components/layout/fragment.rs index a512db3670c..568ebf50657 100644 --- a/components/layout/fragment.rs +++ b/components/layout/fragment.rs @@ -1446,7 +1446,7 @@ impl Fragment { /// A helper method that uses the breaking strategy described by `slice_iterator` (at present, /// either natural word breaking or character breaking) to split this fragment. - fn calculate_split_position_using_breaking_strategy<'a,I>( + fn calculate_split_position_using_breaking_strategy<'a, I>( &self, slice_iterator: I, max_inline_size: Au, @@ -1637,7 +1637,7 @@ impl Fragment { match self.specific { SpecificFragmentInfo::InlineAbsoluteHypothetical(ref mut info) => { - let block_flow = info.flow_ref.as_block(); + let block_flow = info.flow_ref.as_mut_block(); block_flow.base.position.size.inline = block_flow.base.intrinsic_inline_sizes.preferred_inline_size; @@ -1645,7 +1645,7 @@ impl Fragment { self.border_box.size.inline = Au(0); } SpecificFragmentInfo::InlineBlock(ref mut info) => { - let block_flow = info.flow_ref.as_block(); + let block_flow = info.flow_ref.as_mut_block(); self.border_box.size.inline = max(block_flow.base.intrinsic_inline_sizes.minimum_inline_size, block_flow.base.intrinsic_inline_sizes.preferred_inline_size); @@ -1653,7 +1653,7 @@ impl Fragment { block_flow.base.block_container_writing_mode = self.style.writing_mode; } SpecificFragmentInfo::InlineAbsolute(ref mut info) => { - let block_flow = info.flow_ref.as_block(); + let block_flow = info.flow_ref.as_mut_block(); self.border_box.size.inline = max(block_flow.base.intrinsic_inline_sizes.minimum_inline_size, block_flow.base.intrinsic_inline_sizes.preferred_inline_size); @@ -1810,7 +1810,7 @@ impl Fragment { } SpecificFragmentInfo::InlineBlock(ref info) => { // See CSS 2.1 § 10.8.1. - let block_flow = info.flow_ref.as_immutable_block(); + let block_flow = info.flow_ref.as_block(); let font_style = self.style.get_font_arc(); let font_metrics = text::font_metrics_for_style(&mut layout_context.font_context(), font_style); @@ -2234,6 +2234,22 @@ impl Fragment { pub fn margin_box_inline_size(&self) -> Au { self.border_box.size.inline + self.margin.inline_start_end() } + + /// Returns true if this node *or any of the nodes within its inline fragment context* have + /// non-`static` `position`. + pub fn is_positioned(&self) -> bool { + if self.style.get_box().position != position::T::static_ { + return true + } + if let Some(ref inline_context) = self.inline_context { + for node in inline_context.nodes.iter() { + if node.style.get_box().position != position::T::static_ { + return true + } + } + } + false + } } impl fmt::Debug for Fragment { diff --git a/components/layout/generated_content.rs b/components/layout/generated_content.rs index 639fa1e3cc6..3b65afdbfdd 100644 --- a/components/layout/generated_content.rs +++ b/components/layout/generated_content.rs @@ -101,7 +101,7 @@ pub struct ResolveGeneratedContent<'a> { /// The counter representing an ordered list item. list_item: Counter, /// Named CSS counters. - counters: HashMap<String,Counter>, + counters: HashMap<String, Counter>, /// The level of quote nesting. quote: u32, } @@ -277,11 +277,10 @@ impl<'a,'b> ResolveGeneratedContentFragmentMutator<'a,'b> { self.traversal.counters.insert((*counter_name).clone(), counter); } - for &(ref counter_name, value) in fragment.style() + for &(ref counter_name, value) in &fragment.style() .get_counters() .counter_increment - .0 - .iter() { + .0 { if let Some(ref mut counter) = self.traversal.counters.get_mut(counter_name) { counter.increment(self.level, value); continue diff --git a/components/layout/inline.rs b/components/layout/inline.rs index 89c71958289..d06489ea3bd 100644 --- a/components/layout/inline.rs +++ b/components/layout/inline.rs @@ -309,11 +309,11 @@ impl LineBreaker { } /// Reflows the given fragments, which have been plucked out of the inline flow. - fn reflow_fragments<'a,I>(&mut self, - mut old_fragment_iter: I, - flow: &'a InlineFlow, - layout_context: &LayoutContext) - where I: Iterator<Item=Fragment> { + fn reflow_fragments<'a, I>(&mut self, + mut old_fragment_iter: I, + flow: &'a InlineFlow, + layout_context: &LayoutContext) + where I: Iterator<Item=Fragment> { loop { // Acquire the next fragment to lay out from the work list or fragment list, as // appropriate. @@ -1121,7 +1121,7 @@ impl InlineFlow { let run = Arc::make_unique(&mut scanned_text_fragment_info.run); { let glyph_runs = Arc::make_unique(&mut run.glyphs); - for mut glyph_run in glyph_runs.iter_mut() { + for mut glyph_run in &mut *glyph_runs { let mut range = glyph_run.range.intersect(&fragment_range); if range.is_empty() { continue @@ -1226,7 +1226,7 @@ impl InlineFlow { for frag in &self.fragments.fragments { match frag.inline_context { Some(ref inline_context) => { - for node in inline_context.nodes.iter() { + for node in &inline_context.nodes { let font_style = node.style.get_font_arc(); let font_metrics = text::font_metrics_for_style(font_context, font_style); let line_height = text::line_height_from_style(&*node.style, &font_metrics); @@ -1262,19 +1262,13 @@ impl InlineFlow { while start_index > FragmentIndex(0) && self.fragments .fragments[(start_index - FragmentIndex(1)).get() as usize] - .style - .get_box() - .position == position::T::static_ { + .is_positioned() { start_index = start_index - FragmentIndex(1) } let mut end_index = fragment_index + FragmentIndex(1); while end_index < FragmentIndex(self.fragments.fragments.len() as isize) && - self.fragments - .fragments[end_index.get() as usize] - .style - .get_box() - .position == position::T::static_ { + self.fragments.fragments[end_index.get() as usize].is_positioned() { end_index = end_index + FragmentIndex(1) } @@ -1287,6 +1281,10 @@ impl InlineFlow { SpecificFragmentInfo::InlineAbsolute(ref inline_absolute) => { OpaqueFlow::from_flow(&*inline_absolute.flow_ref) == opaque_flow } + SpecificFragmentInfo::InlineAbsoluteHypothetical( + ref inline_absolute_hypothetical) => { + OpaqueFlow::from_flow(&*inline_absolute_hypothetical.flow_ref) == opaque_flow + } _ => false, } }).expect("containing_block_range_for_flow(): couldn't find inline absolute fragment!") @@ -1300,11 +1298,11 @@ impl Flow for InlineFlow { FlowClass::Inline } - fn as_immutable_inline<'a>(&'a self) -> &'a InlineFlow { + fn as_inline<'a>(&'a self) -> &'a InlineFlow { self } - fn as_inline<'a>(&'a mut self) -> &'a mut InlineFlow { + fn as_mut_inline<'a>(&'a mut self) -> &'a mut InlineFlow { self } @@ -1600,20 +1598,43 @@ impl Flow for InlineFlow { fn compute_absolute_position(&mut self, _: &LayoutContext) { // First, gather up the positions of all the containing blocks (if any). + // + // FIXME(pcwalton): This will get the absolute containing blocks inside `...` wrong in the + // case of something like: + // + // <span style="position: relative"> + // Foo + // <span style="display: inline-block">...</span> + // </span> let mut containing_block_positions = Vec::new(); let container_size = Size2D::new(self.base.block_container_inline_size, Au(0)); for (fragment_index, fragment) in self.fragments.fragments.iter().enumerate() { - if let SpecificFragmentInfo::InlineAbsolute(_) = fragment.specific { - let containing_block_range = - self.containing_block_range_for_flow_surrounding_fragment_at_index( - FragmentIndex(fragment_index as isize)); - let first_fragment_index = containing_block_range.begin().get() as usize; - 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; - containing_block_positions.push( - padding_box_origin.to_physical(self.base.writing_mode, container_size)); + match fragment.specific { + SpecificFragmentInfo::InlineAbsolute(_) => { + let containing_block_range = + self.containing_block_range_for_flow_surrounding_fragment_at_index( + FragmentIndex(fragment_index as isize)); + let first_fragment_index = containing_block_range.begin().get() as usize; + 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; + containing_block_positions.push( + padding_box_origin.to_physical(self.base.writing_mode, container_size)); + } + SpecificFragmentInfo::InlineBlock(_) if fragment.is_positioned() => { + let containing_block_range = + self.containing_block_range_for_flow_surrounding_fragment_at_index( + FragmentIndex(fragment_index as isize)); + let first_fragment_index = containing_block_range.begin().get() as usize; + 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; + containing_block_positions.push( + padding_box_origin.to_physical(self.base.writing_mode, container_size)); + } + _ => {} } } @@ -1632,12 +1653,23 @@ impl Flow for InlineFlow { let clip = fragment.clipping_region_for_children(&self.base.clip, &stacking_relative_border_box, false); + let is_positioned = fragment.is_positioned(); match fragment.specific { SpecificFragmentInfo::InlineBlock(ref mut info) => { flow::mut_base(&mut *info.flow_ref).clip = clip; - let block_flow = info.flow_ref.as_block(); + let block_flow = info.flow_ref.as_mut_block(); block_flow.base.absolute_position_info = self.base.absolute_position_info; + + let stacking_relative_position = self.base.stacking_relative_position; + if is_positioned { + let padding_box_origin = containing_block_positions.next().unwrap(); + block_flow.base + .absolute_position_info + .stacking_relative_position_of_absolute_containing_block = + stacking_relative_position + *padding_box_origin; + } + block_flow.base.stacking_relative_position = stacking_relative_border_box.origin; block_flow.base.stacking_relative_position_of_display_port = @@ -1645,18 +1677,19 @@ impl Flow for InlineFlow { } SpecificFragmentInfo::InlineAbsoluteHypothetical(ref mut info) => { flow::mut_base(&mut *info.flow_ref).clip = clip; - let block_flow = info.flow_ref.as_block(); + + let block_flow = info.flow_ref.as_mut_block(); block_flow.base.absolute_position_info = self.base.absolute_position_info; + block_flow.base.stacking_relative_position = stacking_relative_border_box.origin; block_flow.base.stacking_relative_position_of_display_port = self.base.stacking_relative_position_of_display_port; - } SpecificFragmentInfo::InlineAbsolute(ref mut info) => { flow::mut_base(&mut *info.flow_ref).clip = clip; - let block_flow = info.flow_ref.as_block(); + let block_flow = info.flow_ref.as_mut_block(); block_flow.base.absolute_position_info = self.base.absolute_position_info; let stacking_relative_position = self.base.stacking_relative_position; diff --git a/components/layout/layout_task.rs b/components/layout/layout_task.rs index 6028c8c3b6a..4c982ec9661 100644 --- a/components/layout/layout_task.rs +++ b/components/layout/layout_task.rs @@ -139,7 +139,7 @@ pub struct LayoutTaskData { pub offset_parent_response: OffsetParentResponse, /// The list of currently-running animations. - pub running_animations: Arc<HashMap<OpaqueNode,Vec<Animation>>>, + pub running_animations: Arc<HashMap<OpaqueNode, Vec<Animation>>>, /// Receives newly-discovered animations. pub new_animations_receiver: Receiver<Animation>, @@ -708,7 +708,7 @@ impl LayoutTask { url: Url, mq: MediaQueryList, pending: PendingAsyncLoad, - responder: Box<StylesheetLoadResponder+Send>, + responder: Box<StylesheetLoadResponder + Send>, possibly_locked_rw_data: &mut Option<MutexGuard<'a, LayoutTaskData>>) { // TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding @@ -1541,7 +1541,7 @@ fn get_root_flow_background_color(flow: &mut Flow) -> AzColor { return color::transparent() } - let block_flow = flow.as_block(); + let block_flow = flow.as_mut_block(); let kid = match block_flow.base.children.iter_mut().next() { None => return color::transparent(), Some(kid) => kid, diff --git a/components/layout/list_item.rs b/components/layout/list_item.rs index c449406f448..a81f1f2e623 100644 --- a/components/layout/list_item.rs +++ b/components/layout/list_item.rs @@ -68,11 +68,11 @@ impl Flow for ListItemFlow { FlowClass::ListItem } - fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow { + fn as_mut_block<'a>(&'a mut self) -> &'a mut BlockFlow { &mut self.block_flow } - fn as_immutable_block<'a>(&'a self) -> &'a BlockFlow { + fn as_block<'a>(&'a self) -> &'a BlockFlow { &self.block_flow } @@ -228,4 +228,3 @@ impl ListStyleTypeContent { } } } - diff --git a/components/layout/multicol.rs b/components/layout/multicol.rs index 438b8b18830..784df3d0ba7 100644 --- a/components/layout/multicol.rs +++ b/components/layout/multicol.rs @@ -36,15 +36,15 @@ impl Flow for MulticolFlow { FlowClass::Multicol } - fn as_multicol<'a>(&'a mut self) -> &'a mut MulticolFlow { + fn as_mut_multicol<'a>(&'a mut self) -> &'a mut MulticolFlow { self } - fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow { + fn as_mut_block<'a>(&'a mut self) -> &'a mut BlockFlow { &mut self.block_flow } - fn as_immutable_block<'a>(&'a self) -> &'a BlockFlow { + fn as_block<'a>(&'a self) -> &'a BlockFlow { &self.block_flow } diff --git a/components/layout/parallel.rs b/components/layout/parallel.rs index ad0517b6d1b..c936dd00a16 100644 --- a/components/layout/parallel.rs +++ b/components/layout/parallel.rs @@ -89,14 +89,14 @@ pub type UnsafeFlowList = (Box<Vec<UnsafeLayoutNode>>, usize); pub type ChunkedDomTraversalFunction = extern "Rust" fn(UnsafeLayoutNodeList, - &mut WorkerProxy<SharedLayoutContext,UnsafeLayoutNodeList>); + &mut WorkerProxy<SharedLayoutContext, UnsafeLayoutNodeList>); pub type DomTraversalFunction = extern "Rust" fn(UnsafeLayoutNode, - &mut WorkerProxy<SharedLayoutContext,UnsafeLayoutNodeList>); + &mut WorkerProxy<SharedLayoutContext, UnsafeLayoutNodeList>); pub type ChunkedFlowTraversalFunction = - extern "Rust" fn(UnsafeFlowList, &mut WorkerProxy<SharedLayoutContext,UnsafeFlowList>); + extern "Rust" fn(UnsafeFlowList, &mut WorkerProxy<SharedLayoutContext, UnsafeFlowList>); pub type FlowTraversalFunction = extern "Rust" fn(UnsafeFlow, &SharedLayoutContext); @@ -104,17 +104,17 @@ pub type FlowTraversalFunction = extern "Rust" fn(UnsafeFlow, &SharedLayoutConte pub trait ParallelPreorderDomTraversal : PreorderDomTraversal { fn run_parallel(&self, nodes: UnsafeLayoutNodeList, - proxy: &mut WorkerProxy<SharedLayoutContext,UnsafeLayoutNodeList>); + proxy: &mut WorkerProxy<SharedLayoutContext, UnsafeLayoutNodeList>); #[inline(always)] fn run_parallel_helper( &self, unsafe_nodes: UnsafeLayoutNodeList, - proxy: &mut WorkerProxy<SharedLayoutContext,UnsafeLayoutNodeList>, + proxy: &mut WorkerProxy<SharedLayoutContext, UnsafeLayoutNodeList>, top_down_func: ChunkedDomTraversalFunction, bottom_up_func: DomTraversalFunction) { let mut discovered_child_nodes = Vec::new(); - for unsafe_node in unsafe_nodes.0.into_iter() { + for unsafe_node in *unsafe_nodes.0 { // Get a real layout node. let node: LayoutNode = unsafe { layout_node_from_unsafe_layout_node(&unsafe_node) @@ -168,7 +168,7 @@ trait ParallelPostorderDomTraversal : PostorderDomTraversal { /// fetch-and-subtract the parent's children count. fn run_parallel(&self, mut unsafe_node: UnsafeLayoutNode, - proxy: &mut WorkerProxy<SharedLayoutContext,UnsafeLayoutNodeList>) { + proxy: &mut WorkerProxy<SharedLayoutContext, UnsafeLayoutNodeList>) { loop { // Get a real layout node. let node: LayoutNode = unsafe { @@ -284,18 +284,18 @@ trait ParallelPostorderFlowTraversal : PostorderFlowTraversal { trait ParallelPreorderFlowTraversal : PreorderFlowTraversal { fn run_parallel(&self, unsafe_flows: UnsafeFlowList, - proxy: &mut WorkerProxy<SharedLayoutContext,UnsafeFlowList>); + proxy: &mut WorkerProxy<SharedLayoutContext, UnsafeFlowList>); fn should_record_thread_ids(&self) -> bool; #[inline(always)] fn run_parallel_helper(&self, unsafe_flows: UnsafeFlowList, - proxy: &mut WorkerProxy<SharedLayoutContext,UnsafeFlowList>, + proxy: &mut WorkerProxy<SharedLayoutContext, UnsafeFlowList>, top_down_func: ChunkedFlowTraversalFunction, bottom_up_func: FlowTraversalFunction) { let mut discovered_child_flows = Vec::new(); - for mut unsafe_flow in unsafe_flows.0.into_iter() { + for mut unsafe_flow in *unsafe_flows.0 { let mut had_children = false; unsafe { // Get a real flow. @@ -335,7 +335,7 @@ trait ParallelPreorderFlowTraversal : PreorderFlowTraversal { impl<'a> ParallelPreorderFlowTraversal for AssignISizes<'a> { fn run_parallel(&self, unsafe_flows: UnsafeFlowList, - proxy: &mut WorkerProxy<SharedLayoutContext,UnsafeFlowList>) { + proxy: &mut WorkerProxy<SharedLayoutContext, UnsafeFlowList>) { self.run_parallel_helper(unsafe_flows, proxy, assign_inline_sizes, @@ -397,7 +397,7 @@ fn construct_flows(unsafe_node: UnsafeLayoutNode, } fn assign_inline_sizes(unsafe_flows: UnsafeFlowList, - proxy: &mut WorkerProxy<SharedLayoutContext,UnsafeFlowList>) { + proxy: &mut WorkerProxy<SharedLayoutContext, UnsafeFlowList>) { let shared_layout_context = proxy.user_data(); let layout_context = LayoutContext::new(shared_layout_context); let assign_inline_sizes_traversal = AssignISizes { @@ -438,12 +438,12 @@ fn build_display_list(unsafe_flow: UnsafeFlow, build_display_list_traversal.run_parallel(unsafe_flow); } -fn run_queue_with_custom_work_data_type<To,F>( +fn run_queue_with_custom_work_data_type<To, F>( queue: &mut WorkQueue<SharedLayoutContext, WorkQueueData>, callback: F, shared_layout_context: &SharedLayoutContext) - where To: 'static + Send, F: FnOnce(&mut WorkQueue<SharedLayoutContext,To>) { - let queue: &mut WorkQueue<SharedLayoutContext,To> = unsafe { + where To: 'static + Send, F: FnOnce(&mut WorkQueue<SharedLayoutContext, To>) { + let queue: &mut WorkQueue<SharedLayoutContext, To> = unsafe { mem::transmute(queue) }; callback(queue); diff --git a/components/layout/sequential.rs b/components/layout/sequential.rs index 6f806f69bf8..573d35a7b67 100644 --- a/components/layout/sequential.rs +++ b/components/layout/sequential.rs @@ -137,7 +137,7 @@ pub fn iterate_through_flow_tree_fragment_border_boxes(root: &mut FlowRef, }; // FIXME(#2795): Get the real container size. - doit(kid, level+1, iterator, &stacking_context_position); + doit(kid, level + 1, iterator, &stacking_context_position); } } diff --git a/components/layout/table.rs b/components/layout/table.rs index c3c63b85762..4b1a0ceda20 100644 --- a/components/layout/table.rs +++ b/components/layout/table.rs @@ -191,19 +191,19 @@ impl Flow for TableFlow { FlowClass::Table } - fn as_table<'a>(&'a mut self) -> &'a mut TableFlow { + fn as_mut_table<'a>(&'a mut self) -> &'a mut TableFlow { self } - fn as_immutable_table<'a>(&'a self) -> &'a TableFlow { + fn as_table<'a>(&'a self) -> &'a TableFlow { self } - fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow { + fn as_mut_block<'a>(&'a mut self) -> &'a mut BlockFlow { &mut self.block_flow } - fn as_immutable_block(&self) -> &BlockFlow { + fn as_block(&self) -> &BlockFlow { &self.block_flow } @@ -262,34 +262,8 @@ impl Flow for TableFlow { { let mut iterator = self.block_flow.base.child_iter().peekable(); while let Some(kid) = iterator.next() { - let next_index_and_sibling = iterator.peek(); - let next_collapsed_borders_in_block_direction = if collapsing_borders { - match next_index_and_sibling { - Some(next_sibling) => { - if next_sibling.is_table_rowgroup() { - NextBlockCollapsedBorders::FromNextRow( - &next_sibling.as_immutable_table_rowgroup() - .preliminary_collapsed_borders - .block_start) - } else { - NextBlockCollapsedBorders::FromNextRow( - &next_sibling.as_immutable_table_row() - .preliminary_collapsed_borders - .block_start) - } - } - None => { - NextBlockCollapsedBorders::FromTable( - CollapsedBorder::block_end(&*self.block_flow.fragment.style, - CollapsedBorderProvenance::FromTable)) - } - } - } else { - NextBlockCollapsedBorders::NotCollapsingBorders - }; - if kid.is_table_colgroup() { - for specified_inline_size in &kid.as_table_colgroup().inline_sizes { + for specified_inline_size in &kid.as_mut_table_colgroup().inline_sizes { self.column_intrinsic_inline_sizes.push(ColumnIntrinsicInlineSize { minimum_length: match *specified_inline_size { LengthOrPercentageOrAuto::Auto | @@ -313,8 +287,30 @@ impl Flow for TableFlow { first_row, self.table_layout); if collapsing_borders { + let next_index_and_sibling = iterator.peek(); + let next_collapsed_borders_in_block_direction = + match next_index_and_sibling { + Some(next_sibling) => { + if next_sibling.is_table_rowgroup() { + NextBlockCollapsedBorders::FromNextRow( + &next_sibling.as_table_rowgroup() + .preliminary_collapsed_borders + .block_start) + } else { + NextBlockCollapsedBorders::FromNextRow( + &next_sibling.as_table_row() + .preliminary_collapsed_borders + .block_start) + } + } + None => { + NextBlockCollapsedBorders::FromTable( + CollapsedBorder::block_end(&*self.block_flow.fragment.style, + CollapsedBorderProvenance::FromTable)) + } + }; perform_border_collapse_for_row( - kid.as_table_row(), + kid.as_mut_table_row(), table_inline_collapsed_borders.as_ref().unwrap(), previous_collapsed_block_end_borders, next_collapsed_borders_in_block_direction, @@ -334,12 +330,12 @@ impl Flow for TableFlow { Some(grandkid_next_sibling) => { if grandkid_next_sibling.is_table_rowgroup() { NextBlockCollapsedBorders::FromNextRow( - &grandkid_next_sibling.as_immutable_table_rowgroup() + &grandkid_next_sibling.as_table_rowgroup() .preliminary_collapsed_borders .block_start) } else { NextBlockCollapsedBorders::FromNextRow( - &grandkid_next_sibling.as_immutable_table_row() + &grandkid_next_sibling.as_table_row() .preliminary_collapsed_borders .block_start) } @@ -363,7 +359,7 @@ impl Flow for TableFlow { self.table_layout); if collapsing_borders { perform_border_collapse_for_row( - grandkid.as_table_row(), + grandkid.as_mut_table_row(), table_inline_collapsed_borders.as_ref().unwrap(), previous_collapsed_block_end_borders, next_collapsed_borders_in_block_direction, @@ -484,12 +480,12 @@ impl Flow for TableFlow { column_computed_inline_sizes, &spacing_per_cell); if child_flow.is_table_row() { - let child_table_row = child_flow.as_table_row(); + let child_table_row = child_flow.as_mut_table_row(); child_table_row.populate_collapsed_border_spacing( collapsed_inline_direction_border_widths_for_table, &mut collapsed_block_direction_border_widths_for_table); } else if child_flow.is_table_rowgroup() { - let child_table_rowgroup = child_flow.as_table_rowgroup(); + let child_table_rowgroup = child_flow.as_mut_table_rowgroup(); child_table_rowgroup.populate_collapsed_border_spacing( collapsed_inline_direction_border_widths_for_table, &mut collapsed_block_direction_border_widths_for_table); diff --git a/components/layout/table_caption.rs b/components/layout/table_caption.rs index 24cc912af66..5cd35f5be99 100644 --- a/components/layout/table_caption.rs +++ b/components/layout/table_caption.rs @@ -36,15 +36,15 @@ impl Flow for TableCaptionFlow { FlowClass::TableCaption } - fn as_table_caption<'a>(&'a mut self) -> &'a mut TableCaptionFlow { + fn as_mut_table_caption<'a>(&'a mut self) -> &'a mut TableCaptionFlow { self } - fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow { + fn as_mut_block<'a>(&'a mut self) -> &'a mut BlockFlow { &mut self.block_flow } - fn as_immutable_block(&self) -> &BlockFlow { + fn as_block(&self) -> &BlockFlow { &self.block_flow } @@ -108,4 +108,3 @@ impl fmt::Debug for TableCaptionFlow { write!(f, "TableCaptionFlow: {:?}", self.block_flow) } } - diff --git a/components/layout/table_cell.rs b/components/layout/table_cell.rs index fea0fb61263..92ce3d98ceb 100644 --- a/components/layout/table_cell.rs +++ b/components/layout/table_cell.rs @@ -84,19 +84,19 @@ impl Flow for TableCellFlow { FlowClass::TableCell } - fn as_table_cell<'a>(&'a mut self) -> &'a mut TableCellFlow { + fn as_mut_table_cell<'a>(&'a mut self) -> &'a mut TableCellFlow { self } - fn as_immutable_table_cell<'a>(&'a self) -> &'a TableCellFlow { + fn as_table_cell<'a>(&'a self) -> &'a TableCellFlow { self } - fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow { + fn as_mut_block<'a>(&'a mut self) -> &'a mut BlockFlow { &mut self.block_flow } - fn as_immutable_block(&self) -> &BlockFlow { + fn as_block(&self) -> &BlockFlow { &self.block_flow } @@ -354,4 +354,3 @@ impl CollapsedBordersForCell { *border_styles = logical_border_styles.to_physical(writing_mode); } } - diff --git a/components/layout/table_colgroup.rs b/components/layout/table_colgroup.rs index c562149d5f2..7e8d2976823 100644 --- a/components/layout/table_colgroup.rs +++ b/components/layout/table_colgroup.rs @@ -56,7 +56,7 @@ impl Flow for TableColGroupFlow { FlowClass::TableColGroup } - fn as_table_colgroup<'a>(&'a mut self) -> &'a mut TableColGroupFlow { + fn as_mut_table_colgroup<'a>(&'a mut self) -> &'a mut TableColGroupFlow { self } diff --git a/components/layout/table_row.rs b/components/layout/table_row.rs index acd537c27f7..4dc732ff922 100644 --- a/components/layout/table_row.rs +++ b/components/layout/table_row.rs @@ -119,7 +119,7 @@ impl TableRowFlow { } { - let child_fragment = kid.as_table_cell().fragment(); + let child_fragment = kid.as_mut_table_cell().fragment(); // TODO: Percentage block-size let child_specified_block_size = MaybeAuto::from_style(child_fragment.style().content_block_size(), @@ -153,7 +153,7 @@ impl TableRowFlow { // Assign the block-size of kid fragments, which is the same value as own block-size. for kid in self.block_flow.base.child_iter() { - let child_table_cell = kid.as_table_cell(); + let child_table_cell = kid.as_mut_table_cell(); { let kid_fragment = child_table_cell.mut_fragment(); let mut position = kid_fragment.border_box; @@ -166,7 +166,7 @@ impl TableRowFlow { } } - pub fn populate_collapsed_border_spacing<'a,I>( + pub fn populate_collapsed_border_spacing<'a, I>( &mut self, collapsed_inline_direction_border_widths_for_table: &[Au], collapsed_block_direction_border_widths_for_table: &mut Peekable<I>) @@ -194,19 +194,19 @@ impl Flow for TableRowFlow { FlowClass::TableRow } - fn as_table_row<'a>(&'a mut self) -> &'a mut TableRowFlow { + fn as_mut_table_row<'a>(&'a mut self) -> &'a mut TableRowFlow { self } - fn as_immutable_table_row<'a>(&'a self) -> &'a TableRowFlow { + fn as_table_row<'a>(&'a self) -> &'a TableRowFlow { self } - fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow { + fn as_mut_block<'a>(&'a mut self) -> &'a mut BlockFlow { &mut self.block_flow } - fn as_immutable_block(&self) -> &BlockFlow { + fn as_block(&self) -> &BlockFlow { &self.block_flow } @@ -249,7 +249,7 @@ impl Flow for TableRowFlow { let child_specified_inline_size; let child_column_span; { - let child_table_cell = kid.as_table_cell(); + let child_table_cell = kid.as_mut_table_cell(); child_specified_inline_size = child_table_cell.block_flow .fragment .style @@ -685,18 +685,18 @@ pub fn propagate_column_inline_sizes_to_child( // FIXME(pcwalton): This seems inefficient. Reference count it instead? match child_flow.class() { FlowClass::Table => { - let child_table_flow = child_flow.as_table(); + let child_table_flow = child_flow.as_mut_table(); child_table_flow.column_computed_inline_sizes = column_computed_inline_sizes.to_vec(); } FlowClass::TableRowGroup => { - let child_table_rowgroup_flow = child_flow.as_table_rowgroup(); + let child_table_rowgroup_flow = child_flow.as_mut_table_rowgroup(); child_table_rowgroup_flow.column_computed_inline_sizes = column_computed_inline_sizes.to_vec(); child_table_rowgroup_flow.spacing = *border_spacing; child_table_rowgroup_flow.table_writing_mode = table_writing_mode; } FlowClass::TableRow => { - let child_table_row_flow = child_flow.as_table_row(); + let child_table_row_flow = child_flow.as_mut_table_row(); child_table_row_flow.column_computed_inline_sizes = column_computed_inline_sizes.to_vec(); child_table_row_flow.spacing = *border_spacing; @@ -725,7 +725,7 @@ fn set_inline_position_of_child_flow( let reverse_column_order = table_writing_mode.is_bidi_ltr() != row_writing_mode.is_bidi_ltr(); // Handle border collapsing, if necessary. - let child_table_cell = child_flow.as_table_cell(); + let child_table_cell = child_flow.as_mut_table_cell(); match *border_collapse_info { Some(ref border_collapse_info) => { // Write in the child's border collapse state. @@ -821,7 +821,7 @@ fn perform_inline_direction_border_collapse_for_row( CollapsedBorderProvenance::FromPreviousTableCell)); if let Some(&(_, ref next_child_flow)) = iterator.peek() { - let next_child_flow = next_child_flow.as_immutable_block(); + let next_child_flow = next_child_flow.as_block(); inline_collapsed_border.combine( &CollapsedBorder::inline_start(&*next_child_flow.fragment.style, CollapsedBorderProvenance::FromNextTableCell)) diff --git a/components/layout/table_rowgroup.rs b/components/layout/table_rowgroup.rs index 36ca99e0131..a085cd173fe 100644 --- a/components/layout/table_rowgroup.rs +++ b/components/layout/table_rowgroup.rs @@ -83,7 +83,7 @@ impl TableRowGroupFlow { &self.block_flow.fragment } - pub fn populate_collapsed_border_spacing<'a,I>( + pub fn populate_collapsed_border_spacing<'a, I>( &mut self, collapsed_inline_direction_border_widths_for_table: &[Au], collapsed_block_direction_border_widths_for_table: &mut Peekable<I>) @@ -112,19 +112,19 @@ impl Flow for TableRowGroupFlow { FlowClass::TableRowGroup } - fn as_table_rowgroup<'a>(&'a mut self) -> &'a mut TableRowGroupFlow { + fn as_mut_table_rowgroup<'a>(&'a mut self) -> &'a mut TableRowGroupFlow { self } - fn as_immutable_table_rowgroup<'a>(&'a self) -> &'a TableRowGroupFlow { + fn as_table_rowgroup<'a>(&'a self) -> &'a TableRowGroupFlow { self } - fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow { + fn as_mut_block<'a>(&'a mut self) -> &'a mut BlockFlow { &mut self.block_flow } - fn as_immutable_block(&self) -> &BlockFlow { + fn as_block(&self) -> &BlockFlow { &self.block_flow } @@ -187,7 +187,7 @@ impl Flow for TableRowGroupFlow { &border_spacing); if border_collapse == border_collapse::T::collapse { - let child_table_row = child_flow.as_table_row(); + let child_table_row = child_flow.as_mut_table_row(); child_table_row.populate_collapsed_border_spacing( collapsed_inline_direction_border_widths_for_table, &mut collapsed_block_direction_border_widths_for_table); diff --git a/components/layout/table_wrapper.rs b/components/layout/table_wrapper.rs index 459d58a4875..4beb11e76d7 100644 --- a/components/layout/table_wrapper.rs +++ b/components/layout/table_wrapper.rs @@ -99,7 +99,7 @@ impl TableWrapperFlow { continue } - let kid_table = kid.as_table(); + let kid_table = kid.as_mut_table(); let kid_block_flow = &mut kid_table.block_flow; kid_block_flow.fragment .compute_border_and_padding(available_inline_size, @@ -265,19 +265,19 @@ impl Flow for TableWrapperFlow { FlowClass::TableWrapper } - fn as_table_wrapper<'a>(&'a mut self) -> &'a mut TableWrapperFlow { + fn as_mut_table_wrapper<'a>(&'a mut self) -> &'a mut TableWrapperFlow { self } - fn as_immutable_table_wrapper<'a>(&'a self) -> &'a TableWrapperFlow { + fn as_table_wrapper<'a>(&'a self) -> &'a TableWrapperFlow { self } - fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow { + fn as_mut_block<'a>(&'a mut self) -> &'a mut BlockFlow { &mut self.block_flow } - fn as_immutable_block<'a>(&'a self) -> &'a BlockFlow { + fn as_block<'a>(&'a self) -> &'a BlockFlow { &self.block_flow } diff --git a/components/layout/wrapper.rs b/components/layout/wrapper.rs index 82fe6df054a..a44db23a02d 100644 --- a/components/layout/wrapper.rs +++ b/components/layout/wrapper.rs @@ -280,7 +280,7 @@ impl<'ln> LayoutNode<'ln> { /// Borrows the layout data immutably. Fails on a conflicting borrow. #[inline(always)] - pub fn borrow_layout_data<'a>(&'a self) -> Ref<'a,Option<LayoutDataWrapper>> { + pub fn borrow_layout_data<'a>(&'a self) -> Ref<'a, Option<LayoutDataWrapper>> { unsafe { mem::transmute(self.get_jsmanaged().layout_data()) } @@ -288,7 +288,7 @@ impl<'ln> LayoutNode<'ln> { /// Borrows the layout data mutably. Fails on a conflicting borrow. #[inline(always)] - pub fn mutate_layout_data<'a>(&'a self) -> RefMut<'a,Option<LayoutDataWrapper>> { + pub fn mutate_layout_data<'a>(&'a self) -> RefMut<'a, Option<LayoutDataWrapper>> { unsafe { mem::transmute(self.get_jsmanaged().layout_data_mut()) } @@ -743,7 +743,7 @@ impl<'ln> ThreadSafeLayoutNode<'ln> { /// /// TODO(pcwalton): Make this private. It will let us avoid borrow flag checks in some cases. #[inline(always)] - pub fn borrow_layout_data<'a>(&'a self) -> Ref<'a,Option<LayoutDataWrapper>> { + pub fn borrow_layout_data<'a>(&'a self) -> Ref<'a, Option<LayoutDataWrapper>> { self.node.borrow_layout_data() } @@ -751,7 +751,7 @@ impl<'ln> ThreadSafeLayoutNode<'ln> { /// /// TODO(pcwalton): Make this private. It will let us avoid borrow flag checks in some cases. #[inline(always)] - pub fn mutate_layout_data<'a>(&'a self) -> RefMut<'a,Option<LayoutDataWrapper>> { + pub fn mutate_layout_data<'a>(&'a self) -> RefMut<'a, Option<LayoutDataWrapper>> { self.node.mutate_layout_data() } diff --git a/components/net/fetch/cors_cache.rs b/components/net/fetch/cors_cache.rs index 658beec6808..1be29e321b1 100644 --- a/components/net/fetch/cors_cache.rs +++ b/components/net/fetch/cors_cache.rs @@ -53,7 +53,7 @@ pub struct CORSCacheEntry { } impl CORSCacheEntry { - fn new(origin:Url, url: Url, max_age: u32, credentials: bool, + fn new(origin: Url, url: Url, max_age: u32, credentials: bool, header_or_method: HeaderOrMethod) -> CORSCacheEntry { CORSCacheEntry { origin: origin, diff --git a/components/net/fetch/request.rs b/components/net/fetch/request.rs index 7f689a28df0..150e01eec9e 100644 --- a/components/net/fetch/request.rs +++ b/components/net/fetch/request.rs @@ -112,7 +112,7 @@ pub struct Request { pub redirect_mode: RedirectMode, pub redirect_count: usize, pub response_tainting: ResponseTainting, - pub cache: Option<Box<CORSCache+'static>> + pub cache: Option<Box<CORSCache + 'static>> } impl Request { diff --git a/components/net/image_cache_task.rs b/components/net/image_cache_task.rs index 2055f9a34a7..f0d97ba827b 100644 --- a/components/net/image_cache_task.rs +++ b/components/net/image_cache_task.rs @@ -282,7 +282,7 @@ impl ImageCache { let completed_load = CompletedLoad::new(image_response.clone()); self.completed_loads.insert(url, completed_load); - for listener in pending_load.listeners.into_iter() { + for listener in pending_load.listeners { listener.notify(image_response.clone()); } } diff --git a/components/net/mime_classifier.rs b/components/net/mime_classifier.rs index 3495d9a22ba..c4e94966548 100644 --- a/components/net/mime_classifier.rs +++ b/components/net/mime_classifier.rs @@ -23,14 +23,14 @@ impl MIMEClassifier { supplied_type: &Option<(String, String)>, data: &[u8]) -> Option<(String, String)> { - match *supplied_type{ + match *supplied_type { None => { return self.sniff_unknown_type(!no_sniff, data); } Some((ref media_type, ref media_subtype)) => { match (&**media_type, &**media_subtype) { ("unknown", "unknown") | ("application", "unknown") | ("*", "*") => { - return self.sniff_unknown_type(!no_sniff,data); + return self.sniff_unknown_type(!no_sniff, data); } _ => { if no_sniff { @@ -71,8 +71,8 @@ impl MIMEClassifier { return supplied_type.clone(); } - pub fn new()->MIMEClassifier { - MIMEClassifier{ + pub fn new() -> MIMEClassifier { + MIMEClassifier { image_classifier: GroupedClassifier::image_classifer(), audio_video_classifer: GroupedClassifier::audio_video_classifer(), scriptable_classifier: GroupedClassifier::scriptable_classifier(), @@ -84,7 +84,7 @@ impl MIMEClassifier { } //some sort of iterator over the classifiers might be better? fn sniff_unknown_type(&self, sniff_scriptable: bool, data: &[u8]) -> - Option<(String,String)> { + Option<(String, String)> { if sniff_scriptable { self.scriptable_classifier.classify(data) } else { @@ -107,21 +107,21 @@ impl MIMEClassifier { } } fn is_html(tp: &str, sub_tp: &str) -> bool { - tp=="text" && sub_tp=="html" + tp == "text" && sub_tp == "html" } } -pub fn as_string_option(tup: Option<(&'static str, &'static str)>) -> Option<(String,String)> { +pub fn as_string_option(tup: Option<(&'static str, &'static str)>) -> Option<(String, String)> { tup.map(|(a, b)| (a.to_owned(), b.to_owned())) } //Interface used for composite types trait MIMEChecker { - fn classify(&self, data: &[u8])->Option<(String, String)>; + fn classify(&self, data: &[u8]) -> Option<(String, String)>; } trait Matches { - fn matches(&mut self, matches: &[u8])->bool; + fn matches(&mut self, matches: &[u8]) -> bool; } impl <'a, T: Iterator<Item=&'a u8> + Clone> Matches for T { @@ -215,7 +215,7 @@ impl MIMEChecker for TagTerminatedByteMatcher { pub struct Mp4Matcher; impl Mp4Matcher { - pub fn matches(&self,data: &[u8]) -> bool { + pub fn matches(&self, data: &[u8]) -> bool { if data.len() < 12 { return false; } @@ -235,7 +235,7 @@ impl Mp4Matcher { } let mut all_match = true; for i in 8..11 { - if data[i]!=mp4[i - 8] { + if data[i] != mp4[i - 8] { all_match = false; break; } @@ -278,7 +278,7 @@ struct BinaryOrPlaintextClassifier; impl BinaryOrPlaintextClassifier { fn classify_impl(&self, data: &[u8]) -> Option<(&'static str, &'static str)> { - if (data.len() >=2 && + if (data.len() >= 2 && ((data[0] == 0xFFu8 && data[1] == 0xFEu8) || (data[0] == 0xFEu8 && data[1] == 0xFFu8))) || (data.len() >= 3 && data[0] == 0xEFu8 && data[1] == 0xBBu8 && data[2] == 0xBFu8) @@ -320,7 +320,7 @@ impl GroupedClassifier { } } fn audio_video_classifer() -> GroupedClassifier { - GroupedClassifier{ + GroupedClassifier { byte_matchers: vec![ box ByteMatcher::video_webm(), box ByteMatcher::audio_basic(), @@ -335,7 +335,7 @@ impl GroupedClassifier { } } fn scriptable_classifier() -> GroupedClassifier { - GroupedClassifier{ + GroupedClassifier { byte_matchers: vec![ box ByteMatcher::text_html_doctype(), box ByteMatcher::text_html_page(), @@ -361,7 +361,7 @@ impl GroupedClassifier { } fn plaintext_classifier() -> GroupedClassifier { - GroupedClassifier{ + GroupedClassifier { byte_matchers: vec![ box ByteMatcher::text_plain_utf_8_bom(), box ByteMatcher::text_plain_utf_16le_bom(), @@ -395,7 +395,7 @@ impl GroupedClassifier { } } impl MIMEChecker for GroupedClassifier { - fn classify(&self,data: &[u8]) -> Option<(String, String)> { + fn classify(&self, data: &[u8]) -> Option<(String, String)> { self.byte_matchers .iter() .filter_map(|matcher| matcher.classify(data)) @@ -405,7 +405,7 @@ impl MIMEChecker for GroupedClassifier { struct FeedsClassifier; impl FeedsClassifier { - fn classify_impl(&self,data: &[u8]) -> Option<(&'static str,&'static str)> { + fn classify_impl(&self, data: &[u8]) -> Option<(&'static str, &'static str)> { let length = data.len(); let mut data_iterator = data.iter(); @@ -469,7 +469,7 @@ impl FeedsClassifier { } impl MIMEChecker for FeedsClassifier { - fn classify(&self,data: &[u8]) -> Option<(String, String)> { + fn classify(&self, data: &[u8]) -> Option<(String, String)> { as_string_option(self.classify_impl(data)) } } @@ -478,8 +478,8 @@ impl MIMEChecker for FeedsClassifier { //TODO: These should be configured and not hard coded impl ByteMatcher { //A Windows Icon signature - fn image_x_icon()->ByteMatcher { - ByteMatcher{ + fn image_x_icon() -> ByteMatcher { + ByteMatcher { pattern: b"\x00\x00\x01\x00", mask: b"\xFF\xFF\xFF\xFF", content_type: ("image", "x-icon"), @@ -487,8 +487,8 @@ impl ByteMatcher { } } //A Windows Cursor signature. - fn image_x_icon_cursor()->ByteMatcher { - ByteMatcher{ + fn image_x_icon_cursor() -> ByteMatcher { + ByteMatcher { pattern: b"\x00\x00\x02\x00", mask: b"\xFF\xFF\xFF\xFF", content_type: ("image", "x-icon"), @@ -496,8 +496,8 @@ impl ByteMatcher { } } //The string "BM", a BMP signature. - fn image_bmp()->ByteMatcher { - ByteMatcher{ + fn image_bmp() -> ByteMatcher { + ByteMatcher { pattern: b"BM", mask: b"\xFF\xFF", content_type: ("image", "bmp"), @@ -505,8 +505,8 @@ impl ByteMatcher { } } //The string "GIF89a", a GIF signature. - fn image_gif89a()->ByteMatcher { - ByteMatcher{ + fn image_gif89a() -> ByteMatcher { + ByteMatcher { pattern: b"GIF89a", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF", content_type: ("image", "gif"), @@ -514,8 +514,8 @@ impl ByteMatcher { } } //The string "GIF87a", a GIF signature. - fn image_gif87a()->ByteMatcher { - ByteMatcher{ + fn image_gif87a() -> ByteMatcher { + ByteMatcher { pattern: b"GIF87a", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF", content_type: ("image", "gif"), @@ -523,8 +523,8 @@ impl ByteMatcher { } } //The string "RIFF" followed by four bytes followed by the string "WEBPVP". - fn image_webp()->ByteMatcher { - ByteMatcher{ + fn image_webp() -> ByteMatcher { + ByteMatcher { pattern: b"RIFF\x00\x00\x00\x00WEBPVP", mask: b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00,\xFF\xFF\xFF\xFF\xFF\xFF", content_type: ("image", "webp"), @@ -533,8 +533,8 @@ impl ByteMatcher { } //An error-checking byte followed by the string "PNG" followed by CR LF SUB LF, the PNG //signature. - fn image_png()->ByteMatcher { - ByteMatcher{ + fn image_png() -> ByteMatcher { + ByteMatcher { pattern: b"\x89PNG\r\n\x1A\n", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", content_type: ("image", "png"), @@ -542,8 +542,8 @@ impl ByteMatcher { } } // The JPEG Start of Image marker followed by the indicator byte of another marker. - fn image_jpeg()->ByteMatcher { - ByteMatcher{ + fn image_jpeg() -> ByteMatcher { + ByteMatcher { pattern: b"\xFF\xD8\xFF", mask: b"\xFF\xFF\xFF", content_type: ("image", "jpeg"), @@ -551,8 +551,8 @@ impl ByteMatcher { } } //The WebM signature. [TODO: Use more bytes?] - fn video_webm()->ByteMatcher { - ByteMatcher{ + fn video_webm() -> ByteMatcher { + ByteMatcher { pattern: b"\x1A\x45\xDF\xA3", mask: b"\xFF\xFF\xFF\xFF", content_type: ("video", "webm"), @@ -560,8 +560,8 @@ impl ByteMatcher { } } //The string ".snd", the basic audio signature. - fn audio_basic()->ByteMatcher { - ByteMatcher{ + fn audio_basic() -> ByteMatcher { + ByteMatcher { pattern: b".snd", mask: b"\xFF\xFF\xFF\xFF", content_type: ("audio", "basic"), @@ -569,8 +569,8 @@ impl ByteMatcher { } } //The string "FORM" followed by four bytes followed by the string "AIFF", the AIFF signature. - fn audio_aiff()->ByteMatcher { - ByteMatcher{ + fn audio_aiff() -> ByteMatcher { + ByteMatcher { pattern: b"FORM\x00\x00\x00\x00AIFF", mask: b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF", content_type: ("audio", "aiff"), @@ -578,8 +578,8 @@ impl ByteMatcher { } } //The string "ID3", the ID3v2-tagged MP3 signature. - fn audio_mpeg()->ByteMatcher { - ByteMatcher{ + fn audio_mpeg() -> ByteMatcher { + ByteMatcher { pattern: b"ID3", mask: b"\xFF\xFF\xFF", content_type: ("audio", "mpeg"), @@ -587,8 +587,8 @@ impl ByteMatcher { } } //The string "OggS" followed by NUL, the Ogg container signature. - fn application_ogg()->ByteMatcher { - ByteMatcher{ + fn application_ogg() -> ByteMatcher { + ByteMatcher { pattern: b"OggS", mask: b"\xFF\xFF\xFF\xFF\xFF", content_type: ("application", "ogg"), @@ -597,8 +597,8 @@ impl ByteMatcher { } //The string "MThd" followed by four bytes representing the number 6 in 32 bits (big-endian), //the MIDI signature. - fn audio_midi()->ByteMatcher { - ByteMatcher{ + fn audio_midi() -> ByteMatcher { + ByteMatcher { pattern: b"MThd\x00\x00\x00\x06", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", content_type: ("audio", "midi"), @@ -606,8 +606,8 @@ impl ByteMatcher { } } //The string "RIFF" followed by four bytes followed by the string "AVI ", the AVI signature. - fn video_avi()->ByteMatcher { - ByteMatcher{ + fn video_avi() -> ByteMatcher { + ByteMatcher { pattern: b"RIFF\x00\x00\x00\x00AVI ", mask: b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF", content_type: ("video", "avi"), @@ -615,8 +615,8 @@ impl ByteMatcher { } } // The string "RIFF" followed by four bytes followed by the string "WAVE", the WAVE signature. - fn audio_wave()->ByteMatcher { - ByteMatcher{ + fn audio_wave() -> ByteMatcher { + ByteMatcher { pattern: b"RIFF\x00\x00\x00\x00WAVE", mask: b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF", content_type: ("audio", "wave"), @@ -624,9 +624,9 @@ impl ByteMatcher { } } // doctype terminated with Tag terminating (TT) Byte - fn text_html_doctype()->TagTerminatedByteMatcher { + fn text_html_doctype() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { - matcher: ByteMatcher{ + matcher: ByteMatcher { pattern: b"<!DOCTYPE HTML", mask: b"\xFF\xFF\xDF\xDF\xDF\xDF\xDF\xDF\xDF\xFF\xDF\xDF\xDF\xDF", content_type: ("text", "html"), @@ -636,9 +636,9 @@ impl ByteMatcher { } // HTML terminated with Tag terminating (TT) Byte: 0x20 (SP) - fn text_html_page()->TagTerminatedByteMatcher { + fn text_html_page() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { - matcher: ByteMatcher{ + matcher: ByteMatcher { pattern: b"<HTML", mask: b"\xFF\xDF\xDF\xDF\xDF\xFF", content_type: ("text", "html"), @@ -648,9 +648,9 @@ impl ByteMatcher { } // head terminated with Tag Terminating (TT) Byte - fn text_html_head()->TagTerminatedByteMatcher { + fn text_html_head() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { - matcher: ByteMatcher{ + matcher: ByteMatcher { pattern: b"<HEAD", mask: b"\xFF\xDF\xDF\xDF\xDF", content_type: ("text", "html"), @@ -660,7 +660,7 @@ impl ByteMatcher { } // script terminated with Tag Terminating (TT) Byte - fn text_html_script()->TagTerminatedByteMatcher { + fn text_html_script() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b"<SCRIPT", @@ -672,9 +672,9 @@ impl ByteMatcher { } // iframe terminated with Tag Terminating (TT) Byte - fn text_html_iframe()->TagTerminatedByteMatcher { + fn text_html_iframe() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { - matcher: ByteMatcher{ + matcher: ByteMatcher { pattern: b"<IFRAME", mask: b"\xFF\xDF\xDF\xDF\xDF\xDF\xDF", content_type: ("text", "html"), @@ -684,9 +684,9 @@ impl ByteMatcher { } // h1 terminated with Tag Terminating (TT) Byte - fn text_html_h1()->TagTerminatedByteMatcher { + fn text_html_h1() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { - matcher: ByteMatcher{ + matcher: ByteMatcher { pattern: b"<H1", mask: b"\xFF\xDF\xFF", content_type: ("text", "html"), @@ -696,9 +696,9 @@ impl ByteMatcher { } // div terminated with Tag Terminating (TT) Byte - fn text_html_div()->TagTerminatedByteMatcher { + fn text_html_div() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { - matcher: ByteMatcher{ + matcher: ByteMatcher { pattern: b"<DIV", mask: b"\xFF\xDF\xDF\xDF", content_type: ("text", "html"), @@ -708,9 +708,9 @@ impl ByteMatcher { } // font terminated with Tag Terminating (TT) Byte - fn text_html_font()->TagTerminatedByteMatcher { + fn text_html_font() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { - matcher: ByteMatcher{ + matcher: ByteMatcher { pattern: b"<FONT", mask: b"\xFF\xDF\xDF\xDF\xDF", content_type: ("text", "html"), @@ -720,9 +720,9 @@ impl ByteMatcher { } // table terminated with Tag Terminating (TT) Byte - fn text_html_table()->TagTerminatedByteMatcher { + fn text_html_table() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { - matcher: ByteMatcher{ + matcher: ByteMatcher { pattern: b"<TABLE", mask: b"\xFF\xDF\xDF\xDF\xDF\xDF", content_type: ("text", "html"), @@ -732,9 +732,9 @@ impl ByteMatcher { } // a terminated with Tag Terminating (TT) Byte - fn text_html_a()->TagTerminatedByteMatcher { + fn text_html_a() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { - matcher: ByteMatcher{ + matcher: ByteMatcher { pattern: b"<A", mask: b"\xFF\xDF", content_type: ("text", "html"), @@ -744,9 +744,9 @@ impl ByteMatcher { } // style terminated with Tag Terminating (TT) Byte - fn text_html_style()->TagTerminatedByteMatcher { + fn text_html_style() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { - matcher: ByteMatcher{ + matcher: ByteMatcher { pattern: b"<STYLE", mask: b"\xFF\xDF\xDF\xDF\xDF\xDF", content_type: ("text", "html"), @@ -756,9 +756,9 @@ impl ByteMatcher { } // title terminated with Tag Terminating (TT) Byte - fn text_html_title()->TagTerminatedByteMatcher { + fn text_html_title() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { - matcher: ByteMatcher{ + matcher: ByteMatcher { pattern: b"<TITLE", mask: b"\xFF\xDF\xDF\xDF\xDF\xDF", content_type: ("text", "html"), @@ -768,9 +768,9 @@ impl ByteMatcher { } // b terminated with Tag Terminating (TT) Byte - fn text_html_b()->TagTerminatedByteMatcher { + fn text_html_b() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { - matcher: ByteMatcher{ + matcher: ByteMatcher { pattern: b"<B", mask: b"\xFF\xDF", content_type: ("text", "html"), @@ -780,9 +780,9 @@ impl ByteMatcher { } // body terminated with Tag Terminating (TT) Byte - fn text_html_body()->TagTerminatedByteMatcher { + fn text_html_body() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { - matcher: ByteMatcher{ + matcher: ByteMatcher { pattern: b"<BODY", mask: b"\xFF\xDF\xDF\xDF\xDF", content_type: ("text", "html"), @@ -792,9 +792,9 @@ impl ByteMatcher { } // br terminated with Tag Terminating (TT) Byte - fn text_html_br()->TagTerminatedByteMatcher { + fn text_html_br() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { - matcher: ByteMatcher{ + matcher: ByteMatcher { pattern: b"<BR", mask: b"\xFF\xDF\xDF", content_type: ("text", "html"), @@ -804,9 +804,9 @@ impl ByteMatcher { } // p terminated with Tag Terminating (TT) Byte - fn text_html_p()->TagTerminatedByteMatcher { + fn text_html_p() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { - matcher: ByteMatcher{ + matcher: ByteMatcher { pattern: b"<P", mask: b"\xFF\xDF", content_type: ("text", "html"), @@ -816,9 +816,9 @@ impl ByteMatcher { } // comment terminated with Tag Terminating (TT) Byte - fn text_html_comment()->TagTerminatedByteMatcher { + fn text_html_comment() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { - matcher: ByteMatcher{ + matcher: ByteMatcher { pattern: b"<!--", mask: b"\xFF\xFF\xFF\xFF", content_type: ("text", "html"), @@ -828,7 +828,7 @@ impl ByteMatcher { } //The string "<?xml". - fn text_xml()->ByteMatcher { + fn text_xml() -> ByteMatcher { ByteMatcher { pattern: b"<?xml", mask: b"\xFF\xFF\xFF\xFF\xFF", @@ -837,8 +837,8 @@ impl ByteMatcher { } } //The string "%PDF-", the PDF signature. - fn application_pdf()->ByteMatcher { - ByteMatcher{ + fn application_pdf() -> ByteMatcher { + ByteMatcher { pattern: b"%PDF", mask: b"\xFF\xFF\xFF\xFF\xFF", content_type: ("application", "pdf"), @@ -848,8 +848,8 @@ impl ByteMatcher { //34 bytes followed by the string "LP", the Embedded OpenType signature. // TODO: Use this in font context classifier #[allow(dead_code)] - fn application_vnd_ms_font_object()->ByteMatcher { - ByteMatcher{ + fn application_vnd_ms_font_object() -> ByteMatcher { + ByteMatcher { pattern: b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00LP", @@ -863,8 +863,8 @@ impl ByteMatcher { //4 bytes representing the version number 1.0, a TrueType signature. // TODO: Use this in font context classifier #[allow(dead_code)] - fn true_type()->ByteMatcher { - ByteMatcher{ + fn true_type() -> ByteMatcher { + ByteMatcher { pattern: b"\x00\x01\x00\x00", mask: b"\xFF\xFF\xFF\xFF", content_type: ("(TrueType)", ""), @@ -874,8 +874,8 @@ impl ByteMatcher { //The string "OTTO", the OpenType signature. // TODO: Use this in font context classifier #[allow(dead_code)] - fn open_type()->ByteMatcher { - ByteMatcher{ + fn open_type() -> ByteMatcher { + ByteMatcher { pattern: b"OTTO", mask: b"\xFF\xFF\xFF\xFF", content_type: ("(OpenType)", ""), @@ -885,8 +885,8 @@ impl ByteMatcher { // The string "ttcf", the TrueType Collection signature. // TODO: Use this in font context classifier #[allow(dead_code)] - fn true_type_collection()->ByteMatcher { - ByteMatcher{ + fn true_type_collection() -> ByteMatcher { + ByteMatcher { pattern: b"ttcf", mask: b"\xFF\xFF\xFF\xFF", content_type: ("(TrueType Collection)", ""), @@ -896,8 +896,8 @@ impl ByteMatcher { // The string "wOFF", the Web Open Font Format signature. // TODO: Use this in font context classifier #[allow(dead_code)] - fn application_font_woff()->ByteMatcher { - ByteMatcher{ + fn application_font_woff() -> ByteMatcher { + ByteMatcher { pattern: b"wOFF", mask: b"\xFF\xFF\xFF\xFF", content_type: ("application", "font-woff"), @@ -905,8 +905,8 @@ impl ByteMatcher { } } //The GZIP archive signature. - fn application_x_gzip()->ByteMatcher { - ByteMatcher{ + fn application_x_gzip() -> ByteMatcher { + ByteMatcher { pattern: b"\x1F\x8B\x08", mask: b"\xFF\xFF\xFF", content_type: ("application", "x-gzip"), @@ -914,8 +914,8 @@ impl ByteMatcher { } } //The string "PK" followed by ETX EOT, the ZIP archive signature. - fn application_zip()->ByteMatcher { - ByteMatcher{ + fn application_zip() -> ByteMatcher { + ByteMatcher { pattern: b"PK\x03\x04", mask: b"\xFF\xFF\xFF\xFF", content_type: ("application", "zip"), @@ -923,8 +923,8 @@ impl ByteMatcher { } } //The string "Rar " followed by SUB BEL NUL, the RAR archive signature. - fn application_x_rar_compressed()->ByteMatcher { - ByteMatcher{ + fn application_x_rar_compressed() -> ByteMatcher { + ByteMatcher { pattern: b"Rar \x1A\x07\x00", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF", content_type: ("application", "x-rar-compressed"), @@ -932,8 +932,8 @@ impl ByteMatcher { } } // The string "%!PS-Adobe-", the PostScript signature. - fn application_postscript()->ByteMatcher { - ByteMatcher{ + fn application_postscript() -> ByteMatcher { + ByteMatcher { pattern: b"%!PS-Adobe-", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", content_type: ("application", "postscript"), @@ -941,8 +941,8 @@ impl ByteMatcher { } } // UTF-16BE BOM - fn text_plain_utf_16be_bom()->ByteMatcher { - ByteMatcher{ + fn text_plain_utf_16be_bom() -> ByteMatcher { + ByteMatcher { pattern: b"\xFE\xFF\x00\x00", mask: b"\xFF\xFF\x00\x00", content_type: ("text", "plain"), @@ -950,8 +950,8 @@ impl ByteMatcher { } } //UTF-16LE BOM - fn text_plain_utf_16le_bom()->ByteMatcher { - ByteMatcher{ + fn text_plain_utf_16le_bom() -> ByteMatcher { + ByteMatcher { pattern: b"\xFF\xFE\x00\x00", mask: b"\xFF\xFF\x00\x00", content_type: ("text", "plain"), @@ -959,8 +959,8 @@ impl ByteMatcher { } } //UTF-8 BOM - fn text_plain_utf_8_bom()->ByteMatcher { - ByteMatcher{ + fn text_plain_utf_8_bom() -> ByteMatcher { + ByteMatcher { pattern: b"\xEF\xBB\xBF\x00", mask: b"\xFF\xFF\xFF\x00", content_type: ("text", "plain"), diff --git a/components/net/pub_domains.rs b/components/net/pub_domains.rs index 906b942f1be..7d51896f024 100644 --- a/components/net/pub_domains.rs +++ b/components/net/pub_domains.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/. */ -pub static PUB_DOMAINS : [&'static str; 5953] = [ +pub static PUB_DOMAINS: [&'static str; 5953] = [ "com.ac", "edu.ac", "gov.ac", diff --git a/components/net/resource_task.rs b/components/net/resource_task.rs index 7b87ec8830f..88200313cb8 100644 --- a/components/net/resource_task.rs +++ b/components/net/resource_task.rs @@ -128,7 +128,7 @@ pub fn start_sending_opt(start_chan: LoadConsumer, metadata: Metadata) -> Result } /// Create a ResourceTask -pub fn new_resource_task(user_agent: Option<String>, +pub fn new_resource_task(user_agent: String, devtools_chan: Option<Sender<DevtoolsControlMsg>>) -> ResourceTask { let hsts_preload = match preload_hsts_domains() { Some(list) => list, @@ -184,7 +184,7 @@ impl ResourceChannelManager { } pub struct ResourceManager { - user_agent: Option<String>, + user_agent: String, cookie_storage: CookieStorage, resource_task: IpcSender<ControlMsg>, mime_classifier: Arc<MIMEClassifier>, @@ -193,7 +193,7 @@ pub struct ResourceManager { } impl ResourceManager { - pub fn new(user_agent: Option<String>, + pub fn new(user_agent: String, resource_task: IpcSender<ControlMsg>, hsts_list: HSTSList, devtools_channel: Option<Sender<DevtoolsControlMsg>>) -> ResourceManager { @@ -212,7 +212,7 @@ impl ResourceManager { fn set_cookies_for_url(&mut self, request: Url, cookie_list: String, source: CookieSource) { let header = Header::parse_header(&[cookie_list.into_bytes()]); if let Ok(SetCookie(cookies)) = header { - for bare_cookie in cookies.into_iter() { + for bare_cookie in cookies { if let Some(cookie) = cookie::Cookie::new_wrapped(bare_cookie, &request, source) { self.cookie_storage.push(cookie, source); } @@ -229,9 +229,7 @@ impl ResourceManager { } fn load(&mut self, mut load_data: LoadData, consumer: LoadConsumer) { - self.user_agent.as_ref().map(|ua| { - load_data.preserved_headers.set(UserAgent(ua.clone())); - }); + load_data.preserved_headers.set(UserAgent(self.user_agent.clone())); fn from_factory(factory: fn(LoadData, LoadConsumer, Arc<MIMEClassifier>)) -> Box<FnBox(LoadData, LoadConsumer, Arc<MIMEClassifier>) + Send> { diff --git a/components/net_traits/image/base.rs b/components/net_traits/image/base.rs index 1e04ec84878..e0f52592250 100644 --- a/components/net_traits/image/base.rs +++ b/components/net_traits/image/base.rs @@ -116,7 +116,7 @@ pub fn load_from_memory(buffer: &[u8]) -> Option<Image> { fn is_gif(buffer: &[u8]) -> bool { match buffer { - [b'G',b'I',b'F',b'8', n, b'a', ..] if n == b'7' || n == b'9' => true, + [b'G', b'I', b'F', b'8', n, b'a', ..] if n == b'7' || n == b'9' => true, _ => false } } diff --git a/components/plugins/Cargo.toml b/components/plugins/Cargo.toml index 138ce7f9baf..0162a1f5516 100644 --- a/components/plugins/Cargo.toml +++ b/components/plugins/Cargo.toml @@ -11,3 +11,10 @@ plugin = true [dependencies.tenacious] git = "https://github.com/servo/rust-tenacious" +[dependencies.clippy] +git = "https://github.com/Manishearth/rust-clippy" +branch = "servo" +optional = true + +[features] +default = [] diff --git a/components/plugins/casing.rs b/components/plugins/casing.rs index f679441dbbd..40de2ff8d42 100644 --- a/components/plugins/casing.rs +++ b/components/plugins/casing.rs @@ -51,7 +51,7 @@ fn expand_cased<'cx, T>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree], } (_, rest) => { if rest > 0 { - cx.span_err(sp, &format!("expected 1 argument, found {}", rest+1)); + cx.span_err(sp, &format!("expected 1 argument, found {}", rest + 1)); } base::DummyResult::expr(sp) } diff --git a/components/plugins/jstraceable.rs b/components/plugins/jstraceable.rs index 39df8614784..dcfeda5418f 100644 --- a/components/plugins/jstraceable.rs +++ b/components/plugins/jstraceable.rs @@ -8,8 +8,8 @@ use syntax::ptr::P; use syntax::ast::{MetaItem, Expr}; use syntax::ast; use syntax::ext::build::AstBuilder; -use syntax::ext::deriving::generic::{combine_substructure, EnumMatching, FieldInfo, MethodDef, Struct, - Substructure, TraitDef, ty}; +use syntax::ext::deriving::generic::{combine_substructure, EnumMatching, FieldInfo, MethodDef}; +use syntax::ext::deriving::generic::{Struct, Substructure, TraitDef, ty}; pub fn expand_dom_struct(cx: &mut ExtCtxt, sp: Span, _: &MetaItem, anno: Annotatable) -> Annotatable { if let Annotatable::Item(item) = anno { diff --git a/components/plugins/lib.rs b/components/plugins/lib.rs index ba64164f9f6..8b69f2049bb 100644 --- a/components/plugins/lib.rs +++ b/components/plugins/lib.rs @@ -21,6 +21,8 @@ extern crate syntax; extern crate rustc; extern crate tenacious; +#[cfg(feature = "clippy")] +extern crate clippy; use rustc::lint::LintPassObject; use rustc::plugin::Registry; @@ -53,10 +55,19 @@ pub fn plugin_registrar(reg: &mut Registry) { reg.register_lint_pass(box lints::unrooted_must_root::UnrootedPass::new() as LintPassObject); reg.register_lint_pass(box lints::privatize::PrivatizePass as LintPassObject); reg.register_lint_pass(box lints::inheritance_integrity::InheritancePass as LintPassObject); - reg.register_lint_pass(box lints::str_to_string::StrToStringPass as LintPassObject); reg.register_lint_pass(box lints::ban::BanPass as LintPassObject); reg.register_lint_pass(box tenacious::TenaciousPass as LintPassObject); reg.register_attribute("must_root".to_string(), Whitelisted); reg.register_attribute("servo_lang".to_string(), Whitelisted); reg.register_attribute("allow_unrooted_interior".to_string(), Whitelisted); + register_clippy(reg); +} + +#[cfg(feature = "clippy")] +fn register_clippy(reg: &mut Registry) { + ::clippy::plugin_registrar(reg); +} +#[cfg(not(feature = "clippy"))] +fn register_clippy(reg: &mut Registry) { + reg.register_lint_pass(box lints::str_to_string::StrToStringPass as LintPassObject); } diff --git a/components/plugins/utils.rs b/components/plugins/utils.rs index 573eca63f6e..6327ada2f17 100644 --- a/components/plugins/utils.rs +++ b/components/plugins/utils.rs @@ -22,7 +22,7 @@ pub fn match_ty_unwrap<'a>(ty: &'a Ty, segments: &[&str]) -> Option<&'a [P<Ty>]> // I could muck around with the maps and find the full path // however the more efficient way is to simply reverse the iterators and zip them // which will compare them in reverse until one of them runs out of segments - if seg.iter().rev().zip(segments.iter().rev()).all(|(a,b)| a.identifier.name.as_str() == *b) { + if seg.iter().rev().zip(segments.iter().rev()).all(|(a, b)| a.identifier.name.as_str() == *b) { match seg.last() { Some(&PathSegment {parameters: AngleBracketedParameters(ref a), ..}) => { Some(&a.types) diff --git a/components/script/cors.rs b/components/script/cors.rs index 35111966fde..108f37790a3 100644 --- a/components/script/cors.rs +++ b/components/script/cors.rs @@ -106,10 +106,10 @@ impl CORSRequest { } pub fn http_fetch_async(&self, - listener: Box<AsyncCORSResponseListener+Send>, - script_chan: Box<ScriptChan+Send>) { + listener: Box<AsyncCORSResponseListener + Send>, + script_chan: Box<ScriptChan + Send>) { struct CORSContext { - listener: Box<AsyncCORSResponseListener+Send>, + listener: Box<AsyncCORSResponseListener + Send>, response: RefCell<Option<CORSResponse>>, } @@ -341,7 +341,7 @@ pub struct CORSCacheEntry { } impl CORSCacheEntry { - fn new(origin:Url, + fn new(origin: Url, url: Url, max_age: u32, credentials: bool, diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 0aad0a2547b..4e8b3d40101 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -4697,7 +4697,6 @@ class CGDictionary(CGThing): descriptorProvider, isMember="Dictionary", defaultValue=member.defaultValue, - failureCode="return Err(());", exceptionCode="return Err(());")) for member in dictionary.members] diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 6c2b36c40e9..75664ae3be9 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -149,7 +149,7 @@ impl<'a> GlobalRef<'a> { /// `ScriptChan` used to send messages to the event loop of this global's /// thread. - pub fn script_chan(&self) -> Box<ScriptChan+Send> { + pub fn script_chan(&self) -> Box<ScriptChan + Send> { match *self { GlobalRef::Window(ref window) => window.script_chan(), GlobalRef::Worker(ref worker) => worker.script_chan(), @@ -159,7 +159,7 @@ impl<'a> GlobalRef<'a> { /// Create a new sender/receiver pair that can be used to implement an on-demand /// event loop. Used for implementing web APIs that require blocking semantics /// without resorting to nested event loops. - pub fn new_script_pair(&self) -> (Box<ScriptChan+Send>, Box<ScriptPort+Send>) { + pub fn new_script_pair(&self) -> (Box<ScriptChan + Send>, Box<ScriptPort + Send>) { match *self { GlobalRef::Window(ref window) => window.new_script_pair(), GlobalRef::Worker(ref worker) => worker.new_script_pair(), diff --git a/components/script/dom/bindings/js.rs b/components/script/dom/bindings/js.rs index b622485f602..5b05d3ea99f 100644 --- a/components/script/dom/bindings/js.rs +++ b/components/script/dom/bindings/js.rs @@ -207,11 +207,11 @@ impl MutHeapJSVal { /// `JS<T>`. #[must_root] #[derive(JSTraceable)] -pub struct MutHeap<T: HeapGCValue+Copy> { +pub struct MutHeap<T: HeapGCValue + Copy> { val: Cell<T>, } -impl<T: HeapGCValue+Copy> MutHeap<T> { +impl<T: HeapGCValue + Copy> MutHeap<T> { /// Create a new `MutHeap`. pub fn new(initial: T) -> MutHeap<T> { MutHeap { @@ -236,11 +236,11 @@ impl<T: HeapGCValue+Copy> MutHeap<T> { /// barriers are enforced. #[must_root] #[derive(JSTraceable, HeapSizeOf)] -pub struct MutNullableHeap<T: HeapGCValue+Copy> { +pub struct MutNullableHeap<T: HeapGCValue + Copy> { ptr: Cell<Option<T>> } -impl<T: HeapGCValue+Copy> MutNullableHeap<T> { +impl<T: HeapGCValue + Copy> MutNullableHeap<T> { /// Create a new `MutNullableHeap`. pub fn new(initial: Option<T>) -> MutNullableHeap<T> { MutNullableHeap { @@ -288,7 +288,7 @@ impl<T: Reflectable> MutNullableHeap<JS<T>> { } } -impl<T: HeapGCValue+Copy> Default for MutNullableHeap<T> { +impl<T: HeapGCValue + Copy> Default for MutNullableHeap<T> { fn default() -> MutNullableHeap<T> { MutNullableHeap { ptr: Cell::new(None) diff --git a/components/script/dom/bindings/trace.rs b/components/script/dom/bindings/trace.rs index b0e082583f8..d05e099613f 100644 --- a/components/script/dom/bindings/trace.rs +++ b/components/script/dom/bindings/trace.rs @@ -178,7 +178,7 @@ impl<T: JSTraceable> JSTraceable for *mut T { } } -impl<T: JSTraceable+Copy> JSTraceable for Cell<T> { +impl<T: JSTraceable + Copy> JSTraceable for Cell<T> { fn trace(&self, trc: *mut JSTracer) { self.get().trace(trc) } @@ -212,7 +212,7 @@ impl JSTraceable for Heap<JSVal> { impl<T: JSTraceable> JSTraceable for Vec<T> { #[inline] fn trace(&self, trc: *mut JSTracer) { - for e in self.iter() { + for e in &*self { e.trace(trc); } } @@ -246,7 +246,7 @@ impl<T: JSTraceable, U: JSTraceable> JSTraceable for Result<T, U> { } } -impl<K,V,S> JSTraceable for HashMap<K, V, S> +impl<K, V, S> JSTraceable for HashMap<K, V, S> where K: Hash + Eq + JSTraceable, V: JSTraceable, S: HashState, @@ -254,7 +254,7 @@ impl<K,V,S> JSTraceable for HashMap<K, V, S> { #[inline] fn trace(&self, trc: *mut JSTracer) { - for (k, v) in self.iter() { + for (k, v) in &*self { k.trace(trc); v.trace(trc); } @@ -306,7 +306,7 @@ no_jsmanaged_fields!(WebGLError); no_jsmanaged_fields!(ProfilerChan); no_jsmanaged_fields!(PseudoElement); -impl JSTraceable for Box<ScriptChan+Send> { +impl JSTraceable for Box<ScriptChan + Send> { #[inline] fn trace(&self, _trc: *mut JSTracer) { // Do nothing @@ -327,7 +327,7 @@ impl<'a> JSTraceable for &'a str { } } -impl<A,B> JSTraceable for fn(A) -> B { +impl<A, B> JSTraceable for fn(A) -> B { #[inline] fn trace(&self, _: *mut JSTracer) { // Do nothing @@ -341,7 +341,7 @@ impl<T> JSTraceable for IpcSender<T> where T: Deserialize + Serialize { } } -impl JSTraceable for Box<LayoutRPC+'static> { +impl JSTraceable for Box<LayoutRPC + 'static> { #[inline] fn trace(&self, _: *mut JSTracer) { // Do nothing diff --git a/components/script/dom/bindings/utils.rs b/components/script/dom/bindings/utils.rs index d5c7d589ed4..9f458f83c2e 100644 --- a/components/script/dom/bindings/utils.rs +++ b/components/script/dom/bindings/utils.rs @@ -677,7 +677,7 @@ pub unsafe fn finalize_global(obj: *mut JSObject) { /// Trace the resources held by reserved slots of a global object pub unsafe fn trace_global(tracer: *mut JSTracer, obj: *mut JSObject) { let array = get_proto_or_iface_array(obj); - for proto in (&*array).iter() { + for proto in (*array).iter() { if !proto.is_null() { trace_object(tracer, "prototype", &*(proto as *const *mut JSObject as *const Heap<*mut JSObject>)); } @@ -690,7 +690,7 @@ unsafe extern fn wrap(cx: *mut JSContext, -> *mut JSObject { // FIXME terrible idea. need security wrappers // https://github.com/servo/servo/issues/2382 - WrapperNew(cx, obj, GetCrossCompartmentWrapper()) + WrapperNew(cx, obj, GetCrossCompartmentWrapper(), ptr::null(), false) } unsafe extern fn pre_wrap(cx: *mut JSContext, _existing: HandleObject, diff --git a/components/script/dom/blob.rs b/components/script/dom/blob.rs index 51a5ac0ab8c..04f7e782d0e 100644 --- a/components/script/dom/blob.rs +++ b/components/script/dom/blob.rs @@ -35,7 +35,7 @@ pub struct Blob { isClosed_: Cell<bool> } -fn is_ascii_printable(string: &DOMString) -> bool{ +fn is_ascii_printable(string: &DOMString) -> bool { // Step 5.1 in Sec 5.1 of File API spec // http://dev.w3.org/2006/webapi/FileAPI/#constructorBlob return string.chars().all(|c| { c >= '\x20' && c <= '\x7E' }) @@ -92,7 +92,7 @@ impl<'a> BlobHelpers for &'a Blob { impl<'a> BlobMethods for &'a Blob { // https://dev.w3.org/2006/webapi/FileAPI/#dfn-size - fn Size(self) -> u64{ + fn Size(self) -> u64 { match self.bytes { None => 0, Some(ref bytes) => bytes.len() as u64 diff --git a/components/script/dom/browsercontext.rs b/components/script/dom/browsercontext.rs index 8fe518844ba..bab6ca7a5f2 100644 --- a/components/script/dom/browsercontext.rs +++ b/components/script/dom/browsercontext.rs @@ -78,7 +78,7 @@ impl BrowsingContext { let _ar = JSAutoRequest::new(cx); let parent = win.reflector().get_jsobject(); let _ac = JSAutoCompartment::new(cx, parent.get()); - let wrapper = unsafe { WrapperNew(cx, parent, handler) }; + let wrapper = unsafe { WrapperNew(cx, parent, handler, ptr::null(), false) }; assert!(!wrapper.is_null()); self.window_proxy.set(wrapper); } diff --git a/components/script/dom/canvasrenderingcontext2d.rs b/components/script/dom/canvasrenderingcontext2d.rs index 6d3c6edddda..14863009b95 100644 --- a/components/script/dom/canvasrenderingcontext2d.rs +++ b/components/script/dom/canvasrenderingcontext2d.rs @@ -173,7 +173,7 @@ impl CanvasRenderingContext2D { // The source rectangle is the rectangle whose corners are the four points (sx, sy), // (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh). - let source_rect = Rect::new(Point2D::new(sx.min(sx+sw), sy.min(sy+sh)), + let source_rect = Rect::new(Point2D::new(sx.min(sx + sw), sy.min(sy + sh)), Size2D::new(sw.abs(), sh.abs())); // When the source rectangle is outside the source image, @@ -191,8 +191,10 @@ impl CanvasRenderingContext2D { // The destination rectangle is the rectangle whose corners are the four points (dx, dy), // (dx+dw, dy), (dx+dw, dy+dh), (dx, dy+dh). - let dest_rect = Rect::new(Point2D::new(dx.min(dx+dest_rect_width_scaled), dy.min(dy+dest_rect_height_scaled)), - Size2D::new(dest_rect_width_scaled.abs(), dest_rect_height_scaled.abs())); + let dest_rect = Rect::new(Point2D::new(dx.min(dx + dest_rect_width_scaled), + dy.min(dy + dest_rect_height_scaled)), + Size2D::new(dest_rect_width_scaled.abs(), + dest_rect_height_scaled.abs())); let source_rect = Rect::new(Point2D::new(source_rect_clipped.origin.x, source_rect_clipped.origin.y), diff --git a/components/script/dom/console.rs b/components/script/dom/console.rs index 0d7d3c9d8f3..0fca952d492 100644 --- a/components/script/dom/console.rs +++ b/components/script/dom/console.rs @@ -88,7 +88,7 @@ impl<'a> ConsoleMethods for &'a Console { fn prepare_message(logLevel: LogLevel, message: String) -> ConsoleMessage { //TODO: Sending fake values for filename, lineNumber and columnNumber in LogMessage; adjust later - ConsoleMessage{ + ConsoleMessage { message: message, logLevel: logLevel, filename: "test".to_owned(), diff --git a/components/script/dom/cssstyledeclaration.rs b/components/script/dom/cssstyledeclaration.rs index bbfdbc8231e..4c5fc207674 100644 --- a/components/script/dom/cssstyledeclaration.rs +++ b/components/script/dom/cssstyledeclaration.rs @@ -162,7 +162,7 @@ impl<'a> CSSStyleDeclarationMethods for &'a CSSStyleDeclaration { let mut list = vec!(); // Step 2.2 - for longhand in longhand_properties.iter() { + for longhand in &*longhand_properties { // Step 2.2.1 let declaration = owner.get_declaration(&Atom::from_slice(&longhand)); @@ -327,7 +327,7 @@ impl<'a> CSSStyleDeclarationMethods for &'a CSSStyleDeclaration { match longhands_from_shorthand(&property) { // Step 4 Some(longhands) => { - for longhand in longhands.iter() { + for longhand in &*longhands { elem.remove_inline_style_property(longhand) } } diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index 3ef4104c11c..d72e9243b95 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -150,7 +150,7 @@ pub struct DedicatedWorkerGlobalScope { worker: DOMRefCell<Option<TrustedWorkerAddress>>, #[ignore_heap_size_of = "Can't measure trait objects"] /// Sender to the parent thread. - parent_sender: Box<ScriptChan+Send>, + parent_sender: Box<ScriptChan + Send>, } impl DedicatedWorkerGlobalScope { @@ -159,7 +159,7 @@ impl DedicatedWorkerGlobalScope { id: PipelineId, devtools_port: Receiver<DevtoolScriptControlMsg>, runtime: Rc<Runtime>, - parent_sender: Box<ScriptChan+Send>, + parent_sender: Box<ScriptChan + Send>, own_sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>, receiver: Receiver<(TrustedWorkerAddress, WorkerScriptMsg)>) -> DedicatedWorkerGlobalScope { @@ -180,7 +180,7 @@ impl DedicatedWorkerGlobalScope { id: PipelineId, devtools_port: Receiver<DevtoolScriptControlMsg>, runtime: Rc<Runtime>, - parent_sender: Box<ScriptChan+Send>, + parent_sender: Box<ScriptChan + Send>, own_sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>, receiver: Receiver<(TrustedWorkerAddress, WorkerScriptMsg)>) -> Root<DedicatedWorkerGlobalScope> { @@ -197,7 +197,7 @@ impl DedicatedWorkerGlobalScope { id: PipelineId, devtools_ipc_port: IpcReceiver<DevtoolScriptControlMsg>, worker: TrustedWorkerAddress, - parent_sender: Box<ScriptChan+Send>, + parent_sender: Box<ScriptChan + Send>, own_sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>, receiver: Receiver<(TrustedWorkerAddress, WorkerScriptMsg)>) { let serialized_worker_url = worker_url.serialize(); @@ -247,14 +247,14 @@ impl DedicatedWorkerGlobalScope { } pub trait DedicatedWorkerGlobalScopeHelpers { - fn script_chan(self) -> Box<ScriptChan+Send>; + fn script_chan(self) -> Box<ScriptChan + Send>; fn pipeline(self) -> PipelineId; - fn new_script_pair(self) -> (Box<ScriptChan+Send>, Box<ScriptPort+Send>); + fn new_script_pair(self) -> (Box<ScriptChan + Send>, Box<ScriptPort + Send>); fn process_event(self, msg: CommonScriptMsg); } impl<'a> DedicatedWorkerGlobalScopeHelpers for &'a DedicatedWorkerGlobalScope { - fn script_chan(self) -> Box<ScriptChan+Send> { + fn script_chan(self) -> Box<ScriptChan + Send> { box WorkerThreadWorkerChan { sender: self.own_sender.clone(), worker: self.worker.borrow().as_ref().unwrap().clone(), @@ -265,7 +265,7 @@ impl<'a> DedicatedWorkerGlobalScopeHelpers for &'a DedicatedWorkerGlobalScope { self.id } - fn new_script_pair(self) -> (Box<ScriptChan+Send>, Box<ScriptPort+Send>) { + fn new_script_pair(self) -> (Box<ScriptChan + Send>, Box<ScriptPort + Send>) { let (tx, rx) = channel(); let chan = box SendableWorkerScriptChan { sender: tx, diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index c3d81e20ba5..c538893506b 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -899,7 +899,7 @@ impl<'a> DocumentHelpers<'a> for &'a Document { } } else { let fragment = NodeCast::from_root(self.CreateDocumentFragment()); - for node in nodes.into_iter() { + for node in nodes { match node { NodeOrString::eNode(node) => { try!(fragment.r().AppendChild(node.r())); diff --git a/components/script/dom/element.rs b/components/script/dom/element.rs index 8da1c8c9373..6c8bdf028ba 100644 --- a/components/script/dom/element.rs +++ b/components/script/dom/element.rs @@ -685,7 +685,7 @@ impl<'a> ElementHelpers<'a> for &'a Element { // Usually, the reference count will be 1 here. But transitions could make it greater // than that. let existing_declarations = Arc::make_unique(existing_declarations); - for declaration in existing_declarations.iter_mut() { + for declaration in &mut *existing_declarations { if declaration.name() == property_decl.name() { *declaration = property_decl; return; diff --git a/components/script/dom/eventdispatcher.rs b/components/script/dom/eventdispatcher.rs index a99acb7b911..3451b22d108 100644 --- a/components/script/dom/eventdispatcher.rs +++ b/components/script/dom/eventdispatcher.rs @@ -47,7 +47,7 @@ pub fn dispatch_event<'a, 'b>(target: &'a EventTarget, event.set_current_target(cur_target); for listener in &listeners { // Explicitly drop any exception on the floor. - let _ = listener.HandleEvent_(*cur_target, event, Report); + listener.call_or_handle_event(*cur_target, event, Report); if event.stop_immediate() { break; @@ -70,10 +70,10 @@ pub fn dispatch_event<'a, 'b>(target: &'a EventTarget, event.set_current_target(target.clone()); let opt_listeners = target.get_listeners(&type_); - for listeners in opt_listeners.iter() { - for listener in listeners.iter() { + for listeners in opt_listeners { + for listener in listeners { // Explicitly drop any exception on the floor. - let _ = listener.HandleEvent_(target, event, Report); + listener.call_or_handle_event(target, event, Report); if event.stop_immediate() { break; @@ -92,7 +92,7 @@ pub fn dispatch_event<'a, 'b>(target: &'a EventTarget, event.set_current_target(cur_target); for listener in &listeners { // Explicitly drop any exception on the floor. - let _ = listener.HandleEvent_(*cur_target, event, Report); + listener.call_or_handle_event(*cur_target, event, Report); if event.stop_immediate() { break; diff --git a/components/script/dom/eventtarget.rs b/components/script/dom/eventtarget.rs index 79679ff14d2..31c8e366daa 100644 --- a/components/script/dom/eventtarget.rs +++ b/components/script/dom/eventtarget.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 dom::bindings::callback::CallbackContainer; +use dom::bindings::callback::{CallbackContainer, ExceptionHandling}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::EventListenerBinding::EventListener; @@ -37,6 +37,8 @@ use url::Url; use std::collections::HashMap; +pub type EventHandler = EventHandlerNonNull; + #[derive(JSTraceable, Copy, Clone, PartialEq, HeapSizeOf)] pub enum ListenerPhase { Capturing, @@ -94,7 +96,7 @@ impl EventTargetTypeId { #[derive(JSTraceable, Clone, PartialEq)] pub enum EventListenerType { Additive(Rc<EventListener>), - Inline(Rc<EventListener>), + Inline(Rc<EventHandler>), } impl HeapSizeOf for EventListenerType { @@ -105,10 +107,17 @@ impl HeapSizeOf for EventListenerType { } impl EventListenerType { - fn get_listener(&self) -> Rc<EventListener> { + pub fn call_or_handle_event<T: Reflectable>(&self, + object: &T, + event: &Event, + exception_handle: ExceptionHandling) { match *self { - EventListenerType::Additive(ref listener) | - EventListenerType::Inline(ref listener) => listener.clone(), + EventListenerType::Additive(ref listener) => { + let _ = listener.HandleEvent_(object, event, exception_handle); + }, + EventListenerType::Inline(ref handler) => { + let _ = handler.Call_(object, event, exception_handle); + }, } } } @@ -137,17 +146,17 @@ impl EventTarget { } } - pub fn get_listeners(&self, type_: &str) -> Option<Vec<Rc<EventListener>>> { + pub fn get_listeners(&self, type_: &str) -> Option<Vec<EventListenerType>> { self.handlers.borrow().get(type_).map(|listeners| { - listeners.iter().map(|entry| entry.listener.get_listener()).collect() + listeners.iter().map(|entry| entry.listener.clone()).collect() }) } pub fn get_listeners_for(&self, type_: &str, desired_phase: ListenerPhase) - -> Option<Vec<Rc<EventListener>>> { + -> Option<Vec<EventListenerType>> { self.handlers.borrow().get(type_).map(|listeners| { let filtered = listeners.iter().filter(|entry| entry.phase == desired_phase); - filtered.map(|entry| entry.listener.get_listener()).collect() + filtered.map(|entry| entry.listener.clone()).collect() }) } @@ -164,8 +173,8 @@ pub trait EventTargetHelpers { fn dispatch_event(self, event: &Event) -> bool; fn set_inline_event_listener(self, ty: DOMString, - listener: Option<Rc<EventListener>>); - fn get_inline_event_listener(self, ty: DOMString) -> Option<Rc<EventListener>>; + listener: Option<Rc<EventHandler>>); + fn get_inline_event_listener(self, ty: DOMString) -> Option<Rc<EventHandler>>; fn set_event_handler_uncompiled(self, cx: *mut JSContext, url: Url, @@ -192,7 +201,7 @@ impl<'a> EventTargetHelpers for &'a EventTarget { fn set_inline_event_listener(self, ty: DOMString, - listener: Option<Rc<EventListener>>) { + listener: Option<Rc<EventHandler>>) { let mut handlers = self.handlers.borrow_mut(); let entries = match handlers.entry(ty) { Occupied(entry) => entry.into_mut(), @@ -226,15 +235,15 @@ impl<'a> EventTargetHelpers for &'a EventTarget { } } - fn get_inline_event_listener(self, ty: DOMString) -> Option<Rc<EventListener>> { + fn get_inline_event_listener(self, ty: DOMString) -> Option<Rc<EventHandler>> { let handlers = self.handlers.borrow(); let entries = handlers.get(&ty); - entries.and_then(|entries| entries.iter().find(|entry| { + entries.and_then(|entries| entries.iter().filter_map(|entry| { match entry.listener { - EventListenerType::Inline(_) => true, - _ => false, + EventListenerType::Inline(ref handler) => Some(handler.clone()), + _ => None, } - }).map(|entry| entry.listener.get_listener())) + }).next()) } #[allow(unsafe_code)] @@ -283,7 +292,7 @@ impl<'a> EventTargetHelpers for &'a EventTarget { self, ty: &str, listener: Option<Rc<T>>) { let event_listener = listener.map(|listener| - EventListener::new(listener.callback())); + EventHandlerNonNull::new(listener.callback())); self.set_inline_event_listener(ty.to_owned(), event_listener); } @@ -332,8 +341,8 @@ impl<'a> EventTargetMethods for &'a EventTarget { match listener { Some(ref listener) => { let mut handlers = self.handlers.borrow_mut(); - let mut entry = handlers.get_mut(&ty); - for entry in entry.iter_mut() { + let entry = handlers.get_mut(&ty); + for entry in entry { let phase = if capture { ListenerPhase::Capturing } else { ListenerPhase::Bubbling }; let old_entry = EventListenerEntry { phase: phase, diff --git a/components/script/dom/filereader.rs b/components/script/dom/filereader.rs index 4b8721a21e6..f819a2b395c 100644 --- a/components/script/dom/filereader.rs +++ b/components/script/dom/filereader.rs @@ -267,7 +267,7 @@ impl<'a> FileReaderMethods for &'a FileReader { } // https://w3c.github.io/FileAPI/#dfn-readAsText - fn ReadAsText(self, blob: &Blob, label:Option<DOMString>) -> ErrorResult { + fn ReadAsText(self, blob: &Blob, label: Option<DOMString>) -> ErrorResult { self.read(FileReaderFunction::ReadAsText, blob, label) } diff --git a/components/script/dom/formdata.rs b/components/script/dom/formdata.rs index ff2b6d78fdc..cd26613cb74 100644 --- a/components/script/dom/formdata.rs +++ b/components/script/dom/formdata.rs @@ -121,7 +121,7 @@ impl<'a> FormDataMethods for &'a FormData { } } -trait PrivateFormDataHelpers{ +trait PrivateFormDataHelpers { fn get_file_from_blob(self, value: &Blob, filename: Option<DOMString>) -> Root<File>; } diff --git a/components/script/dom/htmlcollection.rs b/components/script/dom/htmlcollection.rs index 88414aa6a84..bbac05d5b97 100644 --- a/components/script/dom/htmlcollection.rs +++ b/components/script/dom/htmlcollection.rs @@ -24,28 +24,25 @@ pub trait CollectionFilter : JSTraceable { #[derive(JSTraceable)] #[must_root] -pub enum CollectionTypeId { - Static(Vec<JS<Element>>), - Live(JS<Node>, Box<CollectionFilter+'static>) -} +pub struct Collection(JS<Node>, Box<CollectionFilter + 'static>); #[dom_struct] #[derive(HeapSizeOf)] pub struct HTMLCollection { reflector_: Reflector, #[ignore_heap_size_of = "Contains a trait object; can't measure due to #6870"] - collection: CollectionTypeId, + collection: Collection, } impl HTMLCollection { - fn new_inherited(collection: CollectionTypeId) -> HTMLCollection { + fn new_inherited(collection: Collection) -> HTMLCollection { HTMLCollection { reflector_: Reflector::new(), collection: collection, } } - pub fn new(window: &Window, collection: CollectionTypeId) -> Root<HTMLCollection> { + pub fn new(window: &Window, collection: Collection) -> Root<HTMLCollection> { reflect_dom_object(box HTMLCollection::new_inherited(collection), GlobalRef::Window(window), HTMLCollectionBinding::Wrap) } @@ -53,8 +50,8 @@ impl HTMLCollection { impl HTMLCollection { pub fn create(window: &Window, root: &Node, - filter: Box<CollectionFilter+'static>) -> Root<HTMLCollection> { - HTMLCollection::new(window, CollectionTypeId::Live(JS::from_ref(root), filter)) + filter: Box<CollectionFilter + 'static>) -> Root<HTMLCollection> { + HTMLCollection::new(window, Collection(JS::from_ref(root), filter)) } fn all_elements(window: &Window, root: &Node, @@ -179,34 +176,28 @@ impl HTMLCollection { impl<'a> HTMLCollectionMethods for &'a HTMLCollection { // https://dom.spec.whatwg.org/#dom-htmlcollection-length + #[allow(unrooted_must_root)] fn Length(self) -> u32 { - match self.collection { - CollectionTypeId::Static(ref elems) => elems.len() as u32, - CollectionTypeId::Live(ref root, ref filter) => { - let root = root.root(); - HTMLCollection::traverse(root.r()) - .filter(|element| filter.filter(element.r(), root.r())) - .count() as u32 - } - } + let Collection(ref root, ref filter) = self.collection; + let root = root.root(); + HTMLCollection::traverse(root.r()) + .filter(|element| filter.filter(element.r(), root.r())) + .count() as u32 } // https://dom.spec.whatwg.org/#dom-htmlcollection-item + #[allow(unrooted_must_root)] fn Item(self, index: u32) -> Option<Root<Element>> { let index = index as usize; - match self.collection { - CollectionTypeId::Static(ref elems) => elems - .get(index).map(|t| t.root()), - CollectionTypeId::Live(ref root, ref filter) => { - let root = root.root(); - HTMLCollection::traverse(root.r()) - .filter(|element| filter.filter(element.r(), root.r())) - .nth(index) - } - } + let Collection(ref root, ref filter) = self.collection; + let root = root.root(); + HTMLCollection::traverse(root.r()) + .filter(|element| filter.filter(element.r(), root.r())) + .nth(index) } // https://dom.spec.whatwg.org/#dom-htmlcollection-nameditem + #[allow(unrooted_must_root)] fn NamedItem(self, key: DOMString) -> Option<Root<Element>> { // Step 1. if key.is_empty() { @@ -214,21 +205,13 @@ impl<'a> HTMLCollectionMethods for &'a HTMLCollection { } // Step 2. - match self.collection { - CollectionTypeId::Static(ref elems) => elems.iter() - .map(|elem| elem.root()) - .find(|elem| { - elem.r().get_string_attribute(&atom!("name")) == key || - elem.r().get_string_attribute(&atom!("id")) == key }), - CollectionTypeId::Live(ref root, ref filter) => { - let root = root.root(); - HTMLCollection::traverse(root.r()) - .filter(|element| filter.filter(element.r(), root.r())) - .find(|elem| { - elem.r().get_string_attribute(&atom!("name")) == key || - elem.r().get_string_attribute(&atom!("id")) == key }) - } - } + let Collection(ref root, ref filter) = self.collection; + let root = root.root(); + HTMLCollection::traverse(root.r()) + .filter(|element| filter.filter(element.r(), root.r())) + .find(|elem| { + elem.r().get_string_attribute(&atom!("name")) == key || + elem.r().get_string_attribute(&atom!("id")) == key}) } // https://dom.spec.whatwg.org/#dom-htmlcollection-item diff --git a/components/script/dom/htmliframeelement.rs b/components/script/dom/htmliframeelement.rs index 978489f3f3b..eed9a99aac0 100644 --- a/components/script/dom/htmliframeelement.rs +++ b/components/script/dom/htmliframeelement.rs @@ -7,8 +7,8 @@ use dom::bindings::codegen::Bindings::HTMLIFrameElementBinding; use dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElementMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast, EventCast}; -use dom::bindings::codegen::InheritTypes::{EventTargetCast, HTMLElementCast, - HTMLIFrameElementDerived}; +use dom::bindings::codegen::InheritTypes::{EventTargetCast, HTMLElementCast}; +use dom::bindings::codegen::InheritTypes::HTMLIFrameElementDerived; use dom::bindings::conversions::ToJSValConvertible; use dom::bindings::error::{ErrorResult, Fallible}; use dom::bindings::error::Error::NotSupported; diff --git a/components/script/dom/htmlimageelement.rs b/components/script/dom/htmlimageelement.rs index ce08c2b7a89..53b2cf7fc22 100644 --- a/components/script/dom/htmlimageelement.rs +++ b/components/script/dom/htmlimageelement.rs @@ -8,8 +8,8 @@ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLImageElementBinding; use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; -use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast, EventTargetCast, HTMLElementCast, - HTMLImageElementDerived}; +use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast, EventTargetCast}; +use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLImageElementDerived}; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{LayoutJS, Root}; diff --git a/components/script/dom/navigatorinfo.rs b/components/script/dom/navigatorinfo.rs index d4aec6999ab..4982908969b 100644 --- a/components/script/dom/navigatorinfo.rs +++ b/components/script/dom/navigatorinfo.rs @@ -28,10 +28,7 @@ pub fn Platform() -> DOMString { } pub fn UserAgent() -> DOMString { - match opts::get().user_agent { - Some(ref user_agent) => user_agent.clone(), - None => "".to_owned(), - } + opts::get().user_agent.clone() } pub fn AppVersion() -> DOMString { diff --git a/components/script/dom/node.rs b/components/script/dom/node.rs index ac5b6ac3401..6ca62f181e3 100644 --- a/components/script/dom/node.rs +++ b/components/script/dom/node.rs @@ -264,7 +264,7 @@ impl LayoutDataRef { /// Borrows the layout data immutably. This function is *not* thread-safe. #[inline] - pub fn borrow<'a>(&'a self) -> Ref<'a,Option<LayoutData>> { + pub fn borrow(&self) -> Ref<Option<LayoutData>> { debug_assert!(task_state::get().is_layout()); self.data_cell.borrow() } @@ -275,7 +275,7 @@ impl LayoutDataRef { /// prevent CSS selector matching from mutably accessing nodes it's not supposed to and racing /// on it. This has already resulted in one bug! #[inline] - pub fn borrow_mut<'a>(&'a self) -> RefMut<'a,Option<LayoutData>> { + pub fn borrow_mut(&self) -> RefMut<Option<LayoutData>> { debug_assert!(task_state::get().is_layout()); self.data_cell.borrow_mut() } @@ -908,7 +908,7 @@ impl<'a> NodeHelpers for &'a Node { // Step 1. match parse_author_origin_selector_list_from_str(&selectors) { // Step 2. - Err(()) => return Err(Syntax), + Err(()) => Err(Syntax), // Step 3. Ok(ref selectors) => { let root = self.ancestors().last(); @@ -1326,7 +1326,7 @@ impl Iterator for FollowingNodeIterator { } } self.current = None; - return None + None } } @@ -1372,7 +1372,7 @@ impl Iterator for PrecedingNodeIterator { } self.current = None; - return None + None } } @@ -1464,7 +1464,7 @@ pub enum CloneChildrenFlag { fn as_uintptr<T>(t: &T) -> uintptr_t { t as *const T as uintptr_t } impl Node { - pub fn reflect_node<N: Reflectable+NodeBase> + pub fn reflect_node<N: Reflectable + NodeBase> (node: Box<N>, document: &Document, wrap_fn: extern "Rust" fn(*mut JSContext, GlobalRef, Box<N>) -> Root<N>) @@ -1663,7 +1663,7 @@ impl Node { Node::insert(node, parent, reference_child, SuppressObserver::Unsuppressed); // Step 6. - return Ok(Root::from_ref(node)) + Ok(Root::from_ref(node)) } // https://dom.spec.whatwg.org/#concept-node-insert @@ -1867,7 +1867,7 @@ impl Node { let copy_elem = ElementCast::to_ref(copy.r()).unwrap(); let window = document.r().window(); - for ref attr in node_elem.attrs().iter() { + for ref attr in &*node_elem.attrs() { let attr = attr.root(); let newattr = Attr::new(window.r(), @@ -2088,24 +2088,13 @@ impl<'a> NodeMethods for &'a Node { // https://dom.spec.whatwg.org/#dom-node-nodevalue fn GetNodeValue(self) -> Option<DOMString> { - match self.type_id { - NodeTypeId::CharacterData(..) => { - let chardata: &CharacterData = CharacterDataCast::to_ref(self).unwrap(); - Some(chardata.Data()) - } - _ => { - None - } - } + CharacterDataCast::to_ref(self).map(|c| c.Data()) } // https://dom.spec.whatwg.org/#dom-node-nodevalue fn SetNodeValue(self, val: Option<DOMString>) { - match self.type_id { - NodeTypeId::CharacterData(..) => { - self.SetTextContent(val) - } - _ => {} + if let NodeTypeId::CharacterData(..) = self.type_id { + self.SetTextContent(val) } } @@ -2554,18 +2543,18 @@ pub struct TrustedNodeAddress(pub *const c_void); #[allow(unsafe_code)] unsafe impl Send for TrustedNodeAddress {} -pub fn document_from_node<T: NodeBase+Reflectable>(derived: &T) -> Root<Document> { +pub fn document_from_node<T: NodeBase + Reflectable>(derived: &T) -> Root<Document> { let node: &Node = NodeCast::from_ref(derived); node.owner_doc() } -pub fn window_from_node<T: NodeBase+Reflectable>(derived: &T) -> Root<Window> { +pub fn window_from_node<T: NodeBase + Reflectable>(derived: &T) -> Root<Window> { let document = document_from_node(derived); document.r().window() } impl<'a> VirtualMethods for &'a Node { - fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { + fn super_type(&self) -> Option<&VirtualMethods> { let eventtarget: &&EventTarget = EventTargetCast::from_borrowed_ref(self); Some(eventtarget as &VirtualMethods) } diff --git a/components/script/dom/nodeiterator.rs b/components/script/dom/nodeiterator.rs index 7e641c83cfd..0958bfca992 100644 --- a/components/script/dom/nodeiterator.rs +++ b/components/script/dom/nodeiterator.rs @@ -138,7 +138,7 @@ impl<'a> NodeIteratorMethods for &'a NodeIterator { } } - return Ok(None); + Ok(None) } // https://dom.spec.whatwg.org/#dom-nodeiterator-previousnode @@ -183,7 +183,7 @@ impl<'a> NodeIteratorMethods for &'a NodeIterator { } } - return Ok(None); + Ok(None) } // https://dom.spec.whatwg.org/#dom-nodeiterator-detach diff --git a/components/script/dom/progressevent.rs b/components/script/dom/progressevent.rs index 1dc1f2b9917..20af2b68d1c 100644 --- a/components/script/dom/progressevent.rs +++ b/components/script/dom/progressevent.rs @@ -69,7 +69,7 @@ impl<'a> ProgressEventMethods for &'a ProgressEvent { } // https://xhr.spec.whatwg.org/#dom-progressevent-loaded - fn Loaded(self) -> u64{ + fn Loaded(self) -> u64 { self.loaded } diff --git a/components/script/dom/range.rs b/components/script/dom/range.rs index bf810546be8..78af618eff5 100644 --- a/components/script/dom/range.rs +++ b/components/script/dom/range.rs @@ -114,7 +114,7 @@ impl Range { }; // Step 11. - let contained_children : Vec<Root<Node>> = + let contained_children: Vec<Root<Node>> = common_ancestor.children().filter(|n| Range::contains(self, n)).collect(); // Step 12. @@ -122,7 +122,7 @@ impl Range { return Err(HierarchyRequest); } - return Ok((first_contained_child, last_contained_child, contained_children)); + Ok((first_contained_child, last_contained_child, contained_children)) } } @@ -338,17 +338,11 @@ impl<'a> RangeMethods for &'a Range { let end = &inner.end; let end_node = end.node(); let end_offset = end.offset; - match (bp_position(parent.r(), offset + 1, start_node.r(), start_offset).unwrap(), - bp_position(parent.r(), offset, end_node.r(), end_offset).unwrap()) { - (Ordering::Greater, Ordering::Less) => { - // Step 5. - true - }, - _ => { - // Step 6. - false - } - } + // Step 5. + Ordering::Greater == bp_position(parent.r(), offset + 1, + start_node.r(), start_offset).unwrap() && + Ordering::Less == bp_position(parent.r(), offset, + end_node.r(), end_offset).unwrap() } // https://dom.spec.whatwg.org/#dom-range-clonecontents diff --git a/components/script/dom/servohtmlparser.rs b/components/script/dom/servohtmlparser.rs index c14603df876..b9ccd50632f 100644 --- a/components/script/dom/servohtmlparser.rs +++ b/components/script/dom/servohtmlparser.rs @@ -63,13 +63,13 @@ pub struct ParserContext { /// The subpage associated with this document. subpage: Option<SubpageId>, /// The target event loop for the response notifications. - script_chan: Box<ScriptChan+Send>, + script_chan: Box<ScriptChan + Send>, /// The URL for this document. url: Url, } impl ParserContext { - pub fn new(id: PipelineId, subpage: Option<SubpageId>, script_chan: Box<ScriptChan+Send>, + pub fn new(id: PipelineId, subpage: Option<SubpageId>, script_chan: Box<ScriptChan + Send>, url: Url) -> ParserContext { ParserContext { parser: RefCell::new(None), @@ -268,7 +268,7 @@ impl ServoHTMLParser { } #[inline] - pub fn tokenizer<'a>(&'a self) -> &'a DOMRefCell<Tokenizer> { + pub fn tokenizer(&self) -> &DOMRefCell<Tokenizer> { &self.tokenizer } } diff --git a/components/script/dom/storage.rs b/components/script/dom/storage.rs index 4aced1a1029..7231d10247d 100644 --- a/components/script/dom/storage.rs +++ b/components/script/dom/storage.rs @@ -144,7 +144,7 @@ trait PrivateStorageHelpers { impl<'a> PrivateStorageHelpers for &'a Storage { /// https://html.spec.whatwg.org/multipage/#send-a-storage-notification fn broadcast_change_notification(self, key: Option<DOMString>, old_value: Option<DOMString>, - new_value: Option<DOMString>){ + new_value: Option<DOMString>) { let global_root = self.global.root(); let global_ref = global_root.r(); let main_script_chan = global_ref.as_window().main_thread_script_chan(); diff --git a/components/script/dom/textencoder.rs b/components/script/dom/textencoder.rs index 29a715a8ed1..1b76de05d0d 100644 --- a/components/script/dom/textencoder.rs +++ b/components/script/dom/textencoder.rs @@ -65,7 +65,7 @@ impl TextEncoder { } _ => { debug!("Encoding Not UTF"); - return Err(Range("The encoding must be utf-8, utf-16le, or utf-16be.".to_owned())) + Err(Range("The encoding must be utf-8, utf-16le, or utf-16be.".to_owned())) } } } @@ -87,7 +87,7 @@ impl<'a> TextEncoderMethods for &'a TextEncoder { let js_object_data: *mut uint8_t = JS_GetUint8ArrayData(js_object, ptr::null()); ptr::copy_nonoverlapping(encoded.as_ptr(), js_object_data, length as usize); - return js_object; + js_object } } } diff --git a/components/script/dom/treewalker.rs b/components/script/dom/treewalker.rs index b859a2f0277..b8271909505 100644 --- a/components/script/dom/treewalker.rs +++ b/components/script/dom/treewalker.rs @@ -104,12 +104,9 @@ impl<'a> TreeWalkerMethods for &'a TreeWalker { node = n; // "2. If node is not null and filtering node returns FILTER_ACCEPT, // then set the currentNode attribute to node, return node." - match try!(self.accept_node(node.r())) { - NodeFilterConstants::FILTER_ACCEPT => { - self.current_node.set(JS::from_rooted(&node)); - return Ok(Some(node)) - }, - _ => {} + if NodeFilterConstants::FILTER_ACCEPT == try!(self.accept_node(node.r())) { + self.current_node.set(JS::from_rooted(&node)); + return Ok(Some(node)) } }, None => break, @@ -195,12 +192,9 @@ impl<'a> TreeWalkerMethods for &'a TreeWalker { } // "5. Filter node and if the return value is FILTER_ACCEPT, then // set the currentNode attribute to node and return node." - match try!(self.accept_node(node.r())) { - NodeFilterConstants::FILTER_ACCEPT => { - self.current_node.set(JS::from_rooted(&node)); - return Ok(Some(node)) - }, - _ => {} + if NodeFilterConstants::FILTER_ACCEPT == try!(self.accept_node(node.r())) { + self.current_node.set(JS::from_rooted(&node)); + return Ok(Some(node)) } } // "6. Return null." @@ -217,9 +211,8 @@ impl<'a> TreeWalkerMethods for &'a TreeWalker { loop { // "1. While result is not FILTER_REJECT and node has a child, run these subsubsteps:" loop { - match result { - NodeFilterConstants::FILTER_REJECT => break, - _ => {} + if NodeFilterConstants::FILTER_REJECT == result { + break; } match node.r().GetFirstChild() { None => break, @@ -230,12 +223,9 @@ impl<'a> TreeWalkerMethods for &'a TreeWalker { result = try!(self.accept_node(node.r())); // "3. If result is FILTER_ACCEPT, then // set the currentNode attribute to node and return node." - match result { - NodeFilterConstants::FILTER_ACCEPT => { - self.current_node.set(JS::from_rooted(&node)); - return Ok(Some(node)) - }, - _ => {} + if NodeFilterConstants::FILTER_ACCEPT == result { + self.current_node.set(JS::from_rooted(&node)); + return Ok(Some(node)) } } } @@ -251,12 +241,9 @@ impl<'a> TreeWalkerMethods for &'a TreeWalker { result = try!(self.accept_node(node.r())); // "4. If result is FILTER_ACCEPT, then // set the currentNode attribute to node and return node." - match result { - NodeFilterConstants::FILTER_ACCEPT => { - self.current_node.set(JS::from_rooted(&node)); - return Ok(Some(node)) - }, - _ => {} + if NodeFilterConstants::FILTER_ACCEPT == result { + self.current_node.set(JS::from_rooted(&node)); + return Ok(Some(node)) } } } @@ -391,13 +378,11 @@ impl<'a> PrivateTreeWalkerHelpers for &'a TreeWalker { let result = try!(self.accept_node(node.r())); // "3. If result is FILTER_ACCEPT, then set the currentNode // attribute to node and return node." - match result { - NodeFilterConstants::FILTER_ACCEPT => { - self.current_node.set(JS::from_rooted(&node)); - return Ok(Some(node)) - }, - _ => {} + if NodeFilterConstants::FILTER_ACCEPT == result { + self.current_node.set(JS::from_rooted(&node)); + return Ok(Some(node)) } + // "4. Set sibling to node's first child if type is next, // and node's last child if type is previous." sibling_op = next_child(node.r()); @@ -418,9 +403,8 @@ impl<'a> PrivateTreeWalkerHelpers for &'a TreeWalker { // "5. Filter node and if the return value is FILTER_ACCEPT, then return null." Some(n) => { node = n; - match try!(self.accept_node(node.r())) { - NodeFilterConstants::FILTER_ACCEPT => return Ok(None), - _ => {} + if NodeFilterConstants::FILTER_ACCEPT == try!(self.accept_node(node.r())) { + return Ok(None) } } } diff --git a/components/script/dom/url.rs b/components/script/dom/url.rs index 9bbd0f1b5fc..d4a8b5a23ff 100644 --- a/components/script/dom/url.rs +++ b/components/script/dom/url.rs @@ -142,7 +142,7 @@ impl<'a> URLMethods for &'a URL { } } -fn parser_with_base<'a>(base: Option<&'a Url>) -> UrlParser<'a> { +fn parser_with_base(base: Option<&Url>) -> UrlParser { let mut parser = UrlParser::new(); if let Some(base) = base { parser.base_url(base); diff --git a/components/script/dom/urlhelper.rs b/components/script/dom/urlhelper.rs index cff468574b2..4376a85e390 100644 --- a/components/script/dom/urlhelper.rs +++ b/components/script/dom/urlhelper.rs @@ -84,7 +84,7 @@ impl UrlHelper { if urlA.port() != urlB.port() { return false } - return true + true } // https://url.spec.whatwg.org/#dom-urlutils-search diff --git a/components/script/dom/virtualmethods.rs b/components/script/dom/virtualmethods.rs index b67cbb69d4f..437f39422c6 100644 --- a/components/script/dom/virtualmethods.rs +++ b/components/script/dom/virtualmethods.rs @@ -48,7 +48,7 @@ use string_cache::Atom; pub trait VirtualMethods { /// Returns self as the superclass of the implementation for this trait, /// if any. - fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods>; + fn super_type(&self) -> Option<&VirtualMethods>; /// Called when changing or adding attributes, after the attribute's value /// has been updated. diff --git a/components/script/dom/webglactiveinfo.rs b/components/script/dom/webglactiveinfo.rs index 671c50c5d36..3bbcfd7dee2 100644 --- a/components/script/dom/webglactiveinfo.rs +++ b/components/script/dom/webglactiveinfo.rs @@ -7,7 +7,7 @@ use dom::bindings::codegen::Bindings::WebGLActiveInfoBinding; use dom::bindings::codegen::Bindings::WebGLActiveInfoBinding::WebGLActiveInfoMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; -use dom::bindings::utils::{Reflector,reflect_dom_object}; +use dom::bindings::utils::{Reflector, reflect_dom_object}; use util::str::DOMString; #[dom_struct] diff --git a/components/script/dom/webglrenderingcontext.rs b/components/script/dom/webglrenderingcontext.rs index 0b6fa7b3869..4acf36256c8 100644 --- a/components/script/dom/webglrenderingcontext.rs +++ b/components/script/dom/webglrenderingcontext.rs @@ -514,15 +514,13 @@ impl<'a> WebGLRenderingContextMethods for &'a WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn VertexAttribPointer(self, attrib_id: u32, size: i32, data_type: u32, normalized: bool, stride: i32, offset: i64) { - match data_type { - constants::FLOAT => { - let msg = CanvasMsg::WebGL( - CanvasWebGLMsg::VertexAttribPointer2f(attrib_id, size, normalized, stride, offset)); - self.ipc_renderer.send(msg).unwrap() - } - _ => panic!("VertexAttribPointer: Data Type not supported") + if let constants::FLOAT = data_type { + let msg = CanvasMsg::WebGL( + CanvasWebGLMsg::VertexAttribPointer2f(attrib_id, size, normalized, stride, offset)); + self.ipc_renderer.send(msg).unwrap() + } else { + panic!("VertexAttribPointer: Data Type not supported") } - } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.4 diff --git a/components/script/dom/webglshaderprecisionformat.rs b/components/script/dom/webglshaderprecisionformat.rs index 17c3ce97a8c..5c7d4232b88 100644 --- a/components/script/dom/webglshaderprecisionformat.rs +++ b/components/script/dom/webglshaderprecisionformat.rs @@ -7,7 +7,7 @@ use dom::bindings::codegen::Bindings::WebGLShaderPrecisionFormatBinding; use dom::bindings::codegen::Bindings::WebGLShaderPrecisionFormatBinding::WebGLShaderPrecisionFormatMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; -use dom::bindings::utils::{Reflector,reflect_dom_object}; +use dom::bindings::utils::{Reflector, reflect_dom_object}; #[dom_struct] #[derive(HeapSizeOf)] diff --git a/components/script/dom/webgluniformlocation.rs b/components/script/dom/webgluniformlocation.rs index d7f7c836706..add5da9f928 100644 --- a/components/script/dom/webgluniformlocation.rs +++ b/components/script/dom/webgluniformlocation.rs @@ -6,7 +6,7 @@ use dom::bindings::codegen::Bindings::WebGLUniformLocationBinding; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; -use dom::bindings::utils::{Reflector,reflect_dom_object}; +use dom::bindings::utils::{Reflector, reflect_dom_object}; #[dom_struct] #[derive(HeapSizeOf)] diff --git a/components/script/dom/websocket.rs b/components/script/dom/websocket.rs index 61e8b09474d..1e00a9e507a 100644 --- a/components/script/dom/websocket.rs +++ b/components/script/dom/websocket.rs @@ -153,7 +153,7 @@ impl WebSocket { return Err(Syntax); } - if protocols[i+1..].iter().any(|p| p == protocol) { + if protocols[i + 1..].iter().any(|p| p == protocol) { return Err(Syntax); } @@ -277,7 +277,7 @@ impl<'a> WebSocketMethods for &'a WebSocket { let mut other_sender = self.sender.borrow_mut(); let my_sender = other_sender.as_mut().unwrap(); let _ = my_sender.lock().unwrap().send_message(Message::Text(data.unwrap().0)); - return Ok(()) + Ok(()) } // https://html.spec.whatwg.org/multipage/#dom-websocket-close diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 6f7b23adf13..82e3247dc8e 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -52,7 +52,7 @@ use profile_traits::mem; use string_cache::Atom; use util::geometry::{self, Au, MAX_RECT}; use util::{breakpoint, opts}; -use util::str::{DOMString,HTML_SPACE_CHARACTERS}; +use util::str::{DOMString, HTML_SPACE_CHARACTERS}; use euclid::{Point2D, Rect, Size2D}; use ipc_channel::ipc::IpcSender; @@ -68,7 +68,7 @@ use libc; use rustc_serialize::base64::{FromBase64, ToBase64, STANDARD}; use std::ascii::AsciiExt; use std::borrow::ToOwned; -use std::cell::{Cell, Ref, RefMut, RefCell}; +use std::cell::{Cell, Ref, RefCell}; use std::collections::HashSet; use std::default::Default; use std::ffi::CString; @@ -121,7 +121,7 @@ pub struct Window { #[ignore_heap_size_of = "channels are hard"] image_cache_chan: ImageCacheChan, #[ignore_heap_size_of = "TODO(#6911) newtypes containing unmeasurable types are hard"] - compositor: DOMRefCell<IpcSender<ScriptToCompositorMsg>>, + compositor: IpcSender<ScriptToCompositorMsg>, browsing_context: DOMRefCell<Option<BrowsingContext>>, page: Rc<Page>, performance: MutNullableHeap<JS<Performance>>, @@ -179,7 +179,7 @@ pub struct Window { /// A handle to perform RPC calls into the layout, quickly. #[ignore_heap_size_of = "trait objects are hard"] - layout_rpc: Box<LayoutRPC+'static>, + layout_rpc: Box<LayoutRPC + 'static>, /// The port that we will use to join layout. If this is `None`, then layout is not running. #[ignore_heap_size_of = "channels are hard"] @@ -232,7 +232,7 @@ impl Window { self.js_runtime.borrow().as_ref().unwrap().cx() } - pub fn script_chan(&self) -> Box<ScriptChan+Send> { + pub fn script_chan(&self) -> Box<ScriptChan + Send> { self.script_chan.clone() } @@ -264,24 +264,24 @@ impl Window { self.parent_info } - pub fn new_script_pair(&self) -> (Box<ScriptChan+Send>, Box<ScriptPort+Send>) { + pub fn new_script_pair(&self) -> (Box<ScriptChan + Send>, Box<ScriptPort + Send>) { let (tx, rx) = channel(); (box SendableMainThreadScriptChan(tx), box rx) } - pub fn image_cache_task<'a>(&'a self) -> &'a ImageCacheTask { + pub fn image_cache_task(&self) -> &ImageCacheTask { &self.image_cache_task } - pub fn compositor<'a>(&'a self) -> RefMut<'a, IpcSender<ScriptToCompositorMsg>> { - self.compositor.borrow_mut() + pub fn compositor(&self) -> &IpcSender<ScriptToCompositorMsg> { + &self.compositor } - pub fn browsing_context<'a>(&'a self) -> Ref<'a, Option<BrowsingContext>> { + pub fn browsing_context(&self) -> Ref<Option<BrowsingContext>> { self.browsing_context.borrow() } - pub fn page<'a>(&'a self) -> &'a Page { + pub fn page(&self) -> &Page { &*self.page } @@ -1099,7 +1099,7 @@ impl Window { control_chan: control_chan, console: Default::default(), crypto: Default::default(), - compositor: DOMRefCell::new(compositor), + compositor: compositor, page: page, navigator: Default::default(), image_cache_task: image_cache_task, @@ -1143,7 +1143,7 @@ impl Window { } } -fn should_move_clip_rect(clip_rect: Rect<Au>, new_viewport: Rect<f32>) -> bool{ +fn should_move_clip_rect(clip_rect: Rect<Au>, new_viewport: Rect<f32>) -> bool { let clip_rect = Rect::new(Point2D::new(clip_rect.origin.x.to_f32_px(), clip_rect.origin.y.to_f32_px()), Size2D::new(clip_rect.size.width.to_f32_px(), diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 80eee7bd3ad..468de091271 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -143,11 +143,11 @@ impl WorkerGlobalScope { self.runtime.cx() } - pub fn resource_task<'a>(&'a self) -> &'a ResourceTask { + pub fn resource_task(&self) -> &ResourceTask { &self.resource_task } - pub fn get_url<'a>(&'a self) -> &'a Url { + pub fn get_url(&self) -> &Url { &self.worker_url } @@ -179,7 +179,7 @@ impl<'a> WorkerGlobalScopeMethods for &'a WorkerGlobalScope { // https://html.spec.whatwg.org/multipage/#dom-workerglobalscope-importscripts fn ImportScripts(self, url_strings: Vec<DOMString>) -> ErrorResult { let mut urls = Vec::with_capacity(url_strings.len()); - for url in url_strings.into_iter() { + for url in url_strings { let url = UrlParser::new().base_url(&self.worker_url) .parse(&url); match url { @@ -188,7 +188,7 @@ impl<'a> WorkerGlobalScopeMethods for &'a WorkerGlobalScope { }; } - for url in urls.into_iter() { + for url in urls { let (url, source) = match load_whole_resource(&self.resource_task, url) { Err(_) => return Err(Network), Ok((metadata, bytes)) => { @@ -288,9 +288,9 @@ impl<'a> WorkerGlobalScopeMethods for &'a WorkerGlobalScope { pub trait WorkerGlobalScopeHelpers { fn execute_script(self, source: DOMString); fn handle_fire_timer(self, timer_id: TimerId); - fn script_chan(self) -> Box<ScriptChan+Send>; + fn script_chan(self) -> Box<ScriptChan + Send>; fn pipeline(self) -> PipelineId; - fn new_script_pair(self) -> (Box<ScriptChan+Send>, Box<ScriptPort+Send>); + fn new_script_pair(self) -> (Box<ScriptChan + Send>, Box<ScriptPort + Send>); fn process_event(self, msg: CommonScriptMsg); fn get_cx(self) -> *mut JSContext; fn set_devtools_wants_updates(self, value: bool); @@ -311,7 +311,7 @@ impl<'a> WorkerGlobalScopeHelpers for &'a WorkerGlobalScope { } } - fn script_chan(self) -> Box<ScriptChan+Send> { + fn script_chan(self) -> Box<ScriptChan + Send> { let dedicated = DedicatedWorkerGlobalScopeCast::to_ref(self); match dedicated { @@ -329,7 +329,7 @@ impl<'a> WorkerGlobalScopeHelpers for &'a WorkerGlobalScope { } } - fn new_script_pair(self) -> (Box<ScriptChan+Send>, Box<ScriptPort+Send>) { + fn new_script_pair(self) -> (Box<ScriptChan + Send>, Box<ScriptPort + Send>) { let dedicated = DedicatedWorkerGlobalScopeCast::to_ref(self); match dedicated { diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index efb42f3c1a0..577416fe700 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -148,7 +148,7 @@ pub struct XMLHttpRequest { timeout_cancel: DOMRefCell<Option<Sender<()>>>, fetch_time: Cell<i64>, #[ignore_heap_size_of = "Cannot calculate Heap size"] - timeout_target: DOMRefCell<Option<Box<ScriptChan+Send>>>, + timeout_target: DOMRefCell<Option<Box<ScriptChan + Send>>>, generation_id: Cell<GenerationId>, response_status: Cell<Result<(), ()>>, } @@ -201,13 +201,13 @@ impl XMLHttpRequest { fn check_cors(context: Arc<Mutex<XHRContext>>, load_data: LoadData, req: CORSRequest, - script_chan: Box<ScriptChan+Send>, + script_chan: Box<ScriptChan + Send>, resource_task: ResourceTask) { struct CORSContext { xhr: Arc<Mutex<XHRContext>>, load_data: RefCell<Option<LoadData>>, req: CORSRequest, - script_chan: Box<ScriptChan+Send>, + script_chan: Box<ScriptChan + Send>, resource_task: ResourceTask, } @@ -244,7 +244,7 @@ impl XMLHttpRequest { } fn initiate_async_xhr(context: Arc<Mutex<XHRContext>>, - script_chan: Box<ScriptChan+Send>, + script_chan: Box<ScriptChan + Send>, resource_task: ResourceTask, load_data: LoadData) { impl AsyncResponseListener for XHRContext { @@ -761,7 +761,7 @@ trait PrivateXMLHttpRequestHelpers { fn dispatch_upload_progress_event(self, type_: DOMString, partial_load: Option<u64>); fn dispatch_response_progress_event(self, type_: DOMString); fn text_response(self) -> DOMString; - fn set_timeout(self, timeout:u32); + fn set_timeout(self, timeout: u32); fn cancel_timeout(self); fn filter_response_headers(self) -> Headers; fn discard_subsequent_responses(self); @@ -784,19 +784,17 @@ impl<'a> PrivateXMLHttpRequestHelpers for &'a XMLHttpRequest { fn process_headers_available(self, cors_request: Option<CORSRequest>, gen_id: GenerationId, metadata: Metadata) -> Result<(), Error> { - match cors_request { - Some(ref req) => { - match metadata.headers { - Some(ref h) if allow_cross_origin_request(req, h) => {}, - _ => { - self.process_partial_response(XHRProgress::Errored(gen_id, Network)); - return Err(Network); - } + + if let Some(ref req) = cors_request { + match metadata.headers { + Some(ref h) if allow_cross_origin_request(req, h) => {}, + _ => { + self.process_partial_response(XHRProgress::Errored(gen_id, Network)); + return Err(Network); } - }, + } + } - _ => {} - }; // XXXManishearth Clear cache entries in case of a network error self.process_partial_response(XHRProgress::HeadersReceived(gen_id, metadata.headers, diff --git a/components/script/dom/xmlhttprequesteventtarget.rs b/components/script/dom/xmlhttprequesteventtarget.rs index af4b8b8bc50..3bf1aa408b0 100644 --- a/components/script/dom/xmlhttprequesteventtarget.rs +++ b/components/script/dom/xmlhttprequesteventtarget.rs @@ -28,7 +28,7 @@ impl XMLHttpRequestEventTarget { } #[inline] - pub fn eventtarget<'a>(&'a self) -> &'a EventTarget { + pub fn eventtarget(&self) -> &EventTarget { &self.eventtarget } } @@ -43,7 +43,7 @@ impl XMLHttpRequestEventTargetDerived for EventTarget { } impl<'a> XMLHttpRequestEventTargetMethods for &'a XMLHttpRequestEventTarget { - event_handler!(loadstart,GetOnloadstart, SetOnloadstart); + event_handler!(loadstart, GetOnloadstart, SetOnloadstart); event_handler!(progress, GetOnprogress, SetOnprogress); event_handler!(abort, GetOnabort, SetOnabort); event_handler!(error, GetOnerror, SetOnerror); diff --git a/components/script/layout_interface.rs b/components/script/layout_interface.rs index 53ab48a7769..8a93faa8fe2 100644 --- a/components/script/layout_interface.rs +++ b/components/script/layout_interface.rs @@ -39,7 +39,7 @@ pub enum Msg { AddStylesheet(Stylesheet, MediaQueryList), /// Adds the given stylesheet to the document. - LoadStylesheet(Url, MediaQueryList, PendingAsyncLoad, Box<StylesheetLoadResponder+Send>), + LoadStylesheet(Url, MediaQueryList, PendingAsyncLoad, Box<StylesheetLoadResponder + Send>), /// Puts a document into quirks mode, causing the quirks mode stylesheet to be loaded. SetQuirksMode, @@ -199,7 +199,7 @@ pub trait ScriptLayoutChan { impl ScriptLayoutChan for OpaqueScriptLayoutChannel { fn new(sender: Sender<Msg>, receiver: Receiver<Msg>) -> OpaqueScriptLayoutChannel { - let inner = (box sender as Box<Any+Send>, box receiver as Box<Any+Send>); + let inner = (box sender as Box<Any + Send>, box receiver as Box<Any + Send>); OpaqueScriptLayoutChannel(inner) } diff --git a/components/script/network_listener.rs b/components/script/network_listener.rs index 2f8bc522347..e8b2e9f59ba 100644 --- a/components/script/network_listener.rs +++ b/components/script/network_listener.rs @@ -10,7 +10,7 @@ use std::sync::{Arc, Mutex}; /// a target thread, where they are invoked on the provided context object. pub struct NetworkListener<T: AsyncResponseListener + PreInvoke + Send + 'static> { pub context: Arc<Mutex<T>>, - pub script_chan: Box<ScriptChan+Send>, + pub script_chan: Box<ScriptChan + Send>, } impl<T: AsyncResponseListener + PreInvoke + Send + 'static> NetworkListener<T> { diff --git a/components/script/page.rs b/components/script/page.rs index f4b3fd6cd18..cea63c08a38 100644 --- a/components/script/page.rs +++ b/components/script/page.rs @@ -46,7 +46,7 @@ impl IterablePage for Rc<Page> { } fn find(&self, id: PipelineId) -> Option<Rc<Page>> { if self.id == id { return Some(self.clone()); } - for page in self.children.borrow().iter() { + for page in &*self.children.borrow() { let found = page.find(id); if found.is_some() { return found; } } @@ -104,7 +104,7 @@ impl Iterator for PageIterator { fn next(&mut self) -> Option<Rc<Page>> { match self.stack.pop() { Some(next) => { - for child in next.children.borrow().iter() { + for child in &*next.children.borrow() { self.stack.push(child.clone()); } Some(next) diff --git a/components/script/parse/html.rs b/components/script/parse/html.rs index 6ea2dc443f8..cd4e6dd1d47 100644 --- a/components/script/parse/html.rs +++ b/components/script/parse/html.rs @@ -90,7 +90,7 @@ impl<'a> TreeSink for servohtmlparser::Sink { let elem = Element::create(name, None, doc.r(), ElementCreator::ParserCreated); - for attr in attrs.into_iter() { + for attr in attrs { elem.r().set_attribute_from_parser(attr.name, attr.value.into(), None); } @@ -152,7 +152,7 @@ impl<'a> TreeSink for servohtmlparser::Sink { let node: Root<Node> = target.root(); let elem = ElementCast::to_ref(node.r()) .expect("tried to set attrs on non-Element in HTML parsing"); - for attr in attrs.into_iter() { + for attr in attrs { elem.set_attribute_from_parser(attr.name, attr.value.into(), None); } } diff --git a/components/script/script_task.rs b/components/script/script_task.rs index 0d9e935483a..8d342a9eaf5 100644 --- a/components/script/script_task.rs +++ b/components/script/script_task.rs @@ -32,8 +32,8 @@ use dom::bindings::js::{RootCollectionPtr, Root, RootedReference}; use dom::bindings::refcounted::{LiveDOMReferences, Trusted, TrustedReference, trace_refcounted_objects}; use dom::bindings::trace::{JSTraceable, trace_traceables, RootedVec}; use dom::bindings::utils::{WRAP_CALLBACKS, DOM_CALLBACKS}; -use dom::document::{Document, IsHTMLDocument, DocumentHelpers, DocumentProgressHandler, - DocumentProgressTask, DocumentSource, MouseEventType}; +use dom::document::{Document, IsHTMLDocument, DocumentHelpers, DocumentProgressHandler}; +use dom::document::{DocumentProgressTask, DocumentSource, MouseEventType}; use dom::element::{Element, AttributeHandlers}; use dom::event::{EventHelpers, EventBubbles, EventCancelable}; use dom::htmliframeelement::HTMLIFrameElementHelpers; @@ -190,7 +190,7 @@ pub enum CommonScriptMsg { /// A DOM object's last pinned reference was removed (dispatched to all tasks). RefcountCleanup(TrustedReference), /// Generic message that encapsulates event handling. - RunnableMsg(Box<Runnable+Send>), + RunnableMsg(Box<Runnable + Send>), } /// Messages used to control the script event loop @@ -203,7 +203,7 @@ pub enum MainThreadScriptMsg { /// should be closed (only dispatched to ScriptTask). ExitWindow(PipelineId), /// Generic message for running tasks in the ScriptTask - MainThreadRunnableMsg(Box<MainThreadRunnable+Send>), + MainThreadRunnableMsg(Box<MainThreadRunnable + Send>), /// Begins a content-initiated load on the specified pipeline (only /// dispatched to ScriptTask). Navigate(PipelineId, LoadData), @@ -214,10 +214,10 @@ pub trait ScriptChan { /// Send a message to the associated event loop. fn send(&self, msg: CommonScriptMsg) -> Result<(), ()>; /// Clone this handle. - fn clone(&self) -> Box<ScriptChan+Send>; + fn clone(&self) -> Box<ScriptChan + Send>; } -impl OpaqueSender<CommonScriptMsg> for Box<ScriptChan+Send> { +impl OpaqueSender<CommonScriptMsg> for Box<ScriptChan + Send> { fn send(&self, msg: CommonScriptMsg) { ScriptChan::send(&**self, msg).unwrap(); } @@ -267,10 +267,10 @@ pub struct SendableMainThreadScriptChan(pub Sender<CommonScriptMsg>); impl ScriptChan for SendableMainThreadScriptChan { fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> { let SendableMainThreadScriptChan(ref chan) = *self; - return chan.send(msg).map_err(|_| ()); + chan.send(msg).map_err(|_| ()) } - fn clone(&self) -> Box<ScriptChan+Send> { + fn clone(&self) -> Box<ScriptChan + Send> { let SendableMainThreadScriptChan(ref chan) = *self; box SendableMainThreadScriptChan((*chan).clone()) } @@ -294,7 +294,7 @@ impl ScriptChan for MainThreadScriptChan { return chan.send(MainThreadScriptMsg::Common(msg)).map_err(|_| ()); } - fn clone(&self) -> Box<ScriptChan+Send> { + fn clone(&self) -> Box<ScriptChan + Send> { let MainThreadScriptChan(ref chan) = *self; box MainThreadScriptChan((*chan).clone()) } @@ -436,8 +436,8 @@ impl ScriptTaskFactory for ScriptTask { ScriptLayoutChan::new(chan, port) } - fn clone_layout_channel(_phantom: Option<&mut ScriptTask>, pair: &OpaqueScriptLayoutChannel) -> Box<Any+Send> { - box pair.sender() as Box<Any+Send> + fn clone_layout_channel(_phantom: Option<&mut ScriptTask>, pair: &OpaqueScriptLayoutChannel) -> Box<Any + Send> { + box pair.sender() as Box<Any + Send> } fn create(_phantom: Option<&mut ScriptTask>, @@ -550,7 +550,7 @@ unsafe extern "C" fn debug_gc_callback(_rt: *mut JSRuntime, status: JSGCStatus, unsafe extern "C" fn shadow_check_callback(_cx: *mut JSContext, _object: HandleObject, _id: HandleId) -> DOMProxyShadowsResult { // XXX implement me - return DOMProxyShadowsResult::ShadowCheckFailed; + DOMProxyShadowsResult::ShadowCheckFailed } impl ScriptTask { @@ -709,7 +709,7 @@ impl ScriptTask { } } - for (id, size) in resizes.into_iter() { + for (id, size) in resizes { self.handle_event(id, ResizeEvent(size)); } @@ -814,7 +814,7 @@ impl ScriptTask { } // Process the gathered events. - for msg in sequential.into_iter() { + for msg in sequential { match msg { MixedMessage::FromConstellation(ConstellationControlMsg::ExitPipeline(id, exit_type)) => { if self.handle_exit_pipeline_msg(id, exit_type) { @@ -1062,7 +1062,7 @@ impl ScriptTask { return ScriptState::DocumentLoading; } - return ScriptState::DocumentLoaded; + ScriptState::DocumentLoaded } fn handle_new_layout(&self, new_layout_info: NewLayoutInfo) { @@ -1188,23 +1188,26 @@ impl ScriptTask { let mut urls = vec![]; let mut dom_tree_size = 0; let mut reports = vec![]; - for it_page in self.root_page().iter() { - let current_url = it_page.document().url().serialize(); - urls.push(current_url.clone()); - for child in NodeCast::from_ref(&*it_page.document()).traverse_preorder() { - let target = EventTargetCast::from_ref(&*child); + if let Some(root_page) = self.page.borrow().as_ref() { + for it_page in root_page.iter() { + let current_url = it_page.document().url().serialize(); + urls.push(current_url.clone()); + + for child in NodeCast::from_ref(&*it_page.document()).traverse_preorder() { + let target = EventTargetCast::from_ref(&*child); + dom_tree_size += heap_size_of_eventtarget(target); + } + let window = it_page.window(); + let target = EventTargetCast::from_ref(&*window); dom_tree_size += heap_size_of_eventtarget(target); + + reports.push(Report { + path: path![format!("url({})", current_url), "dom-tree"], + kind: ReportKind::ExplicitJemallocHeapSize, + size: dom_tree_size, + }) } - let window = it_page.window(); - let target = EventTargetCast::from_ref(&*window); - dom_tree_size += heap_size_of_eventtarget(target); - - reports.push(Report { - path: path![format!("url({})", current_url), "dom-tree"], - kind: ReportKind::ExplicitJemallocHeapSize, - size: dom_tree_size, - }) } let path_seg = format!("url({})", urls.join(", ")); reports.extend(ScriptTask::get_reports(self.get_cx(), path_seg)); @@ -1403,7 +1406,7 @@ impl ScriptTask { if let Some(ref mut child_page) = page.remove(id) { shut_down_layout(&*child_page, exit_type); } - return false; + false } /// Handles when layout task finishes all animation in one tick @@ -1547,7 +1550,7 @@ impl ScriptTask { DocumentSource::FromParser, loader); - let frame_element = frame_element.r().map(|elem| ElementCast::from_ref(elem)); + let frame_element = frame_element.r().map(ElementCast::from_ref); window.r().init_browsing_context(document.r(), frame_element); // Create the root frame @@ -1649,7 +1652,7 @@ impl ScriptTask { let document = page.document(); let mut prev_mouse_over_targets: RootedVec<JS<Node>> = RootedVec::new(); - for target in self.mouse_over_targets.borrow_mut().iter() { + for target in &*self.mouse_over_targets.borrow_mut() { prev_mouse_over_targets.push(target.clone()); } @@ -1660,7 +1663,7 @@ impl ScriptTask { document.r().handle_mouse_move_event(self.js_runtime.rt(), point, &mut mouse_over_targets); // Notify Constellation about anchors that are no longer mouse over targets. - for target in prev_mouse_over_targets.iter() { + for target in &*prev_mouse_over_targets { if !mouse_over_targets.contains(target) { if target.root().r().is_anchor_element() { let event = ConstellationMsg::NodeStatus(None); @@ -1672,7 +1675,7 @@ impl ScriptTask { } // Notify Constellation about the topmost anchor mouse over target. - for target in mouse_over_targets.iter() { + for target in &*mouse_over_targets { let target = target.root(); if target.r().is_anchor_element() { let element = ElementCast::to_ref(target.r()).unwrap(); @@ -1933,7 +1936,7 @@ fn shut_down_layout(page_tree: &Rc<Page>, exit_type: PipelineExitType) { } // Destroy the layout task. If there were node leaks, layout will now crash safely. - for chan in channels.into_iter() { + for chan in channels { chan.send(layout_interface::Msg::ExitNow(exit_type)).ok(); } } diff --git a/components/script/textinput.rs b/components/script/textinput.rs index 31fc7dc2e25..5ecf6a4f312 100644 --- a/components/script/textinput.rs +++ b/components/script/textinput.rs @@ -292,10 +292,11 @@ impl<T: ClipboardProvider> TextInput<T> { /// Deal with a newline input. pub fn handle_return(&mut self) -> KeyReaction { if !self.multiline { - return KeyReaction::TriggerDefaultAction; + KeyReaction::TriggerDefaultAction + } else { + self.insert_char('\n'); + KeyReaction::DispatchInput } - self.insert_char('\n'); - return KeyReaction::DispatchInput; } /// Select all text in the input control. diff --git a/components/script/timers.rs b/components/script/timers.rs index 8ed64c32d83..8cc317f83ac 100644 --- a/components/script/timers.rs +++ b/components/script/timers.rs @@ -83,7 +83,7 @@ pub struct TimerManager { impl Drop for TimerManager { fn drop(&mut self) { - for (_, timer_handle) in self.active_timers.borrow_mut().iter_mut() { + for (_, timer_handle) in &mut *self.active_timers.borrow_mut() { timer_handle.cancel(); } } @@ -125,12 +125,12 @@ impl TimerManager { } pub fn suspend(&self) { - for (_, timer_handle) in self.active_timers.borrow_mut().iter_mut() { + for (_, timer_handle) in &mut *self.active_timers.borrow_mut() { timer_handle.suspend(); } } pub fn resume(&self) { - for (_, timer_handle) in self.active_timers.borrow_mut().iter_mut() { + for (_, timer_handle) in &mut *self.active_timers.borrow_mut() { timer_handle.resume(); } } @@ -142,7 +142,7 @@ impl TimerManager { timeout: i32, is_interval: IsInterval, source: TimerSource, - script_chan: Box<ScriptChan+Send>) + script_chan: Box<ScriptChan + Send>) -> i32 { let duration_ms = cmp::max(0, timeout) as u32; let handle = self.next_timer_handle.get(); @@ -222,8 +222,8 @@ impl TimerManager { for _ in 0..arguments.len() { timer.data.args.push(Heap::default()); } - for i in 0..arguments.len() { - timer.data.args.get_mut(i).unwrap().set(arguments[i].get()); + for (i, item) in arguments.iter().enumerate() { + timer.data.args.get_mut(i).unwrap().set(item.get()); } handle } diff --git a/components/script_traits/lib.rs b/components/script_traits/lib.rs index 637c61f7444..085c9a3f8fc 100644 --- a/components/script_traits/lib.rs +++ b/components/script_traits/lib.rs @@ -135,7 +135,7 @@ pub enum ConstellationControlMsg { /// Notifies script task that all animations are done TickAllAnimations(PipelineId), /// Notifies script that a stylesheet has finished loading. - StylesheetLoadComplete(PipelineId, Url, Box<StylesheetLoadResponder+Send>), + StylesheetLoadComplete(PipelineId, Url, Box<StylesheetLoadResponder + Send>), /// Get the current state of the script task for a given pipeline. GetCurrentState(Sender<ScriptState>, PipelineId), } @@ -169,7 +169,7 @@ pub enum CompositorEvent { /// An opaque wrapper around script<->layout channels to avoid leaking message types into /// crates that don't need to know about them. -pub struct OpaqueScriptLayoutChannel(pub (Box<Any+Send>, Box<Any+Send>)); +pub struct OpaqueScriptLayoutChannel(pub (Box<Any + Send>, Box<Any + Send>)); /// This trait allows creating a `ScriptTask` without depending on the `script` /// crate. @@ -195,5 +195,5 @@ pub trait ScriptTaskFactory { fn create_layout_channel(_phantom: Option<&mut Self>) -> OpaqueScriptLayoutChannel; /// Clone the `Sender` in `pair`. fn clone_layout_channel(_phantom: Option<&mut Self>, pair: &OpaqueScriptLayoutChannel) - -> Box<Any+Send>; + -> Box<Any + Send>; } diff --git a/components/servo/Cargo.lock b/components/servo/Cargo.lock index 76b71e38998..02a96a64acd 100644 --- a/components/servo/Cargo.lock +++ b/components/servo/Cargo.lock @@ -631,6 +631,14 @@ dependencies = [ ] [[package]] +name = "heapsize" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] name = "hpack" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -720,8 +728,9 @@ dependencies = [ [[package]] name = "js" version = "0.1.0" -source = "git+https://github.com/servo/rust-mozjs#e1a8c46045c698ed7c02c381334b9305a7088bbd" +source = "git+https://github.com/servo/rust-mozjs#85e4eff9936889436b24ceefd689d4467db302a9" dependencies = [ + "heapsize 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "mozjs_sys 0.0.0 (git+https://github.com/servo/mozjs)", diff --git a/components/servo/lib.rs b/components/servo/lib.rs index 9d3176a78d6..ae1a42ec92a 100644 --- a/components/servo/lib.rs +++ b/components/servo/lib.rs @@ -155,7 +155,7 @@ impl Browser { } fn create_constellation(opts: opts::Opts, - compositor_proxy: Box<CompositorProxy+Send>, + compositor_proxy: Box<CompositorProxy + Send>, time_profiler_chan: time::ProfilerChan, mem_profiler_chan: mem::ProfilerChan, devtools_chan: Option<Sender<devtools_traits::DevtoolsControlMsg>>, diff --git a/components/style/animation.rs b/components/style/animation.rs index 469c7c39ee9..438ec1683dd 100644 --- a/components/style/animation.rs +++ b/components/style/animation.rs @@ -378,7 +378,7 @@ impl Interpolate for Au { } } -impl <T> Interpolate for Option<T> where T:Interpolate { +impl <T> Interpolate for Option<T> where T: Interpolate { #[inline] fn interpolate(&self, other: &Option<T>, time: f64) -> Option<Option<T>> { match (self, other) { diff --git a/components/style/legacy.rs b/components/style/legacy.rs index dd751b161b3..c2e37731b89 100644 --- a/components/style/legacy.rs +++ b/components/style/legacy.rs @@ -32,14 +32,14 @@ pub trait PresentationalHintSynthesis { /// `common_style_affecting_attributes` or `rare_style_affecting_attributes` as appropriate. If /// you don't, you risk strange random nondeterministic failures due to false positives in /// style sharing. - fn synthesize_presentational_hints_for_legacy_attributes<E,V>( + fn synthesize_presentational_hints_for_legacy_attributes<E, V>( &self, element: &E, matching_rules_list: &mut V, shareable: &mut bool) where E: Element + TElementAttributes, V: VecLike<DeclarationBlock<Vec<PropertyDeclaration>>>; } impl PresentationalHintSynthesis for Stylist { - fn synthesize_presentational_hints_for_legacy_attributes<E,V>( + fn synthesize_presentational_hints_for_legacy_attributes<E, V>( &self, element: &E, matching_rules_list: &mut V, shareable: &mut bool) where E: Element + TElementAttributes, V: VecLike<DeclarationBlock<Vec<PropertyDeclaration>>> { diff --git a/components/style/properties.mako.rs b/components/style/properties.mako.rs index 953caa675b5..74776bdfd5c 100644 --- a/components/style/properties.mako.rs +++ b/components/style/properties.mako.rs @@ -5429,7 +5429,7 @@ pub mod shorthands { let results = try!(input.parse_comma_separated(parse_one_transition)); let (mut properties, mut durations) = (Vec::new(), Vec::new()); let (mut timing_functions, mut delays) = (Vec::new(), Vec::new()); - for result in results.into_iter() { + for result in results { properties.push(result.transition_property); durations.push(result.transition_duration); timing_functions.push(result.transition_timing_function); diff --git a/components/style/selector_matching.rs b/components/style/selector_matching.rs index 6aa016e67d1..666d8753b8c 100644 --- a/components/style/selector_matching.rs +++ b/components/style/selector_matching.rs @@ -200,7 +200,7 @@ impl Stylist { /// The returned boolean indicates whether the style is *shareable*; that is, whether the /// matched selectors are simple enough to allow the matching logic to be reduced to the logic /// in `css::matching::PrivateMatchMethods::candidate_element_allows_for_style_sharing`. - pub fn push_applicable_declarations<E,V>( + pub fn push_applicable_declarations<E, V>( &self, element: &E, parent_bf: Option<&BloomFilter>, diff --git a/components/style/stylesheets.rs b/components/style/stylesheets.rs index 3093f8e69c3..dbc72387853 100644 --- a/components/style/stylesheets.rs +++ b/components/style/stylesheets.rs @@ -10,8 +10,8 @@ use url::Url; use encoding::EncodingRef; -use cssparser::{Parser, decode_stylesheet_bytes, - QualifiedRuleParser, AtRuleParser, RuleListParser, AtRuleType}; +use cssparser::{Parser, decode_stylesheet_bytes, QualifiedRuleParser, AtRuleParser}; +use cssparser::{RuleListParser, AtRuleType}; use string_cache::{Atom, Namespace}; use selectors::parser::{Selector, parse_selector_list}; use parser::{ParserContext, log_css_error}; diff --git a/components/util/cache.rs b/components/util/cache.rs index 074f4514f35..86dc1c3af91 100644 --- a/components/util/cache.rs +++ b/components/util/cache.rs @@ -16,11 +16,11 @@ pub struct HashCache<K, V> { entries: HashMap<K, V, DefaultState<SipHasher>>, } -impl<K, V> HashCache<K,V> +impl<K, V> HashCache<K, V> where K: Clone + PartialEq + Eq + Hash, V: Clone, { - pub fn new() -> HashCache<K,V> { + pub fn new() -> HashCache<K, V> { HashCache { entries: HashMap::with_hash_state(<DefaultState<SipHasher> as Default>::default()), } @@ -58,7 +58,7 @@ pub struct LRUCache<K, V> { cache_size: usize, } -impl<K: Clone + PartialEq, V: Clone> LRUCache<K,V> { +impl<K: Clone + PartialEq, V: Clone> LRUCache<K, V> { pub fn new(size: usize) -> LRUCache<K, V> { LRUCache { entries: vec!(), @@ -76,7 +76,7 @@ impl<K: Clone + PartialEq, V: Clone> LRUCache<K,V> { self.entries[last_index].1.clone() } - pub fn iter<'a>(&'a self) -> Iter<'a,(K,V)> { + pub fn iter<'a>(&'a self) -> Iter<'a,(K, V)> { self.entries.iter() } @@ -110,14 +110,14 @@ impl<K: Clone + PartialEq, V: Clone> LRUCache<K,V> { } } -pub struct SimpleHashCache<K,V> { - entries: Vec<Option<(K,V)>>, +pub struct SimpleHashCache<K, V> { + entries: Vec<Option<(K, V)>>, k0: u64, k1: u64, } -impl<K:Clone+Eq+Hash,V:Clone> SimpleHashCache<K,V> { - pub fn new(cache_size: usize) -> SimpleHashCache<K,V> { +impl<K: Clone + Eq + Hash, V: Clone> SimpleHashCache<K, V> { + pub fn new(cache_size: usize) -> SimpleHashCache<K, V> { let mut r = rand::thread_rng(); SimpleHashCache { entries: vec![None; cache_size], @@ -132,7 +132,7 @@ impl<K:Clone+Eq+Hash,V:Clone> SimpleHashCache<K,V> { } #[inline] - fn bucket_for_key<Q:Hash>(&self, key: &Q) -> usize { + fn bucket_for_key<Q: Hash>(&self, key: &Q) -> usize { let mut hasher = SipHasher::new_with_keys(self.k0, self.k1); key.hash(&mut hasher); self.to_bucket(hasher.finish() as usize) diff --git a/components/util/geometry.rs b/components/util/geometry.rs index cefc82e53d6..12be3a64fbc 100644 --- a/components/util/geometry.rs +++ b/components/util/geometry.rs @@ -279,7 +279,7 @@ pub fn px_to_pt(px: f64) -> f64 { /// Returns true if the rect contains the given point. Points on the top or left sides of the rect /// are considered inside the rectangle, while points on the right or bottom sides of the rect are /// not considered inside the rectangle. -pub fn rect_contains_point<T:PartialOrd + Add<T, Output=T>>(rect: Rect<T>, point: Point2D<T>) -> bool { +pub fn rect_contains_point<T: PartialOrd + Add<T, Output=T>>(rect: Rect<T>, point: Point2D<T>) -> bool { point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width && point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height } diff --git a/components/util/ipc.rs b/components/util/ipc.rs index 7e47ff696f7..7f8e0e82eda 100644 --- a/components/util/ipc.rs +++ b/components/util/ipc.rs @@ -14,7 +14,7 @@ use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering}; use std::sync::mpsc::{self, Receiver, Sender}; lazy_static! { - static ref IN_PROCESS_SENDERS: Mutex<HashMap<usize,Box<Any + Send>>> = + static ref IN_PROCESS_SENDERS: Mutex<HashMap<usize, Box<Any + Send>>> = Mutex::new(HashMap::new()); } @@ -49,7 +49,7 @@ impl<T> Clone for OptionalIpcSender<T> where T: Deserialize + Serialize + Send + impl<T> Deserialize for OptionalIpcSender<T> where T: Deserialize + Serialize + Send + Any { fn deserialize<D>(deserializer: &mut D) - -> Result<OptionalIpcSender<T>,D::Error> where D: Deserializer { + -> Result<OptionalIpcSender<T>, D::Error> where D: Deserializer { if opts::get().multiprocess { return Ok(OptionalIpcSender::OutOfProcess(try!(Deserialize::deserialize( deserializer)))) @@ -66,7 +66,7 @@ impl<T> Deserialize for OptionalIpcSender<T> where T: Deserialize + Serialize + } impl<T> Serialize for OptionalIpcSender<T> where T: Deserialize + Serialize + Send + Any { - fn serialize<S>(&self, serializer: &mut S) -> Result<(),S::Error> where S: Serializer { + fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer { match *self { OptionalIpcSender::OutOfProcess(ref ipc_sender) => ipc_sender.serialize(serializer), OptionalIpcSender::InProcess(ref sender) => { diff --git a/components/util/logical_geometry.rs b/components/util/logical_geometry.rs index 95a3c3513f4..ff316e49d34 100644 --- a/components/util/logical_geometry.rs +++ b/components/util/logical_geometry.rs @@ -456,7 +456,7 @@ impl<T: Copy + Add<T, Output=T>> LogicalPoint<T> { } } -impl<T: Copy + Add<T,Output=T>> Add<LogicalSize<T>> for LogicalPoint<T> { +impl<T: Copy + Add<T, Output=T>> Add<LogicalSize<T>> for LogicalPoint<T> { type Output = LogicalPoint<T>; #[inline] @@ -470,7 +470,7 @@ impl<T: Copy + Add<T,Output=T>> Add<LogicalSize<T>> for LogicalPoint<T> { } } -impl<T: Copy + Sub<T,Output=T>> Sub<LogicalSize<T>> for LogicalPoint<T> { +impl<T: Copy + Sub<T, Output=T>> Sub<LogicalSize<T>> for LogicalPoint<T> { type Output = LogicalPoint<T>; #[inline] diff --git a/components/util/opts.rs b/components/util/opts.rs index 6202396b79f..0e11006ab4e 100644 --- a/components/util/opts.rs +++ b/components/util/opts.rs @@ -135,7 +135,7 @@ pub struct Opts { pub initial_window_size: TypedSize2D<ScreenPx, u32>, /// An optional string allowing the user agent to be set for testing. - pub user_agent: Option<String>, + pub user_agent: String, /// Whether to run in multiprocess mode. pub multiprocess: bool, @@ -337,17 +337,36 @@ static FORCE_CPU_PAINTING: bool = true; #[cfg(not(target_os="android"))] static FORCE_CPU_PAINTING: bool = false; +enum UserAgent { + Desktop, + Android, + Gonk, +} + +fn default_user_agent_string(agent: UserAgent) -> String { + match agent { + UserAgent::Desktop => { + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:37.0) Servo/1.0 Firefox/37.0" + } + UserAgent::Android => { + "Mozilla/5.0 (Android; Mobile; rv:37.0) Servo/1.0 Firefox/37.0" + } + UserAgent::Gonk => { + "Mozilla/5.0 (Mobile; rv:37.0) Servo/1.0 Firefox/37.0" + } + }.to_owned() +} + #[cfg(target_os="android")] -const DEFAULT_USER_AGENT: &'static str = "Mozilla/5.0 (Android; Mobile; rv:37.0) Servo/1.0 Firefox/37.0"; +const DEFAULT_USER_AGENT: UserAgent = UserAgent::Android; // FIXME: This requires https://github.com/servo/servo/issues/7138 to provide the // correct string in Gonk builds (i.e., it will never be chosen today). #[cfg(target_os="gonk")] -const DEFAULT_USER_AGENT: &'static str = "Mozilla/5.0 (Mobile; rv:37.0) Servo/1.0 Firefox/37.0"; +const DEFAULT_USER_AGENT: UserAgent = UserAgent::Gonk; #[cfg(not(any(target_os="android", target_os="gonk")))] -const DEFAULT_USER_AGENT: &'static str = - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:37.0) Servo/1.0 Firefox/37.0"; +const DEFAULT_USER_AGENT: UserAgent = UserAgent::Desktop; pub fn default_opts() -> Opts { Opts { @@ -381,7 +400,7 @@ pub fn default_opts() -> Opts { devtools_port: None, webdriver_port: None, initial_window_size: Size2D::typed(800, 600), - user_agent: None, + user_agent: default_user_agent_string(DEFAULT_USER_AGENT), multiprocess: false, dump_flow_tree: false, dump_display_list: false, @@ -424,7 +443,10 @@ pub fn from_cmdline_args(args: &[String]) { opts.optflagopt("", "devtools", "Start remote devtools server on port", "6000"); opts.optflagopt("", "webdriver", "Start remote WebDriver server on port", "7000"); opts.optopt("", "resolution", "Set window resolution.", "800x600"); - opts.optopt("u", "user-agent", "Set custom user agent string", "NCSA Mosaic/1.0 (X11;SunOS 4.1.4 sun4m)"); + opts.optopt("u", + "user-agent", + "Set custom user agent string (or android / gonk / desktop for platform default)", + "NCSA Mosaic/1.0 (X11;SunOS 4.1.4 sun4m)"); opts.optflag("M", "multiprocess", "Run in multiprocess mode"); opts.optopt("Z", "debug", "A comma-separated string of debug options. Pass help to show available options.", ""); @@ -532,7 +554,13 @@ pub fn from_cmdline_args(args: &[String]) { } }; - let user_agent = opt_match.opt_str("u").or(Some(DEFAULT_USER_AGENT.to_string())); + let user_agent = match opt_match.opt_str("u") { + Some(ref ua) if ua == "android" => default_user_agent_string(UserAgent::Android), + Some(ref ua) if ua == "gonk" => default_user_agent_string(UserAgent::Gonk), + Some(ref ua) if ua == "desktop" => default_user_agent_string(UserAgent::Desktop), + Some(ua) => ua, + None => default_user_agent_string(DEFAULT_USER_AGENT), + }; let user_stylesheets = opt_match.opt_strs("user-stylesheet").iter().map(|filename| { let path = cwd.join(filename); diff --git a/components/util/persistent_list.rs b/components/util/persistent_list.rs index b49cd44cd8b..55d2b6cd2fd 100644 --- a/components/util/persistent_list.rs +++ b/components/util/persistent_list.rs @@ -50,7 +50,7 @@ impl<T> PersistentList<T> where T: Send + Sync { } #[inline] - pub fn iter<'a>(&'a self) -> PersistentListIterator<'a,T> { + pub fn iter<'a>(&'a self) -> PersistentListIterator<'a, T> { // This could clone (and would not need the lifetime if it did), but then it would incur // atomic operations on every call to `.next()`. Bad. PersistentListIterator { @@ -74,7 +74,7 @@ pub struct PersistentListIterator<'a,T> where T: 'a + Send + Sync { entry: Option<&'a PersistentListEntry<T>>, } -impl<'a,T> Iterator for PersistentListIterator<'a,T> where T: Send + Sync + 'static { +impl<'a, T> Iterator for PersistentListIterator<'a, T> where T: Send + Sync + 'static { type Item = &'a T; #[inline] diff --git a/components/util/taskpool.rs b/components/util/taskpool.rs index bbd9ce8f311..bd67d819922 100644 --- a/components/util/taskpool.rs +++ b/components/util/taskpool.rs @@ -34,7 +34,7 @@ impl TaskPool { for i in 0..tasks { let state = state.clone(); spawn_named( - format!("TaskPoolWorker {}/{}", i+1, tasks), + format!("TaskPoolWorker {}/{}", i + 1, tasks), move || worker(&*state)); } diff --git a/components/util/vec.rs b/components/util/vec.rs index dd96fa07a99..638164971e4 100644 --- a/components/util/vec.rs +++ b/components/util/vec.rs @@ -10,7 +10,7 @@ use std::ops; /// FIXME(pcwalton): Workaround for lack of unboxed closures. This is called in /// performance-critical code, so a closure is insufficient. -pub trait Comparator<K,T> { +pub trait Comparator<K, T> { fn compare(&self, key: &K, value: &T) -> Ordering; } @@ -20,7 +20,7 @@ pub trait BinarySearchMethods<T: Ord + PartialOrd + PartialEq> { } pub trait FullBinarySearchMethods<T> { - fn binary_search_index_by<K,C:Comparator<K,T>>(&self, key: &K, cmp: C) -> Option<usize>; + fn binary_search_index_by<K, C: Comparator<K, T>>(&self, key: &K, cmp: C) -> Option<usize>; } impl<T: Ord + PartialOrd + PartialEq> BinarySearchMethods<T> for [T] { @@ -34,13 +34,13 @@ impl<T: Ord + PartialOrd + PartialEq> BinarySearchMethods<T> for [T] { } impl<T> FullBinarySearchMethods<T> for [T] { - fn binary_search_index_by<K,C:Comparator<K,T>>(&self, key: &K, cmp: C) -> Option<usize> { + fn binary_search_index_by<K, C: Comparator<K, T>>(&self, key: &K, cmp: C) -> Option<usize> { if self.is_empty() { return None; } - let mut low : isize = 0; - let mut high : isize = (self.len() as isize) - 1; + let mut low: isize = 0; + let mut high: isize = (self.len() as isize) - 1; while low <= high { // http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html @@ -59,7 +59,7 @@ impl<T> FullBinarySearchMethods<T> for [T] { struct DefaultComparator; -impl<T:PartialEq + PartialOrd + Ord> Comparator<T,T> for DefaultComparator { +impl<T: PartialEq + PartialOrd + Ord> Comparator<T, T> for DefaultComparator { fn compare(&self, key: &T, value: &T) -> Ordering { (*key).cmp(value) } diff --git a/components/util/workqueue.rs b/components/util/workqueue.rs index 2727f036c7e..d0899df1e61 100644 --- a/components/util/workqueue.rs +++ b/components/util/workqueue.rs @@ -273,7 +273,7 @@ impl<QueueData: Sync, WorkData: Send> WorkQueue<QueueData, WorkData> { for (i, thread) in threads.into_iter().enumerate() { spawn_named( - format!("{} worker {}/{}", task_name, i+1, thread_count), + format!("{} worker {}/{}", task_name, i + 1, thread_count), move || { task_state::initialize(state | task_state::IN_WORKER); let mut thread = thread; diff --git a/components/webdriver_server/lib.rs b/components/webdriver_server/lib.rs index 91506de0330..35870e2f0c7 100644 --- a/components/webdriver_server/lib.rs +++ b/components/webdriver_server/lib.rs @@ -19,18 +19,17 @@ extern crate rustc_serialize; extern crate uuid; extern crate ipc_channel; -use msg::constellation_msg::{ConstellationChan, LoadData, FrameId, PipelineId, NavigationDirection, - WebDriverCommandMsg}; +use msg::constellation_msg::{ConstellationChan, LoadData, FrameId, PipelineId}; +use msg::constellation_msg::{NavigationDirection, WebDriverCommandMsg}; use msg::constellation_msg::Msg as ConstellationMsg; use msg::webdriver_msg::{WebDriverFrameId, WebDriverScriptCommand, WebDriverJSError, WebDriverJSResult, LoadStatus}; use url::Url; use webdriver::command::{WebDriverMessage, WebDriverCommand}; -use webdriver::command::{GetParameters, JavascriptCommandParameters, LocatorParameters, - SwitchToFrameParameters, TimeoutsParameters}; +use webdriver::command::{GetParameters, JavascriptCommandParameters, LocatorParameters}; +use webdriver::command::{SwitchToFrameParameters, TimeoutsParameters}; use webdriver::common::{LocatorStrategy, WebElement}; -use webdriver::response::{ - WebDriverResponse, NewSessionResponse, ValueResponse}; +use webdriver::response::{WebDriverResponse, NewSessionResponse, ValueResponse}; use webdriver::server::{self, WebDriverHandler, Session}; use webdriver::error::{WebDriverResult, WebDriverError, ErrorStatus}; use util::task::spawn_named; @@ -498,7 +497,7 @@ impl Handler { "Taking screenshot failed")) }; let config = Config { - char_set:CharacterSet::Standard, + char_set: CharacterSet::Standard, newline: Newline::LF, pad: true, line_length: None |