use std::sync::Arc;
use uzor::input::{KeyCode, ModifierKeys, MouseButton, Sense, TextFieldConfig};
use uzor::layout::docking::DockPanel;
use uzor::layout::OverlayKind;
use uzor::render::{InvalidateBits, TickRate};
use uzor::{Rect, WidgetId};
use crate::handle::{App, IntentCx, OverlayCx, PanelCx};
use crate::runtime::{RuntimeConfig, MAX_SETTLE};
use crate::types::bus::{ImeInput, InputEvent, KeyInput, PointerInput};
use crate::types::command::{
AppCommand, Binding, CadenceCmd, DockTarget, DragOutChrome, DragOutPolicy, FocusCmd, KeymapCmd,
KeymapScope, LayoutCmd, LayoutPolicy, OverlayCmd, OverlayPolicy, OverlaySize, SplitDir,
};
use crate::types::frame::Wake;
use crate::types::ids::{Seconds, Ticket, WindowId};
use crate::types::intent::{CloseCause, DockIntent, Intent, OverlayIntent, TextIntent};
use crate::types::layout_blob::LayoutBlob;
use crate::types::overlay_model::OverlayModel;
use crate::types::spec::{PanelHome, Spec};
use crate::types::window::{Point, SizePx, WindowCommand};
use crate::Handle;
use super::HeadlessHost as Host;
#[derive(Clone, Debug)]
struct P(&'static str);
impl DockPanel for P {
fn title(&self) -> &str {
self.0
}
fn type_id(&self) -> &'static str {
"p"
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Ov {
Modal,
Second,
Menu,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Act {
Save,
Quit,
}
struct TS;
impl Spec for TS {
type Panel = P;
type Overlay = Ov;
type Action = Act;
fn decode_panel(_home: PanelHome, _type_id: &str) -> Option<P> {
Some(P("restored"))
}
}
struct Field {
id: WidgetId,
rect: Rect,
initial: String,
initialized: bool,
}
#[derive(Default)]
struct TestApp {
intents: Vec<Intent<TS>>,
panel_widgets: Vec<(WidgetId, Rect, Sense)>,
overlay_widgets: Vec<(WidgetId, Rect, Sense)>,
field: Option<Field>,
seen_clicks: Vec<(WidgetId, u8)>,
seen_text: Option<String>,
answer: Option<AppCommand<TS>>,
request_frame: bool,
parents: Vec<(WidgetId, WidgetId)>,
trap: Option<WidgetId>,
seen_focus: Vec<(uzor::input::core::events::FocusEvent, String, bool)>,
scroller: Option<(Rect, f64, crate::ScrollView)>,
scroll_key: Option<crate::ScrollKey>,
seen_gestures: Vec<crate::types::gesture::Gesture>,
top_widgets: Vec<(WidgetId, Rect, Sense)>,
seen_captured: Vec<(WidgetId, crate::types::gesture::Gesture)>,
paint_slot: Option<Rect>,
seen_slot: Vec<crate::types::gesture::Gesture>,
seen_context: Vec<(f64, f64)>,
seen_insets: Option<(crate::types::window::Insets, f64, bool)>,
chrome: crate::types::command::ChromeModel,
}
impl App for TestApp {
type Spec = TS;
fn overlay_model(&self, _win: WindowId, _id: Ov) -> OverlayModel {
OverlayModel::default()
}
fn chrome_model(&self, _win: WindowId) -> crate::types::command::ChromeModel {
self.chrome.clone()
}
fn panel(&mut self, cx: &mut PanelCx<'_, TS>) {
for (id, rect, sense) in &self.panel_widgets {
cx.widgets
.coord
.register_on_layer(id.clone(), *rect, *sense, &cx.widgets.layer);
}
for (c, p) in &self.parents {
cx.widgets.coord.set_widget_parent(c, p);
}
cx.widgets.coord.set_focus_trap(self.trap.as_ref());
let seen = &mut self.seen_focus;
cx.view.dispatch_focus(|ev, e| seen.push((ev, e.current.as_str().to_string(), e.at_target())));
if let Some(field) = &mut self.field {
cx.widgets.coord.register_text_field(
field.id.clone(),
field.rect,
TextFieldConfig::text(),
);
if !field.initialized {
cx.widgets
.coord
.text_fields_mut()
.set_text(&field.id, &field.initial);
field.initialized = true;
}
let n = cx
.widgets
.coord
.text_fields()
.text(&field.id)
.chars()
.count();
let r = field.rect;
cx.widgets.coord.text_fields_mut().update_field(
&field.id,
(r.x, r.y, r.width, r.height),
(0..=n).map(|i| r.x + i as f64 * 8.0).collect(),
);
self.seen_text = Some(cx.widgets.coord.text_fields().text(&field.id).to_string());
}
if let Some((vp, h, sv)) = &mut self.scroller {
if let Some(k) = self.scroll_key.take() {
crate::widgets::queue_scroll_key(cx, k);
}
let st = crate::ScrollStyle::default();
let _ = crate::widgets::scroll_begin(cx, "list", *vp, sv, *h, true, &st);
crate::widgets::scroll_end(cx, "list", *vp, sv, &st);
}
for (id, rect, sense) in &self.top_widgets {
cx.widgets.coord.register_on_layer(id.clone(), *rect, *sense, &cx.widgets.layer);
}
if let Some(r) = self.paint_slot {
let resp = crate::widgets::kit::paint_slot("slot", r).paint(cx, |_, _| {});
self.seen_slot.extend(resp.gestures);
}
self.seen_clicks.extend(cx.view.clicks().iter().cloned());
self.seen_gestures.extend(cx.view.gestures().iter().copied());
self.seen_captured.extend(cx.view.captured_gestures.iter().cloned());
self.seen_context.extend(cx.view.context_click());
self.seen_insets = Some((cx.view.safe_area(), cx.view.keyboard(), cx.view.coarse_pointer()));
if self.request_frame {
cx.out.request_frame();
}
}
fn overlay_body(&mut self, cx: &mut OverlayCx<'_, TS>) {
for (id, rect, sense) in &self.overlay_widgets {
cx.widgets
.coord
.register_on_layer(id.clone(), *rect, *sense, &cx.widgets.layer);
}
}
fn intent(&mut self, intent: Intent<TS>, cx: &mut IntentCx<'_, TS>) {
if let Intent::Unhandled(crate::types::intent::UnhandledInput::Key { key, .. }) = &intent {
if key.state != crate::types::bus::KeyState::Up {
self.scroll_key = crate::ScrollKey::from_key(key.code, key.mods).or(self.scroll_key);
}
}
self.intents.push(intent);
if let Some(cmd) = &self.answer {
cx.command(cmd.clone());
}
}
}
fn wid(name: &str) -> WidgetId {
WidgetId::from(name)
}
fn mods_ctrl() -> ModifierKeys {
ModifierKeys {
ctrl: true,
..ModifierKeys::default()
}
}
fn host() -> (Host<TS, TestApp>, Handle<TS>) {
Host::new(TestApp::default(), RuntimeConfig::default())
}
fn open_main(h: &mut Host<TS, TestApp>) -> WindowId {
h.open_window(SizePx::new(800, 600), 1.0)
}
fn open_with_panel(h: &mut Host<TS, TestApp>, handle: &Handle<TS>) -> WindowId {
let win = open_main(h);
handle
.dispatch(AppCommand::Layout(LayoutCmd::OpenPanel {
win,
panel: P("main"),
at: DockTarget::Root,
}))
.expect("dispatch");
h.advance(0.017);
h.advance(0.017);
win
}
fn down(h: &mut Host<TS, TestApp>, win: WindowId, x: f64, y: f64) {
h.input(
win,
InputEvent::Pointer(PointerInput::Down {
pos: Point::new(x, y),
button: MouseButton::Left,
mods: ModifierKeys::default(),
}),
);
}
fn up(h: &mut Host<TS, TestApp>, win: WindowId, x: f64, y: f64) {
h.input(
win,
InputEvent::Pointer(PointerInput::Up {
pos: Point::new(x, y),
button: MouseButton::Left,
mods: ModifierKeys::default(),
}),
);
}
fn mov(h: &mut Host<TS, TestApp>, win: WindowId, x: f64, y: f64) {
h.input(
win,
InputEvent::Pointer(PointerInput::Moved {
pos: Point::new(x, y),
mods: ModifierKeys::default(),
}),
);
}
fn click(h: &mut Host<TS, TestApp>, win: WindowId, x: f64, y: f64) {
down(h, win, x, y);
h.advance(0.017);
up(h, win, x, y);
h.advance(0.017);
h.advance(0.017);
}
fn key(
h: &mut Host<TS, TestApp>,
win: WindowId,
code: KeyCode,
mods: ModifierKeys,
text: Option<&str>,
) {
h.input(
win,
InputEvent::Key(KeyInput {
code,
text: text.map(str::to_string),
state: crate::types::bus::KeyState::Down,
mods,
}),
);
h.advance(0.017);
h.input(
win,
InputEvent::Key(KeyInput {
code,
text: None,
state: crate::types::bus::KeyState::Up,
mods,
}),
);
h.advance(0.017);
h.advance(0.017);
}
fn open_overlay(
h: &mut Host<TS, TestApp>,
handle: &Handle<TS>,
win: WindowId,
id: Ov,
kind: OverlayKind,
policy: OverlayPolicy,
) {
handle
.dispatch(AppCommand::Overlay(OverlayCmd::Open {
win,
id,
kind,
anchor: Some(Rect::new(100.0, 100.0, 10.0, 10.0)),
size: OverlaySize::Fixed {
width: 200.0,
height: 120.0,
},
policy: Some(policy),
}))
.expect("dispatch");
h.advance(0.017);
h.advance(0.017);
}
fn policy(modal: bool, outside: bool, escape: bool, restore: bool) -> OverlayPolicy {
OverlayPolicy {
modal,
dismiss_on_outside: outside,
dismiss_on_escape: escape,
restore_focus: restore,
auto_close_after: None,
keymap_scope: false,
}
}
fn overlay_closed(app: &TestApp, id: Ov) -> Option<CloseCause> {
app.intents.iter().rev().find_map(|i| match i {
Intent::Overlay(OverlayIntent::Closed { id: got, cause, .. }) if *got == id => Some(*cause),
_ => None,
})
}
fn has_unhandled_pointer(app: &TestApp) -> bool {
app.intents.iter().any(|i| {
matches!(
i,
Intent::Unhandled(crate::types::intent::UnhandledInput::Pointer { .. })
)
})
}
fn focused(h: &Host<TS, TestApp>, win: WindowId) -> Option<WidgetId> {
h.snapshot()
.window(win)
.and_then(|w| w.input.focused.clone())
}
#[test]
fn modal_shield_blocks_content_clicks() {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
h.runtime_mut().app_mut().panel_widgets.push((
wid("btn"),
Rect::new(10.0, 100.0, 60.0, 24.0),
Sense::CLICK,
));
open_overlay(
&mut h,
&handle,
win,
Ov::Modal,
OverlayKind::Modal,
policy(true, false, true, true),
);
click(&mut h, win, 20.0, 112.0);
let app = h.runtime().app();
assert!(
!app.seen_clicks.iter().any(|(id, _)| *id == wid("btn")),
"the modal shield leaked a click to content: {:?}",
app.seen_clicks
);
assert!(
!has_unhandled_pointer(app),
"a shielded click is consumed, not unhandled: {:?}",
app.intents
);
assert!(h
.snapshot()
.window(win)
.is_some_and(|w| w.overlays.len() == 1));
}
#[test]
fn outside_click_dismisses_dropdown() {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
h.runtime_mut().app_mut().panel_widgets.push((
wid("btn"),
Rect::new(500.0, 400.0, 60.0, 24.0),
Sense::CLICK,
));
open_overlay(
&mut h,
&handle,
win,
Ov::Menu,
OverlayKind::Dropdown,
policy(false, true, true, true),
);
click(&mut h, win, 520.0, 410.0);
assert_eq!(
overlay_closed(h.runtime().app(), Ov::Menu),
Some(CloseCause::Outside)
);
assert!(h
.snapshot()
.window(win)
.is_some_and(|w| w.overlays.is_empty()));
assert!(
!h.runtime()
.app()
.seen_clicks
.iter()
.any(|(id, _)| *id == wid("btn")),
"the dismissing click must be consumed, not delivered"
);
}
#[test]
fn escape_closes_overlays_top_first() {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
open_overlay(
&mut h,
&handle,
win,
Ov::Modal,
OverlayKind::Modal,
policy(true, true, true, true),
);
open_overlay(
&mut h,
&handle,
win,
Ov::Second,
OverlayKind::Modal,
policy(true, true, true, true),
);
assert!(h
.snapshot()
.window(win)
.is_some_and(|w| w.overlays.len() == 2));
key(&mut h, win, KeyCode::Escape, ModifierKeys::default(), None);
assert_eq!(
overlay_closed(h.runtime().app(), Ov::Second),
Some(CloseCause::Escape)
);
assert_eq!(
overlay_closed(h.runtime().app(), Ov::Modal),
None,
"one Escape, one close"
);
assert!(h
.snapshot()
.window(win)
.is_some_and(|w| w.overlays.len() == 1));
key(&mut h, win, KeyCode::Escape, ModifierKeys::default(), None);
assert_eq!(
overlay_closed(h.runtime().app(), Ov::Modal),
Some(CloseCause::Escape)
);
assert!(h
.snapshot()
.window(win)
.is_some_and(|w| w.overlays.is_empty()));
}
#[test]
fn focus_restores_after_overlay_scope() {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
h.runtime_mut().app_mut().panel_widgets.push((
wid("fld"),
Rect::new(10.0, 100.0, 60.0, 24.0),
Sense::CLICK.union(Sense::FOCUSABLE),
));
h.advance(0.017);
click(&mut h, win, 20.0, 112.0);
assert_eq!(
focused(&h, win),
Some(wid("fld")),
"click focuses a FOCUSABLE widget"
);
open_overlay(
&mut h,
&handle,
win,
Ov::Modal,
OverlayKind::Modal,
policy(true, true, true, true),
);
key(&mut h, win, KeyCode::Escape, ModifierKeys::default(), None);
assert_eq!(
overlay_closed(h.runtime().app(), Ov::Modal),
Some(CloseCause::Escape)
);
assert_eq!(
focused(&h, win),
Some(wid("fld")),
"the scope's saved focus must return"
);
}
#[test]
fn tab_order_trap_and_focus_events() {
use uzor::input::core::events::FocusEvent::*;
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
let f = Sense::CLICK.union(Sense::FOCUSABLE);
{
let app = h.runtime_mut().app_mut();
app.panel_widgets.push((wid("a"), Rect::new(10.0, 100.0, 60.0, 24.0), f));
app.panel_widgets.push((wid("dlg"), Rect::new(100.0, 100.0, 200.0, 100.0), Sense::CLICK));
app.panel_widgets.push((wid("ok"), Rect::new(110.0, 110.0, 40.0, 24.0), f));
app.panel_widgets.push((wid("no"), Rect::new(160.0, 110.0, 40.0, 24.0), f));
app.parents = vec![(wid("ok"), wid("dlg")), (wid("no"), wid("dlg"))];
}
h.advance(0.017);
let tab = |h: &mut Host<TS, TestApp>, shift: bool| {
let m = ModifierKeys { shift, ..ModifierKeys::default() };
key(h, win, KeyCode::Tab, m, None);
h.advance(0.017);
};
tab(&mut h, false);
assert_eq!(focused(&h, win), Some(wid("a")));
tab(&mut h, false);
assert_eq!(focused(&h, win), Some(wid("ok")));
h.advance(0.017);
let seen = std::mem::take(&mut h.runtime_mut().app_mut().seen_focus);
let at: Vec<_> = seen.iter().filter(|e| e.2).map(|e| (e.0, e.1.as_str())).collect();
assert_eq!(at, [(Focus, "a"), (FocusIn, "a"), (Blur, "a"), (FocusOut, "a"), (Focus, "ok"), (FocusIn, "ok")]);
assert!(seen.contains(&(FocusIn, "dlg".into(), false)), "focusin bubbles to the dialog: {seen:?}");
h.runtime_mut().app_mut().trap = Some(wid("dlg"));
h.advance(0.017);
for _ in 0..3 {
tab(&mut h, false);
assert_ne!(focused(&h, win), Some(wid("a")), "Tab must not leave the trap");
}
for _ in 0..3 {
tab(&mut h, true);
assert_ne!(focused(&h, win), Some(wid("a")), "Shift+Tab must not leave the trap");
}
h.runtime_mut().app_mut().trap = None;
h.advance(0.017);
for _ in 0..3 {
tab(&mut h, false);
}
assert!(h.runtime().app().seen_focus.iter().any(|e| e.0 == Focus && e.1 == "a"));
}
#[test]
fn tab_focus_move_requests_a_frame() {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
let f = Sense::CLICK.union(Sense::FOCUSABLE);
{
let app = h.runtime_mut().app_mut();
app.panel_widgets.push((wid("a"), Rect::new(10.0, 100.0, 60.0, 24.0), f));
app.panel_widgets.push((wid("b"), Rect::new(80.0, 100.0, 60.0, 24.0), f));
}
handle
.dispatch(AppCommand::Cadence(CadenceCmd::SetTickRate { win, rate: TickRate::Dirty }))
.expect("dispatch");
handle
.dispatch(AppCommand::Cadence(CadenceCmd::Invalidate { win, region: None, bits: InvalidateBits::ALL }))
.expect("dispatch");
h.advance(0.0);
let down = |h: &mut Host<TS, TestApp>, state| {
h.input(
win,
InputEvent::Key(KeyInput { code: KeyCode::Tab, text: None, state, mods: ModifierKeys::default() }),
);
};
for want in ["a", "b", "a"] {
for _ in 0..3 {
h.advance(0.05);
}
assert!(!h.advance(0.05).frames.iter().any(|fr| fr.window == win), "settled before Tab");
down(&mut h, crate::types::bus::KeyState::Down);
assert!(h.advance(0.0).frames.iter().any(|fr| fr.window == win), "Tab to {want} must paint");
assert_eq!(focused(&h, win), Some(wid(want)));
down(&mut h, crate::types::bus::KeyState::Up);
}
}
#[test]
fn keymap_precedence_focused_global_modal() {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
h.runtime_mut().app_mut().panel_widgets.push((
wid("fld"),
Rect::new(10.0, 100.0, 60.0, 24.0),
Sense::CLICK.union(Sense::FOCUSABLE),
));
let chord = uzor::input::KeyboardShortcut::new(mods_ctrl(), KeyCode::S);
handle
.dispatch(AppCommand::Keymap(KeymapCmd::Bind {
scope: KeymapScope::Global,
binding: Binding::new(chord.clone(), Act::Save),
}))
.expect("dispatch");
handle
.dispatch(AppCommand::Keymap(KeymapCmd::Bind {
scope: KeymapScope::Focused(wid("fld")),
binding: Binding::new(chord.clone(), Act::Quit),
}))
.expect("dispatch");
h.advance(0.017);
click(&mut h, win, 20.0, 112.0);
assert_eq!(focused(&h, win), Some(wid("fld")));
key(&mut h, win, KeyCode::S, mods_ctrl(), None);
assert!(
h.runtime()
.app()
.intents
.iter()
.any(|i| matches!(i, Intent::Action(Act::Quit))),
"the focused binding must win: {:?}",
h.runtime().app().intents
);
handle
.dispatch(AppCommand::Focus(FocusCmd::Clear { win }))
.expect("dispatch");
h.advance(0.017);
key(&mut h, win, KeyCode::S, mods_ctrl(), None);
assert!(
h.runtime()
.app()
.intents
.iter()
.any(|i| matches!(i, Intent::Action(Act::Save))),
"the global binding must resolve once blurred"
);
open_overlay(
&mut h,
&handle,
win,
Ov::Modal,
OverlayKind::Modal,
policy(true, true, true, true),
);
let before = h.runtime().app().intents.len();
key(&mut h, win, KeyCode::S, mods_ctrl(), None);
assert!(
!h.runtime().app().intents[before..]
.iter()
.any(|i| matches!(i, Intent::Action(_))),
"an open modal shields global bindings: {:?}",
&h.runtime().app().intents[before..]
);
}
#[test]
fn click_cook_counts_double_click() {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
h.runtime_mut().app_mut().panel_widgets.push((
wid("btn"),
Rect::new(10.0, 100.0, 60.0, 24.0),
Sense::CLICK,
));
h.advance(0.017);
click(&mut h, win, 20.0, 112.0);
click(&mut h, win, 20.0, 112.0);
let app = h.runtime().app();
assert!(
app.seen_clicks
.iter()
.any(|(id, n)| *id == wid("btn") && *n == 2),
"expected a double click in {:?}",
app.seen_clicks
);
}
#[test]
fn widget_capture_survives_leaving_the_rect() {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
h.runtime_mut().app_mut().panel_widgets.push((
wid("drag"),
Rect::new(10.0, 100.0, 60.0, 24.0),
Sense::CLICK_AND_DRAG,
));
h.advance(0.017);
down(&mut h, win, 20.0, 112.0);
h.advance(0.017);
mov(&mut h, win, 30.0, 112.0);
h.advance(0.017);
mov(&mut h, win, 700.0, 500.0);
h.advance(0.017);
assert!(
h.snapshot().window(win).is_some_and(|w| w.input.captured),
"the drag must hold the capture outside the rect"
);
up(&mut h, win, 700.0, 500.0);
h.advance(0.017);
assert!(
h.snapshot().window(win).is_some_and(|w| !w.input.captured),
"pointer-up ends the capture"
);
}
#[test]
fn route_hops_stay_within_three() {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
h.runtime_mut().app_mut().panel_widgets.push((
wid("btn"),
Rect::new(10.0, 100.0, 60.0, 24.0),
Sense::CLICK,
));
open_overlay(
&mut h,
&handle,
win,
Ov::Modal,
OverlayKind::Modal,
policy(true, true, true, true),
);
click(&mut h, win, 20.0, 112.0); key(&mut h, win, KeyCode::Escape, ModifierKeys::default(), None);
click(&mut h, win, 20.0, 112.0); key(&mut h, win, KeyCode::S, mods_ctrl(), None);
let max = h.runtime().kernel().trace_max();
assert!(
max + 1 <= 3,
"the longest route was {} hops (+1 for push_input): {:?}",
max + 1,
h.runtime().kernel().last_trace()
);
}
#[test]
fn publish_keeps_the_same_arc_when_nothing_changes() {
let (mut h, handle) = host();
let _win = open_with_panel(&mut h, &handle);
let before = h.snapshot();
h.advance(0.0);
h.advance(0.0);
let after = h.snapshot();
assert!(
Arc::ptr_eq(&before, &after),
"a quiet tick must not republish"
);
assert_eq!(before.revision, after.revision);
}
#[test]
fn publish_bumps_revision_once_per_pass() {
let (mut h, handle) = host();
let win = open_main(&mut h);
let r0 = h.snapshot().revision;
for name in ["a", "b"] {
handle
.dispatch(AppCommand::Layout(LayoutCmd::OpenPanel {
win,
panel: P(name),
at: DockTarget::Root,
}))
.expect("dispatch");
}
h.advance(0.0);
let r1 = h.snapshot().revision;
assert_eq!(
r1.get(),
r0.get() + 1,
"two panels in one pass must be a single bump ({r0:?} -> {r1:?})"
);
}
#[test]
fn settle_loop_is_bounded() {
let (mut h, _handle) = Host::new(TestApp::default(), RuntimeConfig::default());
let win = open_main(&mut h);
h.runtime_mut().app_mut().answer = Some(AppCommand::Cadence(CadenceCmd::WakeAt {
token: 1,
at: Seconds::ZERO,
}));
h.runtime_mut().app_mut().intents.clear();
down(&mut h, win, 700.0, 500.0); let wake = h.advance(0.017).wake;
let timers = h
.runtime()
.app()
.intents
.iter()
.filter(|i| matches!(i, Intent::Timer(1)))
.count();
assert_eq!(timers, MAX_SETTLE, "one timer per settle pass, then stop");
assert!(
matches!(wake, Wake::Immediate),
"the unanswered timer keeps the runtime hot: {wake:?}"
);
}
#[test]
fn cadence_cap_and_dirty() {
let (mut h, handle) = host();
let win = open_main(&mut h);
handle
.dispatch(AppCommand::Cadence(CadenceCmd::SetTickRate {
win,
rate: TickRate::Capped(10),
}))
.expect("dispatch");
h.advance(0.0);
assert!(
!h.advance(0.05).frames.iter().any(|f| f.window == win),
"0.05 s < the 0.1 s slot: no frame"
);
let (framed, wake) = {
let out = h.advance(0.06);
(out.frames.iter().any(|f| f.window == win), out.wake)
};
assert!(framed, "0.11 s crossed the slot: frame");
assert!(
matches!(wake, Wake::At(_)),
"a capped window schedules its next slot: {wake:?}"
);
handle
.dispatch(AppCommand::Cadence(CadenceCmd::SetTickRate {
win,
rate: TickRate::Dirty,
}))
.expect("dispatch");
h.advance(0.0);
assert!(
h.advance(0.5).frames.is_empty(),
"dirty and quiet: no frame, however long the step"
);
handle
.dispatch(AppCommand::Cadence(CadenceCmd::Invalidate {
win,
region: None,
bits: InvalidateBits::MATERIAL,
}))
.expect("dispatch");
assert!(
h.advance(0.0).frames.iter().any(|f| f.window == win),
"an invalidation wakes a dirty window"
);
}
#[test]
fn determinism_same_script_same_snapshot() {
fn script() -> Host<TS, TestApp> {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
h.runtime_mut().app_mut().panel_widgets.push((
wid("btn"),
Rect::new(10.0, 100.0, 60.0, 24.0),
Sense::CLICK.union(Sense::FOCUSABLE),
));
h.advance(0.017);
click(&mut h, win, 20.0, 112.0);
key(&mut h, win, KeyCode::S, mods_ctrl(), None);
open_overlay(
&mut h,
&handle,
win,
Ov::Menu,
OverlayKind::Dropdown,
policy(false, true, true, true),
);
click(&mut h, win, 400.0, 300.0); h.advance(0.017);
h
}
let a = script();
let b = script();
assert_eq!(
*a.snapshot(),
*b.snapshot(),
"identical scripts must publish identical snapshots"
);
}
fn split_two_columns(
h: &mut Host<TS, TestApp>,
handle: &Handle<TS>,
win: WindowId,
) -> (uzor::layout::docking::LeafId, Rect) {
let leaf = h.snapshot().window(win).expect("window").dock.leaves[0].leaf;
handle
.dispatch(AppCommand::Layout(LayoutCmd::Split {
win,
leaf,
dir: SplitDir::Right,
panel: P("b"),
}))
.expect("dispatch");
h.advance(0.017);
h.advance(0.017);
let snap = h.snapshot();
let dock = &snap.window(win).expect("window").dock;
assert_eq!(dock.leaves.len(), 2, "the split made a second leaf");
assert_eq!(dock.separators.len(), 1, "one separator between them");
(leaf, dock.separators[0].rect)
}
#[test]
fn splitter_drag_moves_and_clamps() {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
let (left_leaf, sep) = split_two_columns(&mut h, &handle, win);
let left_width = |h: &Host<TS, TestApp>| {
h.snapshot()
.window(win)
.and_then(|w| {
w.dock
.leaves
.iter()
.find(|l| l.leaf == left_leaf)
.map(|l| l.rect.width)
})
.expect("the left leaf survives")
};
let before = left_width(&h);
let cx = sep.x + sep.width / 2.0;
let cy = sep.y + sep.height / 2.0;
down(&mut h, win, cx, cy);
h.advance(0.017);
mov(&mut h, win, cx + 150.0, cy);
h.advance(0.017);
up(&mut h, win, cx + 150.0, cy);
h.advance(0.017);
let grown = left_width(&h);
assert!(
grown > before,
"the separator follows the drag: {before} -> {grown}"
);
for _ in 0..2 {
let from = left_width(&h);
down(&mut h, win, cx + from - before, cy);
h.advance(0.017);
mov(&mut h, win, cx + from - before + 2000.0, cy);
h.advance(0.017);
up(&mut h, win, cx + from - before + 2000.0, cy);
h.advance(0.017);
}
assert_eq!(
left_width(&h),
left_width(&h),
"clamped at the minimum (idempotent)"
);
let clamped = left_width(&h);
down(&mut h, win, cx + clamped - before, cy);
h.advance(0.017);
mov(&mut h, win, cx + clamped - before + 2000.0, cy);
h.advance(0.017);
up(&mut h, win, cx + clamped - before + 2000.0, cy);
h.advance(0.017);
assert_eq!(left_width(&h), clamped, "the clamp holds");
}
#[test]
fn dock_tab_merge_via_drag() {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
let (left_leaf, _sep) = split_two_columns(&mut h, &handle, win);
let (from, to) = {
let snap = h.snapshot();
let dock = &snap.window(win).expect("window").dock;
let from = dock
.leaves
.iter()
.find(|l| l.leaf != left_leaf)
.expect("right leaf")
.rect;
let to = dock
.leaves
.iter()
.find(|l| l.leaf == left_leaf)
.expect("left leaf")
.rect;
(from, to)
};
down(&mut h, win, from.x + from.width / 2.0, from.y + 12.0);
h.advance(0.017);
mov(&mut h, win, to.x + to.width / 2.0, to.y + to.height / 2.0);
h.advance(0.017);
up(&mut h, win, to.x + to.width / 2.0, to.y + to.height / 2.0);
h.advance(0.017);
h.advance(0.017);
let snap = h.snapshot();
let dock = &snap.window(win).expect("window").dock;
assert_eq!(
dock.leaves.len(),
1,
"the drop merged the leaves: {:?}",
dock.leaves
);
assert_eq!(dock.leaves[0].panels.len(), 2, "two tabs in the survivor");
}
#[test]
fn expand_right_gutter_exactly_once() {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
let gutter_x = 796.0;
down(&mut h, win, 700.0, 12.0); h.advance(0.017);
mov(&mut h, win, gutter_x, 300.0);
h.advance(0.017);
h.advance(1.0); up(&mut h, win, gutter_x, 300.0);
h.advance(0.017);
h.advance(0.5);
let expansions = h
.command_log()
.iter()
.filter(|(_, c)| matches!(c, WindowCommand::SetOuterRect { size, .. } if size.width > 800))
.count();
assert_eq!(expansions, 1, "one gutter dwell expands exactly once");
}
#[test]
fn drag_out_spawns_window() {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
handle
.dispatch(AppCommand::Layout(LayoutCmd::SetPolicy(LayoutPolicy {
drag_out: DragOutPolicy::Enabled {
chrome: DragOutChrome::Os,
},
..LayoutPolicy::default()
})))
.expect("dispatch");
h.advance(0.017);
let (left_leaf, _sep) = split_two_columns(&mut h, &handle, win);
let from = {
let snap = h.snapshot();
let dock = &snap.window(win).expect("window").dock;
dock.leaves
.iter()
.find(|l| l.leaf != left_leaf)
.expect("right leaf")
.rect
};
down(&mut h, win, from.x + from.width / 2.0, from.y + 12.0);
h.advance(0.017);
mov(&mut h, win, 700.0, 60.0);
h.advance(0.017);
mov(&mut h, win, 1150.0, 300.0); h.advance(0.017);
up(&mut h, win, 1150.0, 300.0);
h.advance(0.017);
h.advance(0.017);
assert!(
h.command_log()
.iter()
.any(|(_, c)| matches!(c, WindowCommand::Spawn(_))),
"the tear-off asked the host for a window"
);
assert_eq!(
h.snapshot().windows.len(),
2,
"the torn-off panel lives in its own window"
);
assert!(
h.snapshot()
.windows
.iter()
.all(|w| w.id == win || !w.dock.leaves.is_empty()),
"the new window holds a docked panel"
);
}
#[test]
fn layout_blob_roundtrip() {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
handle
.dispatch(AppCommand::Layout(LayoutCmd::OpenPanel {
win,
panel: P("b"),
at: DockTarget::Root,
}))
.expect("dispatch");
h.advance(0.017);
let panel_count = |h: &Host<TS, TestApp>| {
h.snapshot()
.window(win)
.map(|w| w.dock.leaves.iter().map(|l| l.panels.len()).sum::<usize>())
.unwrap_or(0)
};
assert_eq!(panel_count(&h), 2);
handle
.dispatch(AppCommand::Layout(LayoutCmd::RequestBlob {
win,
ticket: Ticket(7),
}))
.expect("dispatch");
h.advance(0.017);
let blob = h
.runtime()
.app()
.intents
.iter()
.find_map(|i| match i {
Intent::Dock(DockIntent::LayoutBlob { ticket, blob, .. }) if *ticket == Ticket(7) => {
Some(LayoutBlob::from_bytes(blob.as_bytes().to_vec()))
}
_ => None,
})
.expect("the blob intent answers the request");
let leaf = h.snapshot().window(win).expect("window").dock.leaves[0].leaf;
handle
.dispatch(AppCommand::Layout(LayoutCmd::ClosePanel {
win,
leaf,
index: 1,
}))
.expect("dispatch");
h.advance(0.017);
assert_eq!(panel_count(&h), 1, "the close mutated the layout");
handle
.dispatch(AppCommand::Layout(LayoutCmd::Restore { win, blob }))
.expect("dispatch");
h.advance(0.017);
assert!(
h.runtime()
.app()
.intents
.iter()
.any(|i| matches!(i, Intent::Dock(DockIntent::LayoutRestored { .. }))),
"restore reports success: {:?}",
h.runtime().app().intents
);
assert_eq!(panel_count(&h), 2, "the captured structure is back");
}
#[test]
fn text_ime_clipboard_flow() {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
h.runtime_mut().app_mut().field = Some(Field {
id: wid("field"),
rect: Rect::new(10.0, 100.0, 200.0, 24.0),
initial: "hi".to_string(),
initialized: false,
});
h.advance(0.017);
click(&mut h, win, 30.0, 112.0); assert_eq!(
focused(&h, win),
Some(wid("field")),
"click focuses the field"
);
key(&mut h, win, KeyCode::A, ModifierKeys::default(), Some("a"));
assert!(
h.runtime().app().intents.iter().any(|i| matches!(
i,
Intent::Text(TextIntent::Changed { field, .. }) if *field == wid("field")
)),
"typing reports Changed: {:?}",
h.runtime().app().intents
);
assert_eq!(h.runtime().app().seen_text.as_deref(), Some("hia"));
h.input(
win,
InputEvent::Ime(ImeInput::Preedit {
text: "\u{301}".to_string(),
cursor: None,
}),
);
h.advance(0.017);
h.advance(0.017);
assert_eq!(
h.runtime().app().seen_text.as_deref(),
Some("hia"),
"preedit never enters the buffer"
);
h.input(win, InputEvent::Ime(ImeInput::Commit("!".to_string())));
h.advance(0.017);
h.advance(0.017);
assert_eq!(h.runtime().app().seen_text.as_deref(), Some("hia!"));
key(&mut h, win, KeyCode::A, mods_ctrl(), None); h.input(
win,
InputEvent::Key(KeyInput {
code: KeyCode::C,
text: None,
state: crate::types::bus::KeyState::Down,
mods: mods_ctrl(),
}),
);
let copied = h
.advance(0.017)
.window_commands
.iter()
.any(|(_, c)| matches!(c, WindowCommand::ClipboardWrite(t) if t == "hia!"));
assert!(copied, "Ctrl+C writes the selection to the clipboard");
key(&mut h, win, KeyCode::Enter, ModifierKeys::default(), None);
assert!(
h.runtime().app().intents.iter().any(|i| matches!(
i,
Intent::Text(TextIntent::Submitted { field, .. }) if *field == wid("field")
)),
"Enter submits: {:?}",
h.runtime().app().intents
);
}
#[test]
fn touch_tap_clicks_content() {
use crate::types::bus::TouchInput;
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
h.runtime_mut().app_mut().panel_widgets.push((wid("btn"), Rect::new(10.0, 100.0, 60.0, 24.0), Sense::CLICK));
h.advance(0.017);
h.input(win, InputEvent::Touch(TouchInput::Start { id: 7, pos: Point::new(20.0, 112.0) }));
h.advance(0.017);
h.input(win, InputEvent::Touch(TouchInput::End { id: 7, pos: Point::new(20.0, 112.0) }));
h.advance(0.017);
h.advance(0.017);
let app = h.runtime().app();
assert!(app.seen_clicks.iter().any(|(id, _)| *id == wid("btn")), "tap did not click: {:?}", app.seen_clicks);
}
#[test]
fn touch_pan_scrolls_without_clicking_and_flings() {
use crate::types::bus::TouchInput;
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
h.runtime_mut().app_mut().scroller = Some((Rect::new(0.0, 0.0, 400.0, 300.0), 3000.0, crate::ScrollView::default()));
h.runtime_mut().app_mut().panel_widgets.push((wid("row"), Rect::new(10.0, 150.0, 300.0, 40.0), Sense::CLICK));
h.runtime_mut().app_mut().request_frame = true;
h.advance(0.017);
let off = |h: &Host<TS, TestApp>| h.runtime().app().scroller.as_ref().unwrap().2.offset;
h.input(win, InputEvent::Touch(TouchInput::Start { id: 1, pos: Point::new(100.0, 250.0) }));
h.advance(0.008);
let mut y = 250.0;
for _ in 0..15 {
y -= 10.0;
h.input(win, InputEvent::Touch(TouchInput::Move { id: 1, pos: Point::new(100.0, y) }));
h.advance(0.017);
}
let at_lift = off(&h);
assert!((at_lift - 140.0).abs() < 1.0, "1:1 after the slop: {at_lift}");
h.input(win, InputEvent::Touch(TouchInput::End { id: 1, pos: Point::new(100.0, y) }));
for _ in 0..30 {
h.advance(0.016);
}
let after = off(&h);
assert!(after > at_lift + 100.0, "fling carried on: {at_lift} -> {after}");
let app = h.runtime().app();
assert!(!app.seen_clicks.iter().any(|(id, _)| *id == wid("row")), "a pan never clicks: {:?}", app.seen_clicks);
assert!(app.seen_gestures.iter().any(|g| matches!(g, crate::types::gesture::Gesture::PanStart { axis: crate::types::gesture::Axis::Vertical, .. })));
h.input(win, InputEvent::Touch(TouchInput::Start { id: 2, pos: Point::new(100.0, 170.0) }));
h.advance(0.017);
h.advance(0.017);
let stopped = off(&h);
h.input(win, InputEvent::Touch(TouchInput::End { id: 2, pos: Point::new(100.0, 170.0) }));
for _ in 0..10 {
h.advance(0.016);
}
assert!((off(&h) - stopped).abs() < 0.5, "stays where the finger stopped it");
assert!(!h.runtime().app().seen_clicks.iter().any(|(id, _)| *id == wid("row")));
}
#[test]
fn touch_pan_that_rests_does_not_fling() {
use crate::types::bus::TouchInput;
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
h.runtime_mut().app_mut().scroller = Some((Rect::new(0.0, 0.0, 400.0, 300.0), 3000.0, crate::ScrollView::default()));
h.runtime_mut().app_mut().request_frame = true;
h.advance(0.017);
let off = |h: &Host<TS, TestApp>| h.runtime().app().scroller.as_ref().unwrap().2.offset;
h.input(win, InputEvent::Touch(TouchInput::Start { id: 1, pos: Point::new(100.0, 250.0) }));
h.advance(0.008);
let mut y = 250.0;
for _ in 0..10 {
y -= 10.0;
h.input(win, InputEvent::Touch(TouchInput::Move { id: 1, pos: Point::new(100.0, y) }));
h.advance(0.008);
}
for _ in 0..20 {
h.advance(0.016);
}
let held = off(&h);
h.input(win, InputEvent::Touch(TouchInput::End { id: 1, pos: Point::new(100.0, y) }));
for _ in 0..30 {
h.advance(0.016);
}
assert!((off(&h) - held).abs() < 0.5, "rested finger: {held} -> {}", off(&h));
}
#[test]
fn touch_long_press_is_a_context_click() {
use crate::types::bus::TouchInput;
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
h.runtime_mut().app_mut().panel_widgets.push((wid("btn"), Rect::new(10.0, 100.0, 60.0, 24.0), Sense::CLICK));
h.advance(0.017);
h.input(win, InputEvent::Touch(TouchInput::Start { id: 3, pos: Point::new(20.0, 112.0) }));
for _ in 0..40 {
h.advance(0.016);
}
h.input(win, InputEvent::Touch(TouchInput::End { id: 3, pos: Point::new(20.0, 112.0) }));
h.advance(0.016);
h.advance(0.016);
let app = h.runtime().app();
assert!(app.seen_gestures.iter().any(|g| matches!(g, crate::types::gesture::Gesture::LongPress { .. })), "{:?}", app.seen_gestures);
assert!(!app.seen_clicks.iter().any(|(id, _)| *id == wid("btn")), "a long-press never activates the widget");
assert_eq!(app.seen_context.first().copied(), Some((20.0, 112.0)));
}
#[test]
fn touch_drag_on_a_drag_widget_drags_instead_of_scrolling() {
use crate::types::bus::TouchInput;
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
h.runtime_mut().app_mut().scroller = Some((Rect::new(0.0, 0.0, 400.0, 300.0), 3000.0, crate::ScrollView::default()));
h.runtime_mut().app_mut().panel_widgets.push((wid("slider"), Rect::new(10.0, 100.0, 300.0, 40.0), Sense::DRAG));
h.runtime_mut().app_mut().request_frame = true;
h.advance(0.017);
let off = |h: &Host<TS, TestApp>| h.runtime().app().scroller.as_ref().unwrap().2.offset;
h.input(win, InputEvent::Touch(TouchInput::Start { id: 1, pos: Point::new(50.0, 120.0) }));
h.advance(0.016);
for i in 1..=10 {
h.input(win, InputEvent::Touch(TouchInput::Move { id: 1, pos: Point::new(50.0 + i as f64 * 10.0, 120.0 - i as f64 * 3.0) }));
h.advance(0.016);
}
let captured = h.snapshot().windows[0].input.captured;
h.input(win, InputEvent::Touch(TouchInput::End { id: 1, pos: Point::new(150.0, 90.0) }));
h.advance(0.016);
assert!(captured, "the drag widget captured the finger");
assert!(off(&h).abs() < 0.5, "nothing scrolled: {}", off(&h));
}
#[test]
fn touch_drag_over_a_text_field_scrolls() {
use crate::types::bus::TouchInput;
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
h.runtime_mut().app_mut().scroller = Some((Rect::new(0.0, 0.0, 400.0, 300.0), 3000.0, crate::ScrollView::default()));
h.runtime_mut().app_mut().field = Some(Field { id: wid("field"), rect: Rect::new(10.0, 200.0, 300.0, 40.0), initial: "some longer text".to_string(), initialized: false });
h.runtime_mut().app_mut().request_frame = true;
h.advance(0.017);
let off = |h: &Host<TS, TestApp>| h.runtime().app().scroller.as_ref().unwrap().2.offset;
h.input(win, InputEvent::Touch(TouchInput::Start { id: 1, pos: Point::new(50.0, 220.0) }));
h.advance(0.016);
let mut y = 220.0;
for _ in 0..10 {
y -= 10.0;
h.input(win, InputEvent::Touch(TouchInput::Move { id: 1, pos: Point::new(52.0, y) }));
h.advance(0.016);
}
let moved = off(&h);
h.input(win, InputEvent::Touch(TouchInput::End { id: 1, pos: Point::new(52.0, y) }));
h.advance(0.016);
assert!(moved > 50.0, "the page scrolled under the finger: {moved}");
assert!(!h.snapshot().windows[0].input.captured, "no text drag holds the pointer");
}
#[test]
fn insets_and_pointer_kind_reach_hooks_and_media() {
use crate::types::bus::{TouchInput, WindowInput};
use crate::types::window::Insets;
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
h.runtime_mut().app_mut().request_frame = true;
h.input(win, InputEvent::Window(WindowInput::Insets { safe: Insets::new(47.0, 0.0, 34.0, 0.0), keyboard: 291.0 }));
h.advance(0.017);
h.advance(0.017);
let seen = h.runtime().app().seen_insets;
assert_eq!(seen.map(|s| (s.0, s.1)), Some((Insets::new(47.0, 0.0, 34.0, 0.0), 291.0)));
let snap_safe = h.snapshot().windows[0].geometry.safe_area;
assert_eq!(snap_safe.top, 47.0);
h.input(win, InputEvent::Touch(TouchInput::Start { id: 1, pos: Point::new(300.0, 300.0) }));
h.advance(0.017);
h.input(win, InputEvent::Touch(TouchInput::End { id: 1, pos: Point::new(300.0, 300.0) }));
h.advance(0.017);
h.advance(0.017);
assert_eq!(h.runtime().app().seen_insets.map(|s| s.2), Some(true), "touch = coarse");
mov(&mut h, win, 10.0, 10.0);
h.advance(0.017);
h.advance(0.017);
assert_eq!(h.runtime().app().seen_insets.map(|s| s.2), Some(false), "mouse = fine");
}
#[test]
fn floating_controls_are_a_top_safe_area_inset() {
use crate::types::command::ChromeModel;
use crate::types::controls::{FloatingControls, WindowControlsStyle};
use crate::types::window::Insets;
let (mut h, handle) = host();
let fc = FloatingControls::new(WindowControlsStyle::default());
let band = fc.reserved_top();
h.runtime_mut().app_mut().chrome = ChromeModel { floating: Some(fc), ..Default::default() };
let win = open_with_panel(&mut h, &handle);
h.runtime_mut().app_mut().request_frame = true;
h.advance(0.017);
h.advance(0.017);
let seen = h.runtime().app().seen_insets;
if crate::types::controls::HOST_HAS_WINDOW_CONTROLS {
assert!(band > 0.0);
assert_eq!(seen.map(|s| s.0), Some(Insets::new(band, 0.0, 0.0, 0.0)));
assert_eq!(uzor::ui::media::current().safe.top, band);
h.input(win, InputEvent::Window(crate::types::bus::WindowInput::Insets { safe: Insets::new(47.0, 0.0, 34.0, 0.0), keyboard: 0.0 }));
h.advance(0.017);
h.advance(0.017);
assert_eq!(h.runtime().app().seen_insets.map(|s| s.0), Some(Insets::new(47.0, 0.0, 34.0, 0.0)));
assert_eq!(uzor::ui::media::current().safe.top, 47.0);
assert_eq!(uzor::ui::media::current().safe.bottom, 34.0);
} else {
assert_eq!(band, 0.0);
assert_eq!(seen.map(|s| s.0.top), Some(0.0));
}
}
#[cfg(feature = "inspector")]
#[test]
fn f12_toggles_the_inspector_and_is_not_reported() {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
key(&mut h, win, KeyCode::F12, ModifierKeys::default(), None);
h.advance(0.017);
mov(&mut h, win, 40.0, 40.0);
h.advance(0.017);
key(&mut h, win, KeyCode::F12, ModifierKeys { shift: true, ..ModifierKeys::default() }, None);
h.advance(0.017);
assert!(!h.runtime().app().intents.iter().any(|i| matches!(
i,
crate::types::intent::Intent::Unhandled(crate::types::intent::UnhandledInput::Key { key, .. }) if key.code == KeyCode::F12
)));
}
#[test]
fn keys_scroll_the_hovered_container() {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
h.runtime_mut().app_mut().scroller = Some((Rect::new(0.0, 0.0, 400.0, 300.0), 3000.0, crate::ScrollView::default()));
h.runtime_mut().app_mut().request_frame = true;
h.advance(0.017);
mov(&mut h, win, 100.0, 100.0);
let off = |h: &Host<TS, TestApp>| h.runtime().app().scroller.as_ref().unwrap().2.offset;
let settle = |h: &mut Host<TS, TestApp>| (0..60).for_each(|_| { h.advance(0.017); });
key(&mut h, win, KeyCode::PageDown, ModifierKeys::default(), None);
settle(&mut h);
assert!((off(&h) - 262.5).abs() < 1.0, "PageDown: {}", off(&h));
key(&mut h, win, KeyCode::End, ModifierKeys::default(), None);
settle(&mut h);
assert!((off(&h) - 2700.0).abs() < 1.0, "End: {}", off(&h));
key(&mut h, win, KeyCode::ArrowUp, ModifierKeys::default(), None);
settle(&mut h);
assert!((off(&h) - 2660.0).abs() < 1.0, "ArrowUp: {}", off(&h));
key(&mut h, win, KeyCode::Home, ModifierKeys::default(), None);
settle(&mut h);
assert!(off(&h).abs() < 1.0, "Home: {}", off(&h));
}
#[test]
fn platform_paste_without_a_field_reaches_the_app() {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
h.input(win, InputEvent::Paste("clip text".into()));
h.advance(0.017);
let got: Vec<_> = h
.runtime_mut()
.app_mut()
.intents
.iter()
.filter_map(|i| match i {
Intent::Unhandled(crate::types::intent::UnhandledInput::Paste { win: w, text }) if *w == win => Some(text.clone()),
_ => None,
})
.collect();
assert_eq!(got, vec!["clip text".to_string()]);
}
#[test]
fn intent_invalidate_paints_in_the_same_tick() {
let (mut h, handle) = Host::new(
TestApp::default(),
RuntimeConfig { tick: uzor::render::TickRate::Dirty, ..RuntimeConfig::default() },
);
let win = open_with_panel(&mut h, &handle);
for _ in 0..10 {
h.advance(0.017);
}
assert!(h.advance(1.0).frames.is_empty(), "idle before the key");
h.runtime_mut().app_mut().answer = Some(AppCommand::Cadence(crate::CadenceCmd::Invalidate {
win,
region: None,
bits: uzor::render::InvalidateBits::ALL,
}));
h.input(
win,
InputEvent::Key(KeyInput {
code: KeyCode::F7,
text: None,
state: crate::types::bus::KeyState::Down,
mods: ModifierKeys::default(),
}),
);
let out = h.advance(0.5);
assert!(out.frames.iter().any(|f| f.window == win), "no frame after the intent's invalidate");
}
fn capture_host() -> (Host<TS, TestApp>, WindowId) {
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
let app = h.runtime_mut().app_mut();
app.scroller = Some((Rect::new(0.0, 0.0, 400.0, 500.0), 3000.0, crate::ScrollView::default()));
app.top_widgets.push((wid("chart"), Rect::new(0.0, 200.0, 400.0, 300.0), Sense::CLICK.with_touch().with_gesture()));
app.top_widgets.push((wid("zoom"), Rect::new(340.0, 210.0, 50.0, 30.0), Sense::CLICK));
app.request_frame = true;
h.advance(0.017);
(h, win)
}
fn off(h: &Host<TS, TestApp>) -> f64 {
h.runtime().app().scroller.as_ref().unwrap().2.offset
}
fn touch(h: &mut Host<TS, TestApp>, win: WindowId, t: crate::types::bus::TouchInput) {
h.input(win, InputEvent::Touch(t));
h.advance(0.017);
}
fn captured(h: &Host<TS, TestApp>) -> Vec<crate::types::gesture::Gesture> {
h.runtime().app().seen_captured.iter().filter(|(w, _)| *w == wid("chart")).map(|(_, g)| *g).collect()
}
#[test]
fn touch_capture_one_finger_pan_is_the_widgets_not_a_scroll() {
use crate::types::bus::TouchInput as T;
use crate::types::gesture::Gesture as G;
let (mut h, win) = capture_host();
touch(&mut h, win, T::Start { id: 1, pos: Point::new(100.0, 400.0) });
let mut y = 400.0;
for _ in 0..12 {
y -= 15.0;
touch(&mut h, win, T::Move { id: 1, pos: Point::new(100.0, y) });
}
touch(&mut h, win, T::End { id: 1, pos: Point::new(100.0, y) });
for _ in 0..20 {
h.advance(0.016);
}
assert_eq!(off(&h), 0.0, "a captured pan never scrolls or flings");
let g = captured(&h);
assert!(g.iter().any(|e| matches!(e, G::PanStart { .. })), "{g:?}");
assert!(g.iter().filter(|e| matches!(e, G::Pan { .. })).count() >= 10);
assert!(g.iter().any(|e| matches!(e, G::PanEnd { .. })));
let app = h.runtime().app();
assert!(!app.seen_gestures.iter().any(|e| matches!(e, G::Pan { .. } | G::PanStart { .. })), "not in gestures(): {:?}", app.seen_gestures);
assert!(!app.seen_clicks.iter().any(|(id, _)| *id == wid("chart")), "a pan never clicks");
touch(&mut h, win, T::Start { id: 2, pos: Point::new(100.0, 190.0) });
let mut y = 190.0;
for _ in 0..10 {
y -= 10.0;
touch(&mut h, win, T::Move { id: 2, pos: Point::new(100.0, y) });
}
touch(&mut h, win, T::End { id: 2, pos: Point::new(100.0, y) });
assert!(off(&h) > 50.0, "outside the capture a pan scrolls: {}", off(&h));
}
#[test]
fn touch_capture_two_fingers_pinch_without_wheel() {
use crate::types::bus::TouchInput as T;
use crate::types::gesture::Gesture as G;
let (mut h, win) = capture_host();
touch(&mut h, win, T::Start { id: 1, pos: Point::new(150.0, 350.0) });
touch(&mut h, win, T::Start { id: 2, pos: Point::new(250.0, 350.0) });
for i in 1..=8 {
let d = i as f64 * 6.0;
touch(&mut h, win, T::Move { id: 1, pos: Point::new(150.0 - d, 350.0 - d) });
touch(&mut h, win, T::Move { id: 2, pos: Point::new(250.0 + d, 350.0 - d) });
}
touch(&mut h, win, T::End { id: 2, pos: Point::new(298.0, 302.0) });
touch(&mut h, win, T::End { id: 1, pos: Point::new(102.0, 302.0) });
h.advance(0.016);
assert_eq!(off(&h), 0.0, "no wheel from two captured fingers");
let g = captured(&h);
let last_scale = g.iter().rev().find_map(|e| match e {
G::Pinch { scale, .. } => Some(*scale),
_ => None,
});
assert!(last_scale.is_some_and(|s| s > 1.9), "{g:?}");
let pan_y: f64 = g.iter().filter_map(|e| match e {
G::PinchPan { delta, .. } => Some(delta.1),
_ => None,
}).sum();
assert!((pan_y + 48.0).abs() < 0.5, "the midpoint moved up 48 px: {pan_y}");
assert!(g.iter().any(|e| matches!(e, G::PinchEnd { .. })));
assert!(!h.runtime().app().seen_clicks.iter().any(|(id, _)| *id == wid("chart")));
touch(&mut h, win, T::Start { id: 3, pos: Point::new(100.0, 150.0) });
touch(&mut h, win, T::Start { id: 4, pos: Point::new(200.0, 150.0) });
for i in 1..=6 {
let y = 150.0 - i as f64 * 15.0;
touch(&mut h, win, T::Move { id: 3, pos: Point::new(100.0, y) });
touch(&mut h, win, T::Move { id: 4, pos: Point::new(200.0, y) });
}
assert!(off(&h) > 40.0, "two fingers elsewhere scroll: {}", off(&h));
}
#[test]
fn touch_capture_taps_click_and_double_tap() {
use crate::types::bus::TouchInput as T;
use crate::types::gesture::Gesture as G;
let (mut h, win) = capture_host();
touch(&mut h, win, T::Start { id: 1, pos: Point::new(100.0, 300.0) });
touch(&mut h, win, T::End { id: 1, pos: Point::new(100.0, 300.0) });
touch(&mut h, win, T::Start { id: 2, pos: Point::new(102.0, 301.0) });
touch(&mut h, win, T::End { id: 2, pos: Point::new(102.0, 301.0) });
h.advance(0.017);
assert!(h.runtime().app().seen_clicks.iter().any(|(id, _)| *id == wid("chart")), "{:?}", h.runtime().app().seen_clicks);
let g = captured(&h);
assert_eq!(g.iter().filter(|e| matches!(e, G::Tap { .. })).count(), 2, "{g:?}");
assert!(g.iter().any(|e| matches!(e, G::DoubleTap { .. })), "{g:?}");
let before = captured(&h).len();
h.advance(1.0);
touch(&mut h, win, T::Start { id: 3, pos: Point::new(360.0, 220.0) });
touch(&mut h, win, T::End { id: 3, pos: Point::new(360.0, 220.0) });
h.advance(0.017);
assert!(h.runtime().app().seen_clicks.iter().any(|(id, _)| *id == wid("zoom")), "{:?}", h.runtime().app().seen_clicks);
assert_eq!(captured(&h).len(), before, "the button's tap is not the chart's");
}
#[test]
fn touch_capture_long_press_drags_instead_of_context() {
use crate::types::bus::TouchInput as T;
use crate::types::gesture::Gesture as G;
let (mut h, win) = capture_host();
touch(&mut h, win, T::Start { id: 1, pos: Point::new(100.0, 300.0) });
for _ in 0..40 {
h.advance(0.016);
}
for i in 1..=5 {
touch(&mut h, win, T::Move { id: 1, pos: Point::new(100.0 + i as f64 * 10.0, 300.0) });
}
touch(&mut h, win, T::End { id: 1, pos: Point::new(150.0, 300.0) });
h.advance(0.016);
let g = captured(&h);
assert!(g.iter().any(|e| matches!(e, G::LongPress { .. })), "{g:?}");
let dx: f64 = g.iter().filter_map(|e| match e {
G::LongPressDrag { delta, .. } => Some(delta.0),
_ => None,
}).sum();
assert_eq!(dx, 50.0);
assert!(g.iter().any(|e| matches!(e, G::LongPressEnd { .. })));
let app = h.runtime().app();
assert!(app.seen_context.is_empty(), "no context click: {:?}", app.seen_context);
assert!(!app.seen_clicks.iter().any(|(id, _)| *id == wid("chart")));
assert_eq!(off(&h), 0.0);
}
#[test]
fn paint_slot_gets_the_pinch_and_the_scroller_stays() {
use crate::types::bus::TouchInput as T;
use crate::types::gesture::Gesture as G;
let (mut h, handle) = host();
let win = open_with_panel(&mut h, &handle);
let app = h.runtime_mut().app_mut();
app.scroller = Some((Rect::new(0.0, 0.0, 390.0, 600.0), 3000.0, crate::ScrollView::default()));
app.paint_slot = Some(Rect::new(0.0, 100.0, 390.0, 400.0));
app.request_frame = true;
h.advance(0.017);
touch(&mut h, win, T::Start { id: 1, pos: Point::new(150.0, 300.0) });
touch(&mut h, win, T::Start { id: 2, pos: Point::new(240.0, 300.0) });
for i in 1..=6 {
let d = i as f64 * 5.0;
touch(&mut h, win, T::Move { id: 1, pos: Point::new(150.0 - d, 300.0 + d) });
touch(&mut h, win, T::Move { id: 2, pos: Point::new(240.0 + d, 300.0 + d) });
}
touch(&mut h, win, T::End { id: 1, pos: Point::new(120.0, 330.0) });
touch(&mut h, win, T::End { id: 2, pos: Point::new(270.0, 330.0) });
h.advance(0.017);
let app = h.runtime().app();
assert_eq!(app.scroller.as_ref().unwrap().2.offset, 0.0);
assert!(app.seen_slot.iter().any(|g| matches!(g, G::Pinch { scale, .. } if *scale > 1.5)), "{:?}", app.seen_slot);
assert!(app.seen_slot.iter().any(|g| matches!(g, G::PinchPan { .. })));
assert!(app.seen_slot.iter().any(|g| matches!(g, G::PinchEnd { .. })));
}