use std::panic::Location;
use std::rc::Rc;
use waft_embedder::{View as EmbedderView, ViewConstraints, ViewId, ViewMetrics};
use waft_foundation::{App, Handle, HandleId, OptionRetained};
use waft_rendering::{AnyRenderObject, PipelineOwner, RenderHandle, RenderView, ViewConfiguration};
use waft_test::{IMPLICIT_VIEW_ID, TestPlatform};
use crate::*;
use waft_foundation::Ref;
pub(crate) const VIEW_WIDTH: f64 = 300.0;
pub(crate) const VIEW_HEIGHT: f64 = 200.0;
#[derive(Default)]
struct TestView {
host: waft_test::TestViewHost,
}
impl EmbedderView for TestView {
fn id(&self) -> ViewId {
IMPLICIT_VIEW_ID
}
fn metrics(&self) -> ViewMetrics {
ViewMetrics {
physical_size: [VIEW_WIDTH, VIEW_HEIGHT],
physical_constraints: ViewConstraints::new(0.0, VIEW_WIDTH, 0.0, VIEW_HEIGHT),
device_pixel_ratio: 1.0,
..ViewMetrics::default()
}
}
fn present(&self, _scene: std::sync::Arc<waft_embedder::Scene>) {}
fn host(&self) -> &dyn waft_embedder::ViewHost {
&self.host
}
}
#[derive(Debug)]
pub(crate) struct TestRoot {
pub(crate) child: WidgetRef,
}
impl RenderObjectWidget for TestRoot {
type RenderObject = RenderView;
fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
let view = Rc::new(TestView::default());
let configuration = ViewConfiguration::from_view(&*view);
RenderView::new(app, None, Some(configuration), view).as_object()
}
}
pub(crate) struct TestRootElement {
element: ElementData,
render_object_element: RenderObjectElementData,
child: Option<AnyElement>,
pipeline_owner: Option<Ref<PipelineOwner>>,
}
impl TestRootElement {
pub(crate) fn new(app: &mut App, widget: WidgetRef) -> Handle<TestRootElement> {
app.create(TestRootElement {
element: ElementData::new(widget),
render_object_element: RenderObjectElementData::default(),
child: None,
pipeline_owner: None,
})
.into_tree_node(app)
}
fn update_child_from_widget(self: Handle<Self>, app: &mut App) {
let child_widget = Self::widget_of(self.as_element().widget(app)).child.clone();
let child = app.get(self).child;
let child = self
.as_element()
.update_child(app, child, Some(child_widget), None);
app.get_mut(self).child = child;
}
}
impl RenderObjectElementWidget for TestRootElement {
type Widget = TestRoot;
fn widget_of(widget: &WidgetRef) -> &TestRoot {
downcast_widget::<TestRoot>(&**widget).expect("the root holds a TestRoot")
}
}
impl RenderObjectElement for TestRootElement {
fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
&app.get(self).render_object_element
}
fn render_object_element_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut RenderObjectElementData {
&mut app.get_mut(self).render_object_element
}
}
impl RenderTreeRootElement for TestRootElement {}
impl Element for TestRootElement {
crate::element_accessors!();
const IS_RENDER_OBJECT_ELEMENT: bool = true;
fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
self.render_object_element_data(app).render_object()
}
fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
None
}
fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
if let Some(child) = app.get(self).child {
visitor(child);
}
}
fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
debug_assert!(app.get(self).child == Some(child));
app.get_mut(self).child = None;
}
fn mount(
self: Handle<Self>,
app: &mut App,
parent: Option<AnyElement>,
new_slot: Option<Slot>,
) {
debug_assert!(parent.is_none());
RenderObjectElement::mount(self, app, parent, new_slot);
let owner = PipelineOwner::new(app, None, None);
let render_view: RenderHandle<RenderView> = self.typed_render_object(app);
owner.set_root_node(app, Some(render_view.as_object()));
render_view.prepare_initial_frame(app);
app.get_mut(self).pipeline_owner = Some(owner);
self.update_child_from_widget(app);
}
fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
RenderObjectElement::update(self, app, new_widget);
self.update_child_from_widget(app);
}
fn perform_rebuild(self: Handle<Self>, app: &mut App) {
RenderObjectElement::perform_rebuild(self, app);
}
fn deactivate(self: Handle<Self>, app: &mut App) {
RenderObjectElement::deactivate(self, app);
}
fn unmount(self: Handle<Self>, app: &mut App) {
RenderObjectElement::unmount(self, app);
}
fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
RenderObjectElement::update_parent_data(self, app, parent_data_element);
}
fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
RenderTreeRootElement::update_slot(self, app, new_slot);
}
fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
RenderTreeRootElement::attach_render_object(self, app, new_slot);
}
fn detach_render_object(self: Handle<Self>, app: &mut App) {
RenderTreeRootElement::detach_render_object(self, app);
}
fn insert_render_object_child(
self: Handle<Self>,
app: &mut App,
child: AnyRenderObject,
_slot: Option<Slot>,
) {
let root: RenderHandle<RenderView> = self.typed_render_object(app);
root.set_child(app, Some(child.as_box().expect("a box child")));
}
fn move_render_object_child(
self: Handle<Self>,
_app: &mut App,
_child: AnyRenderObject,
_old_slot: Option<Slot>,
_new_slot: Option<Slot>,
) {
unreachable!("one child");
}
fn remove_render_object_child(
self: Handle<Self>,
app: &mut App,
_child: AnyRenderObject,
_slot: Option<Slot>,
) {
let root: RenderHandle<RenderView> = self.typed_render_object(app);
root.set_child(app, None);
}
}
pub(crate) struct Harness {
pub(crate) owner: Handle<BuildOwner>,
pub(crate) root: Handle<TestRootElement>,
}
impl Harness {
pub(crate) fn mount(app: &mut App, child: WidgetRef) -> Harness {
let owner = WidgetsBinding::instance(app).build_owner(app);
let widget: WidgetRef = Rc::new(TestRootErased {
root: TestRoot { child },
created: None,
});
let root = TestRootElement::new(app, widget);
root.as_element().assign_owner(app, owner);
owner.build_scope(
app,
root.as_element(),
Some(Box::new(move |app| {
root.as_element().mount(app, None, None)
})),
);
Harness { owner, root }
}
pub(crate) fn set_child(&self, app: &mut App, child: WidgetRef) {
let widget: WidgetRef = Rc::new(TestRootErased {
root: TestRoot { child },
created: None,
});
let root = self.root;
self.owner.build_scope(
app,
root.as_element(),
Some(Box::new(move |app| root.as_element().update(app, widget))),
);
}
pub(crate) fn pump(&self, app: &mut App) {
self.owner.build_scope(app, self.root.as_element(), None);
let pipeline = app.get(self.root).pipeline_owner.handle().expect("mounted");
pipeline.flush_layout(app);
pipeline.flush_compositing_bits(app);
pipeline.flush_paint(app);
self.owner.finalize_tree(app);
}
pub(crate) fn render_root(&self, app: &App) -> RenderHandle<RenderView> {
self.root.typed_render_object(app)
}
pub(crate) fn layers(&self, app: &App) -> Vec<waft_rendering::AnyLayer> {
let root = self
.render_root(app)
.as_object()
.layer(app)
.expect("the root's layer");
layer_tree(app, root)
}
}
pub(crate) fn layer_tree(
app: &App,
root: waft_rendering::AnyContainerLayer,
) -> Vec<waft_rendering::AnyLayer> {
fn walk(
app: &App,
layer: waft_rendering::AnyLayer,
layers: &mut Vec<waft_rendering::AnyLayer>,
) {
layers.push(layer);
if let Some(container) = layer.as_container_layer() {
let mut child = container.first_child(app);
while let Some(current) = child {
walk(app, current, layers);
child = current.next_sibling(app);
}
}
}
let mut layers = Vec::new();
walk(
app,
waft_rendering::ErasedLayer::as_layer(root),
&mut layers,
);
layers
}
#[derive(Debug)]
struct TestRootErased {
root: TestRoot,
created: Option<CreationLocation>,
}
impl Widget for TestRootErased {
fn key(&self) -> Option<&KeyRef> {
None
}
fn creation_location(&self) -> Option<&'static Location<'static>> {
self.created.and_then(CreationLocation::location)
}
fn record_creation_location(&mut self, location: CreationLocation) {
self.created = Some(location);
}
fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
TestRootElement::new(app, this).as_element()
}
fn as_any(&self) -> &dyn std::any::Any {
&self.root
}
fn widget_type(&self) -> std::any::TypeId {
std::any::TypeId::of::<TestRoot>()
}
fn kind(&self) -> WidgetKind {
WidgetKind::Other
}
}
pub(crate) fn padding_under_root(
harness: &Harness,
app: &App,
) -> RenderHandle<waft_rendering::RenderPadding> {
harness
.render_root(app)
.child(app)
.expect("a child")
.as_object()
.downcast::<waft_rendering::RenderPadding>(app)
.expect("a RenderPadding")
}
pub(crate) struct TestScrollContext {
context: BuildContext,
pub(crate) axis_direction: waft_painting::AxisDirection,
pub(crate) device_pixel_ratio: f64,
pub(crate) ignore_pointer: bool,
pub(crate) can_drag: Vec<bool>,
pub(crate) saved_offsets: Vec<f64>,
}
impl TestScrollContext {
pub(crate) fn new(app: &mut App, context: BuildContext) -> Ref<TestScrollContext> {
app.create(TestScrollContext {
context,
axis_direction: waft_painting::AxisDirection::Down,
device_pixel_ratio: 1.0,
ignore_pointer: false,
can_drag: Vec::new(),
saved_offsets: Vec::new(),
})
}
}
impl waft_scheduler::TickerProviderObject for TestScrollContext {
fn create_ticker(
self: Handle<Self>,
app: &mut App,
on_tick: waft_scheduler::TickerCallback,
) -> Ref<waft_scheduler::Ticker> {
waft_scheduler::Ticker::new(app, on_tick, None)
}
}
impl ScrollContext for Handle<TestScrollContext> {
fn type_name(&self) -> &'static str {
"TestScrollContext"
}
fn handle_id(&self) -> HandleId {
self.id()
}
fn vsync(&self) -> Rc<dyn TickerProvider> {
Rc::new(*self)
}
fn notification_context(&self, app: &mut App) -> Option<BuildContext> {
let this = *self;
Some(app.get(this).context)
}
fn storage_context(&self, app: &App) -> BuildContext {
let this = *self;
app.get(this).context
}
fn axis_direction(&self, app: &App) -> waft_painting::AxisDirection {
let this = *self;
app.get(this).axis_direction
}
fn device_pixel_ratio(&self, app: &App) -> f64 {
let this = *self;
app.get(this).device_pixel_ratio
}
fn set_ignore_pointer(&self, app: &mut App, value: bool) {
let this = *self;
app.get_mut(this).ignore_pointer = value;
}
fn set_can_drag(&self, app: &mut App, value: bool) {
let this = *self;
app.get_mut(this).can_drag.push(value);
}
fn save_offset(&self, app: &mut App, offset: f64) {
let this = *self;
app.get_mut(this).saved_offsets.push(offset);
}
}
pub(crate) struct ScrollHarness {
#[allow(dead_code)]
pub(crate) harness: Harness,
pub(crate) context: Ref<TestScrollContext>,
pub(crate) scroll_context: Rc<dyn ScrollContext>,
pub(crate) notifications: Rc<std::cell::RefCell<Vec<String>>>,
}
fn notification_label(notification: &dyn ScrollNotification) -> String {
let any = notification.as_any();
if any.downcast_ref::<ScrollStartNotification>().is_some() {
"start".to_string()
} else if let Some(update) = any.downcast_ref::<ScrollUpdateNotification>() {
format!("update {:?}", update.scroll_delta.unwrap_or_default())
} else if let Some(overscroll) = any.downcast_ref::<OverscrollNotification>() {
format!("overscroll {:?}", overscroll.overscroll)
} else if any.downcast_ref::<ScrollEndNotification>().is_some() {
"end".to_string()
} else if let Some(user) = any.downcast_ref::<UserScrollNotification>() {
format!("user {:?}", user.direction)
} else {
"unknown".to_string()
}
}
pub(crate) fn mount_scroll_harness(app: &mut App) -> ScrollHarness {
let notifications = Rc::new(std::cell::RefCell::new(Vec::new()));
let recorded = notifications.clone();
let tree = NotificationListener::<dyn ScrollNotification>::new(SizedBox::shrink())
.on_notification(move |_app, notification: &dyn ScrollNotification| {
recorded.borrow_mut().push(notification_label(notification));
false
})
.into_widget();
let harness = Harness::mount(app, tree);
harness.pump(app);
let listener = harness.root.as_element().children(app)[0];
let inner = listener.children(app)[0];
let context = TestScrollContext::new(app, inner);
let scroll_context: Rc<dyn ScrollContext> = Rc::new(context.handle());
ScrollHarness {
harness,
context,
scroll_context,
notifications,
}
}
pub(crate) fn binding_pump(app: &mut App, at: std::time::Duration) {
let views = app
.platform()
.downcast_ref::<TestPlatform>()
.expect("an app on a TestPlatform")
.take_frame_requests();
if !views.is_empty() {
pump_frame(app, &views, at);
}
}
pub(crate) fn binding_pump_view(app: &mut App, view: ViewId, at: std::time::Duration) {
app.platform()
.downcast_ref::<TestPlatform>()
.expect("an app on a TestPlatform")
.take_frame_request(view);
pump_frame(app, &[view], at);
}
pub(crate) fn pump_every_view(app: &mut App, at: std::time::Duration) {
let views: Vec<ViewId> = app
.platform()
.views()
.iter()
.map(|view| view.id())
.collect();
pump_frame(app, &views, at);
}
fn pump_frame(app: &mut App, views: &[ViewId], at: std::time::Duration) {
waft_scheduler::SchedulerBinding::handle_begin_frame(app, views, Some(at));
app.drain_microtasks();
waft_scheduler::SchedulerBinding::handle_draw_frame(app, views);
app.drain_microtasks();
}
#[derive(Default)]
pub(crate) struct Quits(std::cell::Cell<u32>);
impl Quits {
pub(crate) fn count(&self) -> u32 {
self.0.get()
}
}
impl waft_embedder::AppExit for Quits {
fn quit(&self, _exit_code: i32) {
self.0.set(self.0.get() + 1);
}
}