Remove old rendering backend.

This removes paint threads, rust-layers dependency, and changes
optional webrender types to be required.

The use_webrender option has been removed, however I've left
the "-w" command line option in place so that wpt
runner can continue to pass that. Once it's removed from there
we can also remove the -w option.

Once this stage is complete, it should be fine to change the
display list building code to generate webrender display
lists directly and avoid the conversion step.
This commit is contained in:
Glenn Watson 2016-10-12 10:13:27 +10:00
parent 4af21e3ae1
commit acfdfd2fa9
55 changed files with 422 additions and 3611 deletions

View file

@ -10,14 +10,11 @@ name = "compositing"
path = "lib.rs"
[dependencies]
app_units = "0.3"
azure = {git = "https://github.com/servo/rust-azure", features = ["plugins"]}
euclid = "0.10.1"
gfx_traits = {path = "../gfx_traits"}
gleam = "0.2.8"
image = "0.10"
ipc-channel = "0.5"
layers = {git = "https://github.com/servo/rust-layers", features = ["plugins"]}
log = "0.3.5"
msg = {path = "../msg"}
net_traits = {path = "../net_traits"}

File diff suppressed because it is too large Load diff

View file

@ -1,542 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use azure::azure_hl;
use compositor::IOCompositor;
use euclid::point::TypedPoint2D;
use euclid::rect::TypedRect;
use euclid::size::TypedSize2D;
use gfx_traits::{Epoch, LayerId, LayerProperties, ScrollPolicy};
use layers::color::Color;
use layers::geometry::LayerPixel;
use layers::layers::{Layer, LayerBufferSet};
use msg::constellation_msg::PipelineId;
use script_traits::CompositorEvent;
use script_traits::CompositorEvent::{MouseButtonEvent, MouseMoveEvent, TouchpadPressureEvent};
use script_traits::ConstellationControlMsg;
use script_traits::MouseEventType;
use script_traits::TouchpadPressurePhase;
use std::rc::Rc;
use windowing::{MouseWindowEvent, WindowMethods};
#[derive(Debug)]
pub struct CompositorData {
/// This layer's pipeline id. The compositor can associate this id with an
/// actual CompositionPipeline.
pub pipeline_id: PipelineId,
/// The ID of this layer within the pipeline.
pub id: LayerId,
/// The behavior of this layer when a scroll message is received.
pub wants_scroll_events: WantsScrollEventsFlag,
/// Whether an ancestor layer that receives scroll events moves this layer.
pub scroll_policy: ScrollPolicy,
/// The epoch that has been requested for this layer (via send_buffer_requests).
pub requested_epoch: Epoch,
/// The last accepted painted buffer for this layer (via assign_pained_buffers).
pub painted_epoch: Epoch,
/// The scroll offset originating from this scrolling root. This allows scrolling roots
/// to track their current scroll position even while their content_offset does not change.
pub scroll_offset: TypedPoint2D<f32, LayerPixel>,
/// The pipeline ID of this layer, if it represents a subpage.
pub subpage_info: Option<PipelineId>,
}
impl CompositorData {
pub fn new_layer(pipeline_id: PipelineId,
layer_properties: LayerProperties,
wants_scroll_events: WantsScrollEventsFlag,
tile_size: usize)
-> Rc<Layer<CompositorData>> {
let new_compositor_data = CompositorData {
pipeline_id: pipeline_id,
id: layer_properties.id,
wants_scroll_events: wants_scroll_events,
scroll_policy: layer_properties.scroll_policy,
requested_epoch: Epoch(0),
painted_epoch: Epoch(0),
scroll_offset: TypedPoint2D::zero(),
subpage_info: layer_properties.subpage_pipeline_id,
};
Rc::new(Layer::new(TypedRect::from_untyped(&layer_properties.rect),
tile_size,
to_layers_color(&layer_properties.background_color),
1.0,
layer_properties.establishes_3d_context,
new_compositor_data))
}
}
pub trait CompositorLayer {
fn update_layer_except_bounds(&self, layer_properties: LayerProperties);
fn update_layer(&self, layer_properties: LayerProperties);
fn add_buffers<Window>(&self,
compositor: &mut IOCompositor<Window>,
new_buffers: Box<LayerBufferSet>,
epoch: Epoch)
where Window: WindowMethods;
/// Destroys all layer tiles, sending the buffers back to the painter to be destroyed or
/// reused.
fn clear<Window>(&self, compositor: &mut IOCompositor<Window>) where Window: WindowMethods;
/// Destroys tiles for this layer and all descendent layers, sending the buffers back to the
/// painter to be destroyed or reused.
fn clear_all_tiles<Window>(&self, compositor: &mut IOCompositor<Window>)
where Window: WindowMethods;
/// Removes the root layer (and any children) for a given pipeline from the
/// compositor. Buffers that the compositor is holding are returned to the
/// owning paint thread.
fn remove_root_layer_with_pipeline_id<Window>(&self,
compositor: &mut IOCompositor<Window>,
pipeline_id: PipelineId)
where Window: WindowMethods;
/// Destroys all tiles of all layers, including children, *without* sending them back to the
/// painter. You must call this only when the paint thread is destined to be going down;
/// otherwise, you will leak tiles.
///
/// This is used during shutdown, when we know the paint thread is going away.
fn forget_all_tiles(&self);
/// Move the layer's descendants that don't want scroll events and scroll by a relative
/// specified amount in page coordinates. This also takes in a cursor position to see if the
/// mouse is over child layers first. If a layer successfully scrolled returns either
/// ScrollPositionUnchanged or ScrollPositionChanged. If no layer was targeted by the event
/// returns ScrollEventUnhandled.
fn handle_scroll_event(&self,
delta: TypedPoint2D<f32, LayerPixel>,
cursor: TypedPoint2D<f32, LayerPixel>)
-> ScrollEventResult;
// Takes in a MouseWindowEvent, determines if it should be passed to children, and
// sends the event off to the appropriate pipeline. NB: the cursor position is in
// client coordinates.
fn send_mouse_event<Window>(&self,
compositor: &IOCompositor<Window>,
event: MouseWindowEvent,
cursor: TypedPoint2D<f32, LayerPixel>)
where Window: WindowMethods;
fn send_mouse_move_event<Window>(&self,
compositor: &IOCompositor<Window>,
cursor: TypedPoint2D<f32, LayerPixel>)
where Window: WindowMethods;
fn send_event<Window>(&self,
compositor: &IOCompositor<Window>,
event: CompositorEvent)
where Window: WindowMethods;
fn send_touchpad_pressure_event<Window>(&self,
compositor: &IOCompositor<Window>,
cursor: TypedPoint2D<f32, LayerPixel>,
pressure: f32,
phase: TouchpadPressurePhase)
where Window: WindowMethods;
fn clamp_scroll_offset_and_scroll_layer(&self,
new_offset: TypedPoint2D<f32, LayerPixel>)
-> ScrollEventResult;
fn scroll_layer_and_all_child_layers(&self,
new_offset: TypedPoint2D<f32, LayerPixel>)
-> bool;
/// Return a flag describing how this layer deals with scroll events.
fn wants_scroll_events(&self) -> WantsScrollEventsFlag;
/// Return the pipeline id associated with this layer.
fn pipeline_id(&self) -> PipelineId;
}
pub trait RcCompositorLayer {
/// Traverses the existing layer hierarchy and removes any layers that
/// currently exist but which are no longer required.
fn collect_old_layers<Window>(&self,
compositor: &mut IOCompositor<Window>,
pipeline_id: PipelineId,
new_layers: &[LayerProperties],
pipelines_removed: &mut Vec<PipelineId>)
where Window: WindowMethods;
}
#[derive(Copy, PartialEq, Clone, Debug)]
pub enum WantsScrollEventsFlag {
WantsScrollEvents,
DoesntWantScrollEvents,
}
fn to_layers_color(color: &azure_hl::Color) -> Color {
Color { r: color.r, g: color.g, b: color.b, a: color.a }
}
trait Clampable {
fn clamp(&self, mn: &Self, mx: &Self) -> Self;
}
impl Clampable for f32 {
/// Returns the number constrained within the range `mn <= self <= mx`.
/// If any of the numbers are `NAN` then `NAN` is returned.
#[inline]
fn clamp(&self, mn: &f32, mx: &f32) -> f32 {
match () {
_ if self.is_nan() => *self,
_ if !(*self <= *mx) => *mx,
_ if !(*self >= *mn) => *mn,
_ => *self,
}
}
}
fn calculate_content_size_for_layer(layer: &Layer<CompositorData>)
-> TypedSize2D<f32, LayerPixel> {
layer.children().iter().fold(TypedRect::zero(),
|unioned_rect, child_rect| {
unioned_rect.union(&*child_rect.bounds.borrow())
}).size
}
#[derive(PartialEq)]
pub enum ScrollEventResult {
ScrollEventUnhandled,
ScrollPositionChanged,
ScrollPositionUnchanged,
}
impl CompositorLayer for Layer<CompositorData> {
fn update_layer_except_bounds(&self, layer_properties: LayerProperties) {
self.extra_data.borrow_mut().scroll_policy = layer_properties.scroll_policy;
self.extra_data.borrow_mut().subpage_info = layer_properties.subpage_pipeline_id;
*self.transform.borrow_mut() = layer_properties.transform;
*self.perspective.borrow_mut() = layer_properties.perspective;
*self.background_color.borrow_mut() = to_layers_color(&layer_properties.background_color);
self.contents_changed();
}
fn update_layer(&self, layer_properties: LayerProperties) {
*self.bounds.borrow_mut() = TypedRect::from_untyped(&layer_properties.rect);
// Call scroll for bounds checking if the page shrunk. Use (-1, -1) as the
// cursor position to make sure the scroll isn't propagated downwards.
self.handle_scroll_event(TypedPoint2D::zero(), TypedPoint2D::new(-1f32, -1f32));
self.update_layer_except_bounds(layer_properties);
}
// Add LayerBuffers to the specified layer. Returns the layer buffer set back if the layer that
// matches the given pipeline ID was not found; otherwise returns None and consumes the layer
// buffer set.
//
// If the epoch of the message does not match the layer's epoch, the message is ignored, the
// layer buffer set is consumed, and None is returned.
fn add_buffers<Window>(&self,
compositor: &mut IOCompositor<Window>,
new_buffers: Box<LayerBufferSet>,
epoch: Epoch)
where Window: WindowMethods {
self.extra_data.borrow_mut().painted_epoch = epoch;
assert!(self.extra_data.borrow().painted_epoch == self.extra_data.borrow().requested_epoch);
for buffer in new_buffers.buffers.into_iter().rev() {
self.add_buffer(buffer);
}
compositor.cache_unused_buffers(self.collect_unused_buffers())
}
fn clear<Window>(&self, compositor: &mut IOCompositor<Window>) where Window: WindowMethods {
let buffers = self.collect_buffers();
if !buffers.is_empty() {
compositor.cache_unused_buffers(buffers);
}
}
/// Destroys tiles for this layer and all descendent layers, sending the buffers back to the
/// painter to be destroyed or reused.
fn clear_all_tiles<Window>(&self,
compositor: &mut IOCompositor<Window>)
where Window: WindowMethods {
self.clear(compositor);
for kid in &*self.children() {
kid.clear_all_tiles(compositor);
}
}
fn remove_root_layer_with_pipeline_id<Window>(&self,
compositor: &mut IOCompositor<Window>,
pipeline_id: PipelineId)
where Window: WindowMethods {
// Find the child that is the root layer for this pipeline.
let index = self.children().iter().position(|kid| {
let extra_data = kid.extra_data.borrow();
extra_data.pipeline_id == pipeline_id && extra_data.id == LayerId::null()
});
match index {
Some(index) => {
// Remove the root layer, and return buffers to the paint thread
let child = self.children().remove(index);
child.clear_all_tiles(compositor);
}
None => {
// Wasn't found, recurse into child layers
for kid in &*self.children() {
kid.remove_root_layer_with_pipeline_id(compositor, pipeline_id);
}
}
}
}
/// Destroys all tiles of all layers, including children, *without* sending them back to the
/// painter. You must call this only when the paint thread is destined to be going down;
/// otherwise, you will leak tiles.
///
/// This is used during shutdown, when we know the paint thread is going away.
fn forget_all_tiles(&self) {
let tiles = self.collect_buffers();
for tile in tiles {
let mut tile = tile;
tile.mark_wont_leak()
}
for kid in &*self.children() {
kid.forget_all_tiles();
}
}
fn handle_scroll_event(&self,
delta: TypedPoint2D<f32, LayerPixel>,
cursor: TypedPoint2D<f32, LayerPixel>)
-> ScrollEventResult {
// 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().rev() {
let child_bounds = child.bounds.borrow();
if child_bounds.contains(&new_cursor) {
let result = child.handle_scroll_event(delta, new_cursor - child_bounds.origin);
if result != ScrollEventResult::ScrollEventUnhandled {
return result;
}
}
}
// If this layer doesn't want scroll events, it can't handle scroll events.
if self.wants_scroll_events() != WantsScrollEventsFlag::WantsScrollEvents {
return ScrollEventResult::ScrollEventUnhandled;
}
self.clamp_scroll_offset_and_scroll_layer(scroll_offset + delta)
}
fn clamp_scroll_offset_and_scroll_layer(&self, new_offset: TypedPoint2D<f32, LayerPixel>)
-> ScrollEventResult {
let layer_size = self.bounds.borrow().size;
let content_size = calculate_content_size_for_layer(self);
let min_x = (layer_size.width - content_size.width).min(0.0);
let min_y = (layer_size.height - content_size.height).min(0.0);
let new_offset: TypedPoint2D<f32, LayerPixel> =
TypedPoint2D::new(new_offset.x.clamp(&min_x, &0.0),
new_offset.y.clamp(&min_y, &0.0));
if self.extra_data.borrow().scroll_offset == new_offset {
return ScrollEventResult::ScrollPositionUnchanged;
}
// The scroll offset is just a record of the scroll position of this scrolling root,
// but scroll_layer_and_all_child_layers actually moves the child layers.
self.extra_data.borrow_mut().scroll_offset = new_offset;
let mut result = false;
for child in &*self.children() {
result |= child.scroll_layer_and_all_child_layers(new_offset);
}
if result {
ScrollEventResult::ScrollPositionChanged
} else {
ScrollEventResult::ScrollPositionUnchanged
}
}
fn send_mouse_event<Window>(&self,
compositor: &IOCompositor<Window>,
event: MouseWindowEvent,
cursor: TypedPoint2D<f32, LayerPixel>)
where Window: WindowMethods {
let event_point = cursor.to_untyped();
let message = match event {
MouseWindowEvent::Click(button, _) =>
MouseButtonEvent(MouseEventType::Click, button, event_point),
MouseWindowEvent::MouseDown(button, _) =>
MouseButtonEvent(MouseEventType::MouseDown, button, event_point),
MouseWindowEvent::MouseUp(button, _) =>
MouseButtonEvent(MouseEventType::MouseUp, button, event_point),
};
self.send_event(compositor, message);
}
fn send_mouse_move_event<Window>(&self,
compositor: &IOCompositor<Window>,
cursor: TypedPoint2D<f32, LayerPixel>)
where Window: WindowMethods {
self.send_event(compositor, MouseMoveEvent(Some(cursor.to_untyped())));
}
fn send_event<Window>(&self,
compositor: &IOCompositor<Window>,
event: CompositorEvent) where Window: WindowMethods {
if let Some(pipeline) = compositor.pipeline(self.pipeline_id()) {
let _ = pipeline.script_chan
.send(ConstellationControlMsg::SendEvent(pipeline.id.clone(), event));
}
}
fn send_touchpad_pressure_event<Window>(&self,
compositor: &IOCompositor<Window>,
cursor: TypedPoint2D<f32, LayerPixel>,
pressure: f32,
phase: TouchpadPressurePhase)
where Window: WindowMethods {
if let Some(pipeline) = compositor.pipeline(self.pipeline_id()) {
let message = TouchpadPressureEvent(cursor.to_untyped(), pressure, phase);
let _ = pipeline.script_chan.send(ConstellationControlMsg::SendEvent(pipeline.id.clone(), message));
}
}
fn scroll_layer_and_all_child_layers(&self, new_offset: TypedPoint2D<f32, LayerPixel>)
-> bool {
let mut result = false;
// Only scroll this layer if it's not fixed-positioned.
if self.extra_data.borrow().scroll_policy != ScrollPolicy::FixedPosition {
let new_offset = new_offset.to_untyped();
*self.content_offset.borrow_mut() = TypedPoint2D::from_untyped(&new_offset);
result = true
}
let offset_for_children = new_offset + self.extra_data.borrow().scroll_offset;
for child in &*self.children() {
result |= child.scroll_layer_and_all_child_layers(offset_for_children);
}
result
}
fn wants_scroll_events(&self) -> WantsScrollEventsFlag {
self.extra_data.borrow().wants_scroll_events
}
fn pipeline_id(&self) -> PipelineId {
self.extra_data.borrow().pipeline_id
}
}
impl RcCompositorLayer for Rc<Layer<CompositorData>> {
fn collect_old_layers<Window>(&self,
compositor: &mut IOCompositor<Window>,
pipeline_id: PipelineId,
new_layers: &[LayerProperties],
pipelines_removed: &mut Vec<PipelineId>)
where Window: WindowMethods {
fn find_root_layer_for_pipeline(layer: &Rc<Layer<CompositorData>>, pipeline_id: PipelineId)
-> Option<Rc<Layer<CompositorData>>> {
let extra_data = layer.extra_data.borrow();
if extra_data.pipeline_id == pipeline_id {
return Some((*layer).clone())
}
for kid in &*layer.children() {
if let Some(layer) = find_root_layer_for_pipeline(kid, pipeline_id) {
return Some(layer.clone())
}
}
None
}
fn collect_old_layers_for_pipeline<Window>(
layer: &Layer<CompositorData>,
compositor: &mut IOCompositor<Window>,
pipeline_id: PipelineId,
new_layers: &[LayerProperties],
pipelines_removed: &mut Vec<PipelineId>,
layer_pipeline_id: Option<PipelineId>)
where Window: WindowMethods {
// 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 &*layer.children() {
let extra_data = kid.extra_data.borrow();
let layer_pipeline_id = extra_data.subpage_info.or(layer_pipeline_id);
collect_old_layers_for_pipeline(kid,
compositor,
pipeline_id,
new_layers,
pipelines_removed,
layer_pipeline_id);
}
// Retain child layers that also exist in the new layer list.
layer.children().retain(|child| {
let extra_data = child.extra_data.borrow();
if pipeline_id == extra_data.pipeline_id {
// Never remove our own root layer.
if extra_data.id == LayerId::null() {
return true
}
// Keep this layer if it exists in the new layer list.
if new_layers.iter().any(|properties| properties.id == extra_data.id) {
return true
}
}
if let Some(layer_pipeline_id) = layer_pipeline_id {
for layer_properties in new_layers.iter() {
// Keep this layer if a reference to it exists.
if let Some(ref subpage_pipeline_id) = layer_properties.subpage_pipeline_id {
if *subpage_pipeline_id == layer_pipeline_id {
return true
}
}
}
pipelines_removed.push(extra_data.pipeline_id);
}
// When removing a layer, clear any tiles and surfaces associated with the layer.
child.clear_all_tiles(compositor);
false
});
}
// First, find the root layer with the given pipeline ID.
let root_layer = match find_root_layer_for_pipeline(self, pipeline_id) {
Some(root_layer) => root_layer,
None => return,
};
// Then collect all old layers underneath that layer.
collect_old_layers_for_pipeline(&root_layer,
compositor,
pipeline_id,
new_layers,
pipelines_removed,
None);
}
}

