use api::{BorderRadius, ClipMode, HitTestItem, HitTestResult, ItemTag, PrimitiveFlags};
use api::{PipelineId, ApiHitTester, ClipId};
use api::units::*;
use crate::clip::{ClipItemKind, ClipStore, ClipNode, rounded_rectangle_contains_point};
use crate::clip::{polygon_contains_point};
use crate::prim_store::PolygonKey;
use crate::scene_builder_thread::Interners;
use crate::spatial_tree::{SpatialNodeIndex, SpatialTree};
use crate::internal_types::{FastHashMap, FastHashSet, LayoutPrimitiveInfo};
use std::ops;
use std::sync::{Arc, Mutex};
use crate::util::{LayoutToWorldFastTransform, VecHelper};
pub struct SharedHitTester {
hit_tester: Mutex<Arc<HitTester>>,
}
impl SharedHitTester {
pub fn new() -> Self {
SharedHitTester {
hit_tester: Mutex::new(Arc::new(HitTester::empty())),
}
}
pub fn get_ref(&self) -> Arc<HitTester> {
let guard = self.hit_tester.lock().unwrap();
Arc::clone(&*guard)
}
pub(crate) fn update(&self, new_hit_tester: Arc<HitTester>) {
let mut guard = self.hit_tester.lock().unwrap();
*guard = new_hit_tester;
}
}
impl ApiHitTester for SharedHitTester {
fn hit_test(&self,
pipeline_id: Option<PipelineId>,
point: WorldPoint,
) -> HitTestResult {
self.get_ref().hit_test(HitTest::new(pipeline_id, point))
}
}
#[derive(MallocSizeOf)]
struct HitTestSpatialNode {
pipeline_id: PipelineId,
world_content_transform: LayoutToWorldFastTransform,
world_viewport_transform: LayoutToWorldFastTransform,
external_scroll_offset: LayoutVector2D,
}
#[derive(MallocSizeOf)]
struct HitTestClipNode {
region: HitTestRegion,
spatial_node_index: SpatialNodeIndex,
}
impl HitTestClipNode {
fn new(
node: ClipNode,
spatial_node_index: SpatialNodeIndex,
interners: &Interners,
) -> Self {
let region = match node.item.kind {
ClipItemKind::Rectangle { rect, mode } => {
HitTestRegion::Rectangle(rect, mode)
}
ClipItemKind::RoundedRectangle { rect, radius, mode } => {
HitTestRegion::RoundedRectangle(rect, radius, mode)
}
ClipItemKind::Image { rect, polygon_handle, .. } => {
if let Some(handle) = polygon_handle {
let polygon = &interners.polygon[handle];
HitTestRegion::Polygon(rect, *polygon)
} else {
HitTestRegion::Rectangle(rect, ClipMode::Clip)
}
}
ClipItemKind::BoxShadow { .. } => HitTestRegion::Invalid,
};
HitTestClipNode {
region,
spatial_node_index,
}
}
}
#[derive(Clone, MallocSizeOf)]
struct HitTestingItem {
rect: LayoutRect,
clip_rect: LayoutRect,
tag: ItemTag,
is_backface_visible: bool,
spatial_node_index: SpatialNodeIndex,
#[ignore_malloc_size_of = "Range"]
clip_nodes_range: ops::Range<ClipNodeIndex>,
}
impl HitTestingItem {
fn new(
tag: ItemTag,
info: &LayoutPrimitiveInfo,
spatial_node_index: SpatialNodeIndex,
clip_nodes_range: ops::Range<ClipNodeIndex>,
) -> HitTestingItem {
HitTestingItem {
rect: info.rect,
clip_rect: info.clip_rect,
tag,
is_backface_visible: info.flags.contains(PrimitiveFlags::IS_BACKFACE_VISIBLE),
spatial_node_index,
clip_nodes_range,
}
}
}
pub struct HitTestingSceneStats {
pub clip_nodes_count: usize,
pub items_count: usize,
}
impl HitTestingSceneStats {
pub fn empty() -> Self {
HitTestingSceneStats {
clip_nodes_count: 0,
items_count: 0,
}
}
}
#[derive(MallocSizeOf, Debug, Copy, Clone)]
pub struct ClipNodeIndex(u32);
#[derive(MallocSizeOf)]
pub struct HitTestingScene {
clip_nodes: Vec<HitTestClipNode>,
items: Vec<HitTestingItem>,
#[ignore_malloc_size_of = "ClipId"]
clip_id_stack: Vec<ClipId>,
#[ignore_malloc_size_of = "simple"]
cached_clip_id: Option<(ClipId, ops::Range<ClipNodeIndex>)>,
#[ignore_malloc_size_of = "ClipId"]
seen_clips: FastHashSet<ClipId>,
}
impl HitTestingScene {
pub fn new(stats: &HitTestingSceneStats) -> Self {
HitTestingScene {
clip_nodes: Vec::with_capacity(stats.clip_nodes_count),
items: Vec::with_capacity(stats.items_count),
clip_id_stack: Vec::with_capacity(8),
cached_clip_id: None,
seen_clips: FastHashSet::default(),
}
}
pub fn get_stats(&self) -> HitTestingSceneStats {
HitTestingSceneStats {
clip_nodes_count: self.clip_nodes.len(),
items_count: self.items.len(),
}
}
pub fn add_item(
&mut self,
tag: ItemTag,
info: &LayoutPrimitiveInfo,
spatial_node_index: SpatialNodeIndex,
clip_id: ClipId,
clip_store: &ClipStore,
interners: &Interners,
) {
let clip_range = match self.cached_clip_id {
Some((cached_clip_id, ref range)) if cached_clip_id == clip_id => {
range.clone()
}
Some(_) | None => {
let start = ClipNodeIndex(self.clip_nodes.len() as u32);
self.seen_clips.clear();
for clip_id in &self.clip_id_stack {
add_clips(
*clip_id,
clip_store,
&mut self.clip_nodes,
&mut self.seen_clips,
interners,
);
}
add_clips(
clip_id,
clip_store,
&mut self.clip_nodes,
&mut self.seen_clips,
interners,
);
let end = ClipNodeIndex(self.clip_nodes.len() as u32);
let range = ops::Range {
start,
end,
};
self.cached_clip_id = Some((clip_id, range.clone()));
range
}
};
let item = HitTestingItem::new(
tag,
info,
spatial_node_index,
clip_range,
);
self.items.push(item);
}
pub fn push_clip(
&mut self,
clip_id: ClipId,
) {
self.cached_clip_id = None;
self.clip_id_stack.push(clip_id);
}
pub fn pop_clip(
&mut self,
) {
self.cached_clip_id = None;
self.clip_id_stack.pop().unwrap();
}
}
#[derive(MallocSizeOf)]
enum HitTestRegion {
Invalid,
Rectangle(LayoutRect, ClipMode),
RoundedRectangle(LayoutRect, BorderRadius, ClipMode),
Polygon(LayoutRect, PolygonKey),
}
impl HitTestRegion {
fn contains(&self, point: &LayoutPoint) -> bool {
match *self {
HitTestRegion::Rectangle(ref rectangle, ClipMode::Clip) =>
rectangle.contains(*point),
HitTestRegion::Rectangle(ref rectangle, ClipMode::ClipOut) =>
!rectangle.contains(*point),
HitTestRegion::RoundedRectangle(rect, radii, ClipMode::Clip) =>
rounded_rectangle_contains_point(point, &rect, &radii),
HitTestRegion::RoundedRectangle(rect, radii, ClipMode::ClipOut) =>
!rounded_rectangle_contains_point(point, &rect, &radii),
HitTestRegion::Polygon(rect, polygon) =>
polygon_contains_point(point, &rect, &polygon),
HitTestRegion::Invalid => true,
}
}
}
#[derive(MallocSizeOf)]
pub struct HitTester {
#[ignore_malloc_size_of = "Arc"]
scene: Arc<HitTestingScene>,
spatial_nodes: Vec<HitTestSpatialNode>,
pipeline_root_nodes: FastHashMap<PipelineId, SpatialNodeIndex>,
}
impl HitTester {
pub fn empty() -> Self {
HitTester {
scene: Arc::new(HitTestingScene::new(&HitTestingSceneStats::empty())),
spatial_nodes: Vec::new(),
pipeline_root_nodes: FastHashMap::default(),
}
}
pub fn new(
scene: Arc<HitTestingScene>,
spatial_tree: &SpatialTree,
) -> HitTester {
let mut hit_tester = HitTester {
scene,
spatial_nodes: Vec::new(),
pipeline_root_nodes: FastHashMap::default(),
};
hit_tester.read_spatial_tree(spatial_tree);
hit_tester
}
fn read_spatial_tree(
&mut self,
spatial_tree: &SpatialTree,
) {
self.spatial_nodes.clear();
self.spatial_nodes.reserve(spatial_tree.spatial_nodes.len());
for (index, node) in spatial_tree.spatial_nodes.iter().enumerate() {
let index = SpatialNodeIndex::new(index);
self.pipeline_root_nodes.entry(node.pipeline_id).or_insert(index);
self.spatial_nodes.push(HitTestSpatialNode {
pipeline_id: node.pipeline_id,
world_content_transform: spatial_tree
.get_world_transform(index)
.into_fast_transform(),
world_viewport_transform: spatial_tree
.get_world_viewport_transform(index)
.into_fast_transform(),
external_scroll_offset: spatial_tree.external_scroll_offset(index),
});
}
}
pub fn hit_test(&self, test: HitTest) -> HitTestResult {
let mut result = HitTestResult::default();
let mut current_spatial_node_index = SpatialNodeIndex::INVALID;
let mut point_in_layer = None;
let mut current_root_spatial_node_index = SpatialNodeIndex::INVALID;
let mut point_in_viewport = None;
for item in self.scene.items.iter().rev() {
let scroll_node = &self.spatial_nodes[item.spatial_node_index.0 as usize];
let pipeline_id = scroll_node.pipeline_id;
match (test.pipeline_id, pipeline_id) {
(Some(id), node_id) if node_id != id => continue,
_ => {},
}
if item.spatial_node_index != current_spatial_node_index {
point_in_layer = scroll_node
.world_content_transform
.inverse()
.and_then(|inverted| inverted.transform_point2d(test.point));
current_spatial_node_index = item.spatial_node_index;
}
if let Some(point_in_layer) = point_in_layer {
if !item.rect.contains(point_in_layer) {
continue;
}
if !item.clip_rect.contains(point_in_layer) {
continue;
}
let mut is_valid = true;
let clip_nodes = &self.scene.clip_nodes[item.clip_nodes_range.start.0 as usize .. item.clip_nodes_range.end.0 as usize];
for clip_node in clip_nodes {
let transform = self
.spatial_nodes[clip_node.spatial_node_index.0 as usize]
.world_content_transform;
let transformed_point = match transform
.inverse()
.and_then(|inverted| inverted.transform_point2d(test.point))
{
Some(point) => point,
None => {
continue;
}
};
if !clip_node.region.contains(&transformed_point) {
is_valid = false;
break;
}
}
if !is_valid {
continue;
}
if !item.is_backface_visible && scroll_node.world_content_transform.is_backface_visible() {
continue;
}
let root_spatial_node_index = self.pipeline_root_nodes[&pipeline_id];
if root_spatial_node_index != current_root_spatial_node_index {
let root_node = &self.spatial_nodes[root_spatial_node_index.0 as usize];
point_in_viewport = root_node
.world_viewport_transform
.inverse()
.and_then(|inverted| inverted.transform_point2d(test.point))
.map(|pt| pt - scroll_node.external_scroll_offset);
current_root_spatial_node_index = root_spatial_node_index;
}
if let Some(point_in_viewport) = point_in_viewport {
result.items.push(HitTestItem {
pipeline: pipeline_id,
tag: item.tag,
point_in_viewport,
point_relative_to_item: point_in_layer - item.rect.min.to_vector(),
});
}
}
}
result.items.dedup();
result
}
}
#[derive(MallocSizeOf)]
pub struct HitTest {
pipeline_id: Option<PipelineId>,
point: WorldPoint,
}
impl HitTest {
pub fn new(
pipeline_id: Option<PipelineId>,
point: WorldPoint,
) -> HitTest {
HitTest {
pipeline_id,
point,
}
}
}
fn add_clips(
clip_id: ClipId,
clip_store: &ClipStore,
clip_nodes: &mut Vec<HitTestClipNode>,
seen_clips: &mut FastHashSet<ClipId>,
interners: &Interners,
) {
if seen_clips.contains(&clip_id) {
return;
}
seen_clips.insert(clip_id);
let template = &clip_store.templates[&clip_id];
let instances = &clip_store.instances[template.clips.start as usize .. template.clips.end as usize];
for clip in instances {
clip_nodes.alloc().init(
HitTestClipNode::new(
clip.key.into(),
clip.clip.spatial_node_index,
interners,
)
);
}
if clip_id != template.parent {
add_clips(
template.parent,
clip_store,
clip_nodes,
seen_clips,
interners,
);
}
}