use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use waft_embedder::{
AppExit, AppLifecycleState, Brightness, Cameras, CaptionSettings, Clipboard, CompositionLayer,
Compositor, Dispatcher, DockMenu, FileDialogs, FontSource, Haptics, HardwareBuffer,
HardwareBufferAllocator, Image, ImageCodecFuture, ImageDecodeError, Instant, MediaAssets,
MenuBar, Notifications, Opener, Picture, Platform, Players, PointerReport, PopupMenus,
RequestId, Restoration, SignedDuration, SystemChrome, SystemContextMenu, TargetPlatform,
TextServices, TrayIcons, VideoFrame, VideoFrameReaders, View, ViewEmbedder, ViewError,
ViewFocusEvent, ViewHost, ViewId, ViewMetrics, ViewRef, WindowConfig,
};
use waft_embedder::image_codecs::ImageCodecs;
use waft_embedder::valo;
use crate::windows::view_of_request;
use crate::{TestFontSource, TestTimeZone, TestView, TestWindows};
type FontSourceMaker = Rc<dyn Fn() -> Box<dyn FontSource>>;
type ImageCodecOpener = Rc<dyn Fn(Arc<[u8]>) -> ImageCodecFuture>;
type PixelImporter = Rc<dyn Fn(valo::PixelBuffer) -> Option<Image>>;
type PictureRasterizer = Rc<dyn Fn(&Picture, u32, u32) -> Option<Image>>;
type FrameImporter = Rc<dyn Fn(&dyn VideoFrame) -> Option<Image>>;
type BufferImporter = Rc<dyn Fn(&dyn HardwareBuffer) -> Option<Image>>;
pub struct TestPlatform {
target: Cell<TargetPlatform>,
briefly_show_password: Cell<bool>,
brightness: Cell<Brightness>,
time_zone: RefCell<TestTimeZone>,
default_route: String,
views: RefCell<Vec<ViewRef>>,
test_views: Vec<Rc<TestView>>,
next_request: Cell<u64>,
added_views: RefCell<Vec<Rc<TestView>>>,
frame_requests: RefCell<Vec<ViewId>>,
dispatcher: Arc<TestDispatcher>,
font_source: FontSourceMaker,
image_codec: Option<ImageCodecOpener>,
pixel_import: Option<PixelImporter>,
picture_to_image: Option<PictureRasterizer>,
frame_import: Option<FrameImporter>,
buffer_import: Option<BufferImporter>,
windows: Option<Rc<TestWindows>>,
clipboard: Option<Rc<dyn Clipboard>>,
system_chrome: Option<Rc<dyn SystemChrome>>,
haptics: Option<Rc<dyn Haptics>>,
system_context_menu: Option<Rc<dyn SystemContextMenu>>,
menu_bar: Option<Rc<dyn MenuBar>>,
popup_menus: Option<Rc<dyn PopupMenus>>,
tray_icons: Option<Rc<dyn TrayIcons>>,
file_dialogs: Option<Rc<dyn FileDialogs>>,
opener: Option<Rc<dyn Opener>>,
notifications: Option<Rc<dyn Notifications>>,
compositor: Option<Arc<dyn Compositor>>,
hardware_buffer_allocator: Option<Arc<dyn HardwareBufferAllocator>>,
players: Option<Rc<dyn Players>>,
media_assets: Option<Rc<dyn MediaAssets>>,
image_codecs: Option<Rc<dyn ImageCodecs>>,
cameras: Option<Rc<dyn Cameras>>,
video_frame_readers: Option<Rc<dyn VideoFrameReaders>>,
caption_settings: Option<Rc<dyn CaptionSettings>>,
dock_menu: Option<Rc<dyn DockMenu>>,
text_services: Option<Rc<dyn TextServices>>,
restoration: Option<Rc<dyn Restoration>>,
app_exit: Option<Rc<dyn AppExit>>,
initial_lifecycle_state: Option<AppLifecycleState>,
}
impl TestPlatform {
pub fn new() -> TestPlatform {
TestPlatform {
target: Cell::new(TargetPlatform::Android),
briefly_show_password: Cell::new(true),
brightness: Cell::new(Brightness::Light),
time_zone: RefCell::default(),
default_route: "/".into(),
views: RefCell::default(),
test_views: Vec::new(),
next_request: Cell::new(1),
added_views: RefCell::default(),
frame_requests: RefCell::default(),
dispatcher: Arc::new(TestDispatcher::default()),
font_source: Rc::new(|| Box::new(TestFontSource::new())),
image_codec: None,
pixel_import: None,
picture_to_image: None,
frame_import: None,
buffer_import: None,
windows: None,
clipboard: None,
system_chrome: None,
haptics: None,
system_context_menu: None,
menu_bar: None,
popup_menus: None,
tray_icons: None,
file_dialogs: None,
opener: None,
notifications: None,
compositor: None,
hardware_buffer_allocator: None,
players: None,
media_assets: None,
image_codecs: None,
cameras: None,
video_frame_readers: None,
caption_settings: None,
dock_menu: None,
text_services: None,
restoration: None,
app_exit: None,
initial_lifecycle_state: None,
}
}
pub fn on(self, target: TargetPlatform) -> TestPlatform {
self.target.set(target);
self
}
pub fn with_view(self, view: ViewRef) -> TestPlatform {
self.views.borrow_mut().push(view);
self
}
pub fn with_views(mut self, ids: &[ViewId]) -> TestPlatform {
for &id in ids {
let view = Rc::new(TestView::new(800.0, 600.0).with_id(id));
self.views.borrow_mut().push(Rc::clone(&view) as ViewRef);
self.test_views.push(view);
}
self
}
pub fn test_view(&self, id: ViewId) -> Rc<TestView> {
let view = self.test_views.iter().find(|view| view.id() == id);
Rc::clone(view.expect("a view with_views gave"))
}
pub fn added_views(&self) -> Vec<Rc<TestView>> {
self.added_views.borrow().clone()
}
pub fn give_view(&self, view: ViewRef) {
self.views.borrow_mut().push(view);
}
pub fn take_view(&self, id: ViewId) {
self.views.borrow_mut().retain(|view| view.id() != id);
}
pub fn with_briefly_show_password(self, shown: bool) -> TestPlatform {
self.briefly_show_password.set(shown);
self
}
pub fn with_brightness(self, brightness: Brightness) -> TestPlatform {
self.brightness.set(brightness);
self
}
pub fn with_default_route(mut self, route: impl Into<String>) -> TestPlatform {
self.default_route = route.into();
self
}
pub fn with_initial_lifecycle_state(mut self, state: AppLifecycleState) -> TestPlatform {
self.initial_lifecycle_state = Some(state);
self
}
pub fn with_font_source(
mut self,
make: impl Fn() -> Box<dyn FontSource> + 'static,
) -> TestPlatform {
self.font_source = Rc::new(make);
self
}
pub fn with_image_codec(
mut self,
open: impl Fn(Arc<[u8]>) -> ImageCodecFuture + 'static,
) -> TestPlatform {
self.image_codec = Some(Rc::new(open));
self
}
pub fn with_pixel_import(
mut self,
import: impl Fn(valo::PixelBuffer) -> Option<Image> + 'static,
) -> TestPlatform {
self.pixel_import = Some(Rc::new(import));
self
}
pub fn with_picture_to_image(
mut self,
draw: impl Fn(&Picture, u32, u32) -> Option<Image> + 'static,
) -> TestPlatform {
self.picture_to_image = Some(Rc::new(draw));
self
}
pub fn with_frame_import(
mut self,
import: impl Fn(&dyn VideoFrame) -> Option<Image> + 'static,
) -> TestPlatform {
self.frame_import = Some(Rc::new(import));
self
}
pub fn with_buffer_import(
mut self,
import: impl Fn(&dyn HardwareBuffer) -> Option<Image> + 'static,
) -> TestPlatform {
self.buffer_import = Some(Rc::new(import));
self
}
pub fn with_windows(mut self, windows: Rc<TestWindows>) -> TestPlatform {
self.windows = Some(windows);
self
}
pub fn with_clipboard(mut self, clipboard: Rc<dyn Clipboard>) -> TestPlatform {
self.clipboard = Some(clipboard);
self
}
pub fn with_system_chrome(mut self, system_chrome: Rc<dyn SystemChrome>) -> TestPlatform {
self.system_chrome = Some(system_chrome);
self
}
pub fn with_haptics(mut self, haptics: Rc<dyn Haptics>) -> TestPlatform {
self.haptics = Some(haptics);
self
}
pub fn with_system_context_menu(mut self, menu: Rc<dyn SystemContextMenu>) -> TestPlatform {
self.system_context_menu = Some(menu);
self
}
pub fn with_menu_bar(mut self, menu_bar: Rc<dyn MenuBar>) -> TestPlatform {
self.menu_bar = Some(menu_bar);
self
}
pub fn with_popup_menus(mut self, menus: Rc<dyn PopupMenus>) -> TestPlatform {
self.popup_menus = Some(menus);
self
}
pub fn with_tray_icons(mut self, tray_icons: Rc<dyn TrayIcons>) -> TestPlatform {
self.tray_icons = Some(tray_icons);
self
}
pub fn with_file_dialogs(mut self, file_dialogs: Rc<dyn FileDialogs>) -> TestPlatform {
self.file_dialogs = Some(file_dialogs);
self
}
pub fn with_opener(mut self, opener: Rc<dyn Opener>) -> TestPlatform {
self.opener = Some(opener);
self
}
pub fn with_notifications(mut self, notifications: Rc<dyn Notifications>) -> TestPlatform {
self.notifications = Some(notifications);
self
}
pub fn with_compositor(mut self, compositor: Arc<dyn Compositor>) -> TestPlatform {
self.compositor = Some(compositor);
self
}
pub fn with_hardware_buffer_allocator(
mut self,
allocator: Arc<dyn HardwareBufferAllocator>,
) -> TestPlatform {
self.hardware_buffer_allocator = Some(allocator);
self
}
pub fn with_players(mut self, players: Rc<dyn Players>) -> TestPlatform {
self.players = Some(players);
self
}
pub fn with_media_assets(mut self, media_assets: Rc<dyn MediaAssets>) -> TestPlatform {
self.media_assets = Some(media_assets);
self
}
pub fn with_image_codecs(mut self, image_codecs: Rc<dyn ImageCodecs>) -> TestPlatform {
self.image_codecs = Some(image_codecs);
self
}
pub fn with_cameras(mut self, cameras: Rc<dyn Cameras>) -> TestPlatform {
self.cameras = Some(cameras);
self
}
pub fn with_video_frame_readers(
mut self,
video_frame_readers: Rc<dyn VideoFrameReaders>,
) -> TestPlatform {
self.video_frame_readers = Some(video_frame_readers);
self
}
pub fn with_caption_settings(
mut self,
caption_settings: Rc<dyn CaptionSettings>,
) -> TestPlatform {
self.caption_settings = Some(caption_settings);
self
}
pub fn with_dock_menu(mut self, dock_menu: Rc<dyn DockMenu>) -> TestPlatform {
self.dock_menu = Some(dock_menu);
self
}
pub fn with_text_services(mut self, services: Rc<dyn TextServices>) -> TestPlatform {
self.text_services = Some(services);
self
}
pub fn with_restoration(mut self, restoration: Rc<dyn Restoration>) -> TestPlatform {
self.restoration = Some(restoration);
self
}
pub fn with_app_exit(mut self, app_exit: Rc<dyn AppExit>) -> TestPlatform {
self.app_exit = Some(app_exit);
self
}
pub fn with_time_zone(self, zone: TestTimeZone) -> TestPlatform {
self.set_time_zone(zone);
self
}
pub fn set_target(&self, target: TargetPlatform) {
self.target.set(target);
}
pub fn set_briefly_show_password(&self, shown: bool) {
self.briefly_show_password.set(shown);
}
pub fn set_time_zone(&self, zone: TestTimeZone) {
*self.time_zone.borrow_mut() = zone;
}
pub fn set_brightness(&self, brightness: Brightness) {
self.brightness.set(brightness);
}
pub fn frame_requests(&self) -> Vec<ViewId> {
self.frame_requests.borrow().clone()
}
pub fn has_frame_request(&self, view: ViewId) -> bool {
self.frame_requests.borrow().contains(&view)
}
pub fn take_frame_request(&self, view: ViewId) -> bool {
let mut requests = self.frame_requests.borrow_mut();
let asked = requests.contains(&view);
requests.retain(|&asking| asking != view);
asked
}
pub fn take_frame_requests(&self) -> Vec<ViewId> {
let requests = std::mem::take(&mut *self.frame_requests.borrow_mut());
self.views()
.iter()
.map(|view| view.id())
.filter(|id| requests.contains(id))
.collect()
}
pub fn wakes(&self) -> Vec<Option<Instant>> {
self.dispatcher.timer_wakeups()
}
pub fn wake_now_requests(&self) -> usize {
self.dispatcher.wake_now_requests()
}
fn take_request_id(&self) -> RequestId {
let id = RequestId(self.next_request.get());
self.next_request.set(id.0 + 1);
id
}
}
impl Default for TestPlatform {
fn default() -> TestPlatform {
TestPlatform::new()
}
}
impl Platform for TestPlatform {
fn target_platform(&self) -> TargetPlatform {
self.target.get()
}
fn request_frame(&self, view: ViewId) {
self.frame_requests.borrow_mut().push(view);
}
fn now(&self) -> Instant {
Instant::now()
}
fn dispatcher(&self) -> Arc<dyn Dispatcher> {
Arc::clone(&self.dispatcher) as Arc<dyn Dispatcher>
}
fn views(&self) -> Vec<ViewRef> {
let windows = self.windows.iter().flat_map(|windows| windows.open_views());
let added = self.added_views().into_iter().map(|view| view as ViewRef);
let given = self.views.borrow().clone();
given.into_iter().chain(windows).chain(added).collect()
}
fn view(&self, id: ViewId) -> Option<ViewRef> {
self.views().into_iter().find(|view| view.id() == id)
}
fn request_view(
&self,
config: WindowConfig,
initial_data: Option<String>,
) -> Result<RequestId, ViewError> {
let windows = self.windows.as_ref().ok_or(ViewError::Unsupported)?;
let id = self.take_request_id();
windows.request(id, config, initial_data);
Ok(id)
}
fn briefly_show_password(&self) -> bool {
self.briefly_show_password.get()
}
fn time_zone_offset(&self, seconds_since_epoch: i64) -> SignedDuration {
self.time_zone.borrow().offset(seconds_since_epoch)
}
fn time_zone_name(&self, seconds_since_epoch: i64) -> String {
self.time_zone.borrow().name(seconds_since_epoch)
}
fn platform_brightness(&self) -> Brightness {
self.brightness.get()
}
fn default_route_name(&self) -> String {
self.default_route.clone()
}
fn initial_lifecycle_state(&self) -> Option<AppLifecycleState> {
self.initial_lifecycle_state
}
fn font_source(&self) -> Option<Box<dyn FontSource>> {
Some((self.font_source)())
}
fn open_image_codec(&self, bytes: Arc<[u8]>) -> ImageCodecFuture {
match &self.image_codec {
Some(open) => open(bytes),
None => Box::pin(std::future::ready(Err(ImageDecodeError::NoDecoder))),
}
}
fn import_pixels(&self, pixels: valo::PixelBuffer) -> Option<Image> {
self.pixel_import.as_ref().and_then(|import| import(pixels))
}
fn picture_to_image_sync(&self, picture: &Picture, width: u32, height: u32) -> Option<Image> {
self.picture_to_image
.as_ref()
.and_then(|draw| draw(picture, width, height))
}
fn import_video_frame(&self, frame: &dyn VideoFrame) -> Option<Image> {
self.frame_import.as_ref().and_then(|import| import(frame))
}
fn import_hardware_buffer(&self, buffer: &dyn HardwareBuffer) -> Option<Image> {
self.buffer_import
.as_ref()
.and_then(|import| import(buffer))
}
fn import_texture(
&self,
_buffer: &dyn HardwareBuffer,
_device: &wgpu::Device,
) -> Option<wgpu::Texture> {
None
}
fn clipboard(&self) -> Option<&dyn Clipboard> {
self.clipboard.as_deref()
}
fn system_chrome(&self) -> Option<&dyn SystemChrome> {
self.system_chrome.as_deref()
}
fn haptics(&self) -> Option<&dyn Haptics> {
self.haptics.as_deref()
}
fn system_context_menu(&self) -> Option<&dyn SystemContextMenu> {
self.system_context_menu.as_deref()
}
fn menu_bar(&self) -> Option<&dyn MenuBar> {
self.menu_bar.as_deref()
}
fn popup_menus(&self) -> Option<&dyn PopupMenus> {
self.popup_menus.as_deref()
}
fn tray_icons(&self) -> Option<&dyn TrayIcons> {
self.tray_icons.as_deref()
}
fn file_dialogs(&self) -> Option<&dyn FileDialogs> {
self.file_dialogs.as_deref()
}
fn opener(&self) -> Option<&dyn Opener> {
self.opener.as_deref()
}
fn notifications(&self) -> Option<&dyn Notifications> {
self.notifications.as_deref()
}
fn compositor(&self) -> Option<Arc<dyn Compositor>> {
self.compositor.clone()
}
fn hardware_buffer_allocator(&self) -> Option<Arc<dyn HardwareBufferAllocator>> {
self.hardware_buffer_allocator.clone()
}
fn players(&self) -> Option<&dyn Players> {
self.players.as_deref()
}
fn media_assets(&self) -> Option<&dyn MediaAssets> {
self.media_assets.as_deref()
}
fn image_codecs(&self) -> Option<&dyn ImageCodecs> {
self.image_codecs.as_deref()
}
fn cameras(&self) -> Option<&dyn Cameras> {
self.cameras.as_deref()
}
fn video_frame_readers(&self) -> Option<&dyn VideoFrameReaders> {
self.video_frame_readers.as_deref()
}
fn caption_settings(&self) -> Option<&dyn CaptionSettings> {
self.caption_settings.as_deref()
}
fn view_embedder(&self) -> Option<&dyn ViewEmbedder> {
self.compositor.as_ref().map(|_| self as &dyn ViewEmbedder)
}
fn dock_menu(&self) -> Option<&dyn DockMenu> {
self.dock_menu.as_deref()
}
fn text_services(&self) -> Option<&dyn TextServices> {
self.text_services.as_deref()
}
fn restoration(&self) -> Option<&dyn Restoration> {
self.restoration.as_deref()
}
fn app_exit(&self) -> Option<&dyn AppExit> {
self.app_exit.as_deref()
}
}
impl ViewEmbedder for TestPlatform {
fn add_view(
&self,
_layer: &Arc<dyn CompositionLayer>,
metrics: ViewMetrics,
host: Rc<dyn ViewHost>,
initial_data: Option<String>,
) -> Result<RequestId, ViewError> {
let id = self.take_request_id();
let [width, height] = metrics.physical_size;
let mut view = TestView::with_pixel_ratio(width, height, metrics.device_pixel_ratio)
.with_id(view_of_request(id))
.with_request(id, initial_data)
.with_host(host);
if let Some(screen) = metrics.screen {
view = view.on_screen(screen);
}
self.added_views.borrow_mut().push(Rc::new(view));
Ok(id)
}
fn set_view_metrics(&self, _view: ViewId, _metrics: ViewMetrics) {}
fn set_view_in_sight(&self, _view: ViewId, _in_sight: bool) {}
fn remove_view(&self, view: ViewId) {
self.added_views
.borrow_mut()
.retain(|added| added.id() != view);
}
fn send_pointer_reports(&self, _reports: Vec<PointerReport>) {}
fn send_view_focus_event(&self, _event: ViewFocusEvent) {}
}
#[derive(Default)]
pub struct TestDispatcher {
timer_wakeups: Mutex<Vec<Option<Instant>>>,
wake_now_requests: AtomicUsize,
}
impl TestDispatcher {
pub fn timer_wakeups(&self) -> Vec<Option<Instant>> {
self.timer_wakeups
.lock()
.expect("the wakeups are never poisoned: nothing runs under their lock")
.clone()
}
pub fn wake_now_requests(&self) -> usize {
self.wake_now_requests.load(Ordering::Acquire)
}
}
impl Dispatcher for TestDispatcher {
fn wake_at(&self, timer_wakeup: Option<Instant>) {
self.timer_wakeups
.lock()
.expect("the wakeups are never poisoned: nothing runs under their lock")
.push(timer_wakeup);
}
fn wake_now(&self) {
self.wake_now_requests.fetch_add(1, Ordering::AcqRel);
}
fn dispatch(&self, work: Box<dyn FnOnce() + Send>) {
work();
}
}
#[cfg(test)]
mod tests {
use waft_embedder::Platform;
use super::TestPlatform;
#[test]
fn the_test_platforms_fonts_are_flutter_test() {
let platform = TestPlatform::new();
let mut source = platform.font_source().expect("the test platform has fonts");
assert!(source.family("Roboto")[0].matches("FlutterTest"));
}
#[test]
fn a_test_platform_briefly_shows_passwords_unless_told_not_to() {
assert!(TestPlatform::new().briefly_show_password());
assert!(
!TestPlatform::new()
.with_briefly_show_password(false)
.briefly_show_password()
);
}
#[test]
fn a_change_of_the_setting_is_what_the_platform_answers_next() {
let platform = TestPlatform::new();
platform.set_briefly_show_password(false);
assert!(!platform.briefly_show_password());
platform.set_briefly_show_password(true);
assert!(platform.briefly_show_password());
}
}