View file

@ -8,16 +8,14 @@ use SendableFrameTree;
use compositor::CompositingReason;
use euclid::point::Point2D;
use euclid::size::Size2D;
use gfx_traits::{Epoch, FrameTreeId, LayerId, LayerProperties, PaintListener};
use gfx_traits::LayerId;
use ipc_channel::ipc::IpcSender;
use layers::layers::{BufferRequest, LayerBufferSet};
use layers::platform::surface::{NativeDisplay, NativeSurface};
use msg::constellation_msg::{Image, Key, KeyModifiers, KeyState, PipelineId};
use profile_traits::mem;
use profile_traits::time;
use script_traits::{AnimationState, ConstellationMsg, EventResult};
use std::fmt::{Debug, Error, Formatter};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::mpsc::{Receiver, Sender};
use style_traits::cursor::Cursor;
use style_traits::viewport::ViewportConstraints;
use url::Url;
@ -63,55 +61,6 @@ impl RenderListener for Box<CompositorProxy + 'static> {
}
}
/// Implementation of the abstract `PaintListener` interface.
impl PaintListener for Box<CompositorProxy + 'static + Send> {
fn native_display(&mut self) -> Option<NativeDisplay> {
let (chan, port) = channel();
self.send(Msg::GetNativeDisplay(chan));
// If the compositor is shutting down when a paint thread
// is being created, the compositor won't respond to
// this message, resulting in an eventual panic. Instead,
// just return None in this case, since the paint thread
// will exit shortly and never actually be requested
// to paint buffers by the compositor.
port.recv().unwrap_or(None)
}
fn assign_painted_buffers(&mut self,
pipeline_id: PipelineId,
epoch: Epoch,
replies: Vec<(LayerId, Box<LayerBufferSet>)>,
frame_tree_id: FrameTreeId) {
self.send(Msg::AssignPaintedBuffers(pipeline_id, epoch, replies, frame_tree_id));
}
fn ignore_buffer_requests(&mut self, buffer_requests: Vec<BufferRequest>) {
let mut native_surfaces = Vec::new();
for request in buffer_requests.into_iter() {
if let Some(native_surface) = request.native_surface {
native_surfaces.push(native_surface);
}
}
if !native_surfaces.is_empty() {
self.send(Msg::ReturnUnusedNativeSurfaces(native_surfaces));
}
}
fn initialize_layers_for_pipeline(&mut self,
pipeline_id: PipelineId,
properties: Vec<LayerProperties>,
epoch: Epoch) {
// FIXME(#2004, pcwalton): This assumes that the first layer determines the page size, and
// that all other layers are immediate children of it. This is sufficient to handle
// `position: fixed` but will not be sufficient to handle `overflow: scroll` or transforms.
self.send(Msg::InitializeLayersForPipeline(pipeline_id, epoch, properties));
}
fn notify_paint_thread_exiting(&mut self, pipeline_id: PipelineId) {
self.send(Msg::PaintThreadExited(pipeline_id))
}
}
/// Messages from the painting thread and the constellation thread to the compositor thread.
pub enum Msg {
/// Requests that the compositor shut down.
@ -122,18 +71,8 @@ pub enum Msg {
/// (e.g. SetFrameTree) at the time that we send it an ExitMsg.
ShutdownComplete,
/// Requests the compositor's graphics metadata. Graphics metadata is what the painter needs
/// to create surfaces that the compositor can see. On Linux this is the X display; on Mac this
/// is the pixel format.
GetNativeDisplay(Sender<Option<NativeDisplay>>),
/// Tells the compositor to create or update the layers for a pipeline if necessary
/// (i.e. if no layer with that ID exists).
InitializeLayersForPipeline(PipelineId, Epoch, Vec<LayerProperties>),
/// Scroll a page in a window
ScrollFragmentPoint(PipelineId, LayerId, Point2D<f32>, bool),
/// Requests that the compositor assign the painted buffers to the given layers.
AssignPaintedBuffers(PipelineId, Epoch, Vec<(LayerId, Box<LayerBufferSet>)>, FrameTreeId),
/// Alerts the compositor that the current page has changed its title.
ChangePageTitle(PipelineId, Option<String>),
/// Alerts the compositor that the current page has changed its URL.
@ -158,8 +97,6 @@ pub enum Msg {
SetCursor(Cursor),
/// Composite to a PNG file and return the Image over a passed channel.
CreatePng(IpcSender<Option<Image>>),
/// Informs the compositor that the paint thread for the given pipeline has exited.
PaintThreadExited(PipelineId),
/// Alerts the compositor that the viewport has been constrained in some manner
ViewportConstrained(PipelineId, ViewportConstraints),
/// A reply to the compositor asking if the output image is stable.
@ -168,9 +105,6 @@ pub enum Msg {
NewFavicon(Url),
/// <head> tag finished parsing
HeadParsed,
/// Signal that the paint thread ignored the paint requests that carried
/// these native surfaces, so that they can be re-added to the surface cache.
ReturnUnusedNativeSurfaces(Vec<NativeSurface>),
/// Collect memory reports and send them back to the given mem::ReportsChan.
CollectMemoryReports(mem::ReportsChan),
/// A status message to be displayed by the browser chrome.
@ -181,8 +115,6 @@ pub enum Msg {
MoveTo(Point2D<i32>),
/// Resize the window to size
ResizeTo(Size2D<u32>),
/// Get scroll offset of a layer
GetScrollOffset(PipelineId, LayerId, IpcSender<Point2D<f32>>),
/// Pipeline visibility changed
PipelineVisibilityChanged(PipelineId, bool),
/// WebRender has successfully processed a scroll. The boolean specifies whether a composite is
@ -201,10 +133,7 @@ impl Debug for Msg {
match *self {
Msg::Exit => write!(f, "Exit"),
Msg::ShutdownComplete => write!(f, "ShutdownComplete"),
Msg::GetNativeDisplay(..) => write!(f, "GetNativeDisplay"),
Msg::InitializeLayersForPipeline(..) => write!(f, "InitializeLayersForPipeline"),
Msg::ScrollFragmentPoint(..) => write!(f, "ScrollFragmentPoint"),
Msg::AssignPaintedBuffers(..) => write!(f, "AssignPaintedBuffers"),
Msg::ChangeRunningAnimationsState(..) => write!(f, "ChangeRunningAnimationsState"),
Msg::ChangePageTitle(..) => write!(f, "ChangePageTitle"),
Msg::ChangePageUrl(..) => write!(f, "ChangePageUrl"),
@ -217,12 +146,10 @@ impl Debug for Msg {
Msg::TouchEventProcessed(..) => write!(f, "TouchEventProcessed"),
Msg::SetCursor(..) => write!(f, "SetCursor"),
Msg::CreatePng(..) => write!(f, "CreatePng"),
Msg::PaintThreadExited(..) => write!(f, "PaintThreadExited"),
Msg::ViewportConstrained(..) => write!(f, "ViewportConstrained"),
Msg::IsReadyToSaveImageReply(..) => write!(f, "IsReadyToSaveImageReply"),
Msg::NewFavicon(..) => write!(f, "NewFavicon"),
Msg::HeadParsed => write!(f, "HeadParsed"),
Msg::ReturnUnusedNativeSurfaces(..) => write!(f, "ReturnUnusedNativeSurfaces"),
Msg::CollectMemoryReports(..) => write!(f, "CollectMemoryReports"),
Msg::Status(..) => write!(f, "Status"),
Msg::GetClientWindow(..) => write!(f, "GetClientWindow"),
@ -230,7 +157,6 @@ impl Debug for Msg {
Msg::ResizeTo(..) => write!(f, "ResizeTo"),
Msg::PipelineVisibilityChanged(..) => write!(f, "PipelineVisibilityChanged"),
Msg::PipelineExited(..) => write!(f, "PipelineExited"),
Msg::GetScrollOffset(..) => write!(f, "GetScrollOffset"),
Msg::NewScrollFrameReady(..) => write!(f, "NewScrollFrameReady"),
}
}
@ -248,7 +174,7 @@ pub struct InitialCompositorState {
pub time_profiler_chan: time::ProfilerChan,
/// A channel to the memory profiler thread.
pub mem_profiler_chan: mem::ProfilerChan,
/// Instance of webrender API if enabled
pub webrender: Option<webrender::Renderer>,
pub webrender_api_sender: Option<webrender_traits::RenderApiSender>,
/// Instance of webrender API
pub webrender: webrender::Renderer,
pub webrender_api_sender: webrender_traits::RenderApiSender,
}

View file

@ -10,15 +10,11 @@
#![deny(unsafe_code)]
extern crate app_units;
extern crate azure;
extern crate euclid;
extern crate gfx_traits;
extern crate gleam;
extern crate image;
extern crate ipc_channel;
extern crate layers;
#[macro_use]
extern crate log;
extern crate msg;
@ -39,18 +35,14 @@ extern crate webrender_traits;
pub use compositor_thread::CompositorProxy;
pub use compositor::IOCompositor;
use euclid::size::TypedSize2D;
use gfx_traits::ChromeToPaintMsg;
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use script_traits::{ConstellationControlMsg, LayoutControlMsg};
use std::sync::mpsc::Sender;
use style_traits::PagePx;
mod compositor;
mod compositor_layer;
pub mod compositor_thread;
mod delayed_composition;
mod surface_map;
mod touch;
pub mod windowing;
@ -66,5 +58,4 @@ pub struct CompositionPipeline {
pub id: PipelineId,
pub script_chan: IpcSender<ConstellationControlMsg>,
pub layout_chan: IpcSender<LayoutControlMsg>,
pub chrome_to_paint_chan: Sender<ChromeToPaintMsg>,
}

View file

@ -1,164 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use euclid::size::Size2D;
use layers::platform::surface::{NativeDisplay, NativeSurface};
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::hash::{Hash, Hasher};
/// This is a struct used to store surfaces when they are not in use.
/// The paint thread can quickly query for a particular size of surface when it
/// needs it.
pub struct SurfaceMap {
/// A HashMap that stores the Buffers.
map: HashMap<SurfaceKey, SurfaceValue>,
/// The current amount of memory stored by the SurfaceMap's surfaces.
mem: usize,
/// The maximum allowed memory. Unused surfaces will be deleted
/// when this threshold is exceeded.
max_mem: usize,
/// A monotonically increasing counter to track how recently tile sizes were used.
counter: usize,
}
/// A key with which to store surfaces. It is based on the size of the surface.
#[derive(Eq, Copy, Clone)]
struct SurfaceKey([i32; 2]);
impl Hash for SurfaceKey {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
impl PartialEq for SurfaceKey {
fn eq(&self, other: &SurfaceKey) -> bool {
let SurfaceKey(s) = *self;
let SurfaceKey(o) = *other;
s[0] == o[0] && s[1] == o[1]
}
}
/// Create a key from a given size
impl SurfaceKey {
fn get(input: Size2D<i32>) -> SurfaceKey {
SurfaceKey([input.width, input.height])
}
}
/// A helper struct to keep track of surfaces in the HashMap
struct SurfaceValue {
/// An array of surfaces, all the same size
surfaces: Vec<NativeSurface>,
/// The counter when this size was last requested
last_action: usize,
}
impl SurfaceMap {
// Creates a new SurfaceMap with a given surface limit.
pub fn new(max_mem: usize) -> SurfaceMap {
SurfaceMap {
map: HashMap::new(),
mem: 0,
max_mem: max_mem,
counter: 0,
}
}
pub fn insert_surfaces<I>(&mut self, display: &NativeDisplay, surfaces: I)
where I: IntoIterator<Item=NativeSurface>
{
for surface in surfaces {
self.insert(display, surface);
}
}
/// Insert a new buffer into the map.
pub fn insert(&mut self, display: &NativeDisplay, mut new_surface: NativeSurface) {
let new_key = SurfaceKey::get(new_surface.get_size());
// If all our surfaces are the same size and we're already at our
// memory limit, no need to store this new buffer; just let it drop.
let new_total_memory_usage = self.mem + new_surface.get_memory_usage();
if new_total_memory_usage > self.max_mem && self.map.len() == 1 &&
self.map.contains_key(&new_key) {
new_surface.destroy(display);
return;
}
self.mem = new_total_memory_usage;
new_surface.mark_wont_leak();
// use lazy insertion function to prevent unnecessary allocation
let counter = &self.counter;
match self.map.entry(new_key) {
Occupied(entry) => {
entry.into_mut().surfaces.push(new_surface);
}
Vacant(entry) => {
entry.insert(SurfaceValue {
surfaces: vec!(new_surface),
last_action: *counter,
});
}
}
let mut opt_key: Option<SurfaceKey> = None;
while self.mem > self.max_mem {
let old_key = match opt_key {
Some(key) => key,
None => {
match self.map.iter().min_by_key(|&(_, x)| x.last_action) {
Some((k, _)) => *k,
None => panic!("SurfaceMap: tried to delete with no elements in map"),
}
}
};
if {
let list = &mut self.map.get_mut(&old_key).unwrap().surfaces;
let mut condemned_surface = list.pop().take().unwrap();
self.mem -= condemned_surface.get_memory_usage();
condemned_surface.destroy(display);
list.is_empty()
}
{ // then
self.map.remove(&old_key); // Don't store empty vectors!
opt_key = None;
} else {
opt_key = Some(old_key);
}
}
}
// Try to find a buffer for the given size.
pub fn find(&mut self, size: Size2D<i32>) -> Option<NativeSurface> {
let mut flag = false; // True if key needs to be popped after retrieval.
let key = SurfaceKey::get(size);
let ret = match self.map.get_mut(&key) {
Some(ref mut surface_val) => {
surface_val.last_action = self.counter;
self.counter += 1;
let surface = surface_val.surfaces.pop().take().unwrap();
self.mem -= surface.get_memory_usage();
if surface_val.surfaces.is_empty() {
flag = true;
}
Some(surface)
}
None => None,
};
if flag {
self.map.remove(&key); // Don't store empty vectors!
}
ret
}
pub fn mem(&self) -> usize {
self.mem
}
}

View file

@ -4,7 +4,7 @@
use euclid::point::TypedPoint2D;
use euclid::scale_factor::ScaleFactor;
use layers::geometry::DevicePixel;
use gfx_traits::DevicePixel;
use script_traits::{EventResult, TouchId};
use self::TouchState::*;

View file

@ -9,8 +9,7 @@ use euclid::{Point2D, Size2D};
use euclid::point::TypedPoint2D;
use euclid::scale_factor::ScaleFactor;
use euclid::size::TypedSize2D;
use layers::geometry::DevicePixel;
use layers::platform::surface::NativeDisplay;
use gfx_traits::DevicePixel;
use msg::constellation_msg::{Key, KeyModifiers, KeyState};
use net_traits::net_error_list::NetError;
use script_traits::{MouseButton, TouchEventType, TouchId, TouchpadPressurePhase};
@ -139,9 +138,6 @@ pub trait WindowMethods {
/// Returns the scale factor of the system (device pixels / screen pixels).
fn scale_factor(&self) -> ScaleFactor<f32, ScreenPx, DevicePixel>;
/// Gets the OS native graphics display for this window.
fn native_display(&self) -> NativeDisplay;
/// Creates a channel to the compositor. The dummy parameter is needed because we don't have
/// UFCS in Rust yet.
///