#![allow(clippy::too_many_arguments, clippy::type_complexity)]
use std::{
cell::Cell,
collections::{HashMap, HashSet, hash_map::DefaultHasher},
hash::{Hash, Hasher},
rc::Rc,
sync::{
Arc, Mutex,
atomic::{AtomicU64, Ordering},
},
};
use crate::{
Command, CommandDelivery, CommandKey, CommandSender, CommandTarget,
command::{QueuedCommand, queued_command},
diagnostics::{WidgetTimingPhase, record_widget_timing, start_widget_timing},
motion::{FrameClock, Motion},
overlay::OverlayOptions,
reactive::{ObservationPhase, ObservationScope},
};
use sui_animation::{AnimationSpec, Interpolate};
use sui_core::{
AsyncWakeToken, Clipboard, Color, CursorGrabMode, DpiInfo, DragPayload, DragScopeId,
DragSessionId, DropEffect, DropEffects, Event, ImageHandle, InvalidationKind,
InvalidationRequest, InvalidationTarget, MotionPolicy, Path, Point, Rect, SemanticsNode, Size,
TimerToken, Transform, UrlOpener, Vector, WakeEvent, WidgetId, WindowId,
};
use sui_layout::{Axis, Constraints, IntrinsicSize, LayoutContext};
use sui_reactive::{Observable, Signal};
use sui_scene::{
Border, Brush, ImageRegistry, ImageSource, LayerCompositionMode, LayerProperties,
RegisteredExternalImage, RegisteredImage, Scene, SceneCommand, SceneLayer,
SceneLayerDescriptor, SceneLayerId, ShadowParams, StrokeStyle, TextRenderPolicy, WidgetShader,
};
use sui_text::{
FontRegistry, PersistentTextLayout, ShapedText, ShapedTextWindow, TextLayout, TextLayoutHandle,
TextLayoutRequest, TextMeasurement, TextRun, TextStyle, TextSystem,
};
static NEXT_WIDGET_ID: AtomicU64 = AtomicU64::new(1);
static NEXT_TIMER_TOKEN: AtomicU64 = AtomicU64::new(1);
static NEXT_ASYNC_WAKE_TOKEN: AtomicU64 = AtomicU64::new(1);
static NEXT_DRAG_SESSION_ID: AtomicU64 = AtomicU64::new(1);
const WIDGET_IMAGE_HANDLE_NAMESPACE: u64 = 1 << 63;
const TRANSFORM_EQ_ULPS: f32 = 16.0;
fn relative_transform(child: Transform, parent: Transform) -> Transform {
if transforms_nearly_equal(child, parent) {
return Transform::IDENTITY;
}
parent
.inverse()
.map(|inverse| child.then(inverse))
.unwrap_or(child)
}
fn transforms_nearly_equal(left: Transform, right: Transform) -> bool {
let nearly_equal = |left: f32, right: f32| {
let scale = left.abs().max(right.abs()).max(1.0);
(left - right).abs() <= f32::EPSILON * TRANSFORM_EQ_ULPS * scale
};
nearly_equal(left.xx, right.xx)
&& nearly_equal(left.yx, right.yx)
&& nearly_equal(left.xy, right.xy)
&& nearly_equal(left.yy, right.yy)
&& nearly_equal(left.dx, right.dx)
&& nearly_equal(left.dy, right.dy)
}
fn event_for_transform(event: &Event, inverse: Transform) -> Event {
if inverse.is_identity() {
return event.clone();
}
match event {
Event::Pointer(pointer) => {
let mut pointer = pointer.clone();
pointer.position = inverse.transform_point(pointer.position);
pointer.delta = inverse.transform_vector(pointer.delta);
pointer.scroll_delta = pointer.scroll_delta.map(|delta| match delta {
sui_core::ScrollDelta::Pixels(delta) => {
sui_core::ScrollDelta::Pixels(inverse.transform_vector(delta))
}
sui_core::ScrollDelta::Lines(delta) => sui_core::ScrollDelta::Lines(delta),
});
Event::Pointer(pointer)
}
Event::Drag(drag) => {
let mut drag = drag.clone();
drag.position = inverse.transform_point(drag.position);
drag.start_position = inverse.transform_point(drag.start_position);
Event::Drag(drag)
}
_ => event.clone(),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventPhase {
Capture,
Target,
Bubble,
}
pub trait WidgetPodVisitor {
fn visit(&mut self, child: &WidgetPod);
}
pub trait WidgetPodMutVisitor {
fn visit(&mut self, child: &mut WidgetPod);
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WidgetDiagnostic {
pub name: String,
pub value: String,
}
#[derive(Debug, Default)]
pub struct WidgetDiagnosticsCtx {
entries: Vec<WidgetDiagnostic>,
}
impl WidgetDiagnosticsCtx {
pub fn record(&mut self, name: impl Into<String>, value: impl Into<String>) {
self.entries.push(WidgetDiagnostic {
name: name.into(),
value: value.into(),
});
}
fn into_entries(self) -> Vec<WidgetDiagnostic> {
self.entries
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WidgetDiagnosticsSnapshot {
pub widget_id: WidgetId,
pub widget_name: &'static str,
pub entries: Vec<WidgetDiagnostic>,
}
pub trait Widget {
fn event(&mut self, _ctx: &mut EventCtx, _event: &Event) {}
fn command(&mut self, _ctx: &mut EventCtx, _command: &Command<'_>) {}
fn debug_name(&self) -> &'static str {
std::any::type_name::<Self>()
}
fn diagnostics(&self, _ctx: &mut WidgetDiagnosticsCtx) {}
fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
constraints.max
}
fn measure_size(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
self.measure(ctx, constraints)
}
fn measure_axis(&mut self, ctx: &mut MeasureCtx, constraints: Constraints, axis: Axis) -> f32 {
let size = self.measure_size(ctx, constraints);
match axis {
Axis::Horizontal => size.width,
Axis::Vertical => size.height,
}
}
fn intrinsic_size(
&mut self,
ctx: &mut MeasureCtx,
axis: Axis,
available_cross: f32,
) -> IntrinsicSize {
let cross = if available_cross.is_finite() {
available_cross.max(0.0)
} else {
f32::INFINITY
};
let constraints = match axis {
Axis::Horizontal => Constraints::new(Size::ZERO, Size::new(f32::INFINITY, cross)),
Axis::Vertical => Constraints::new(Size::ZERO, Size::new(cross, f32::INFINITY)),
};
let size = self.measure_size(ctx, constraints);
IntrinsicSize::fixed(match axis {
Axis::Horizontal => size.width,
Axis::Vertical => size.height,
})
}
fn arrange(&mut self, _ctx: &mut ArrangeCtx, _bounds: Rect) {}
fn paint(&self, _ctx: &mut PaintCtx) {}
fn supports_output_reuse(&self) -> bool {
false
}
fn layer_options(&self) -> LayerOptions {
LayerOptions::default()
}
fn layer_properties(&self) -> LayerProperties {
LayerProperties::default()
}
fn layer_properties_at(&self, frame_time: f64) -> LayerProperties {
let _ = frame_time;
self.layer_properties()
}
fn stack_host_options(&self) -> Option<StackHostOptions> {
None
}
fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
None
}
fn overlay_options(&self) -> Option<OverlayOptions> {
None
}
fn semantics(&self, _ctx: &mut SemanticsCtx) {}
fn accepts_focus(&self) -> bool {
false
}
fn hit_test_self(&self) -> bool {
true
}
fn focus_changed(&mut self, _ctx: &mut EventCtx, _focused: bool) {}
fn visit_children(&self, _visitor: &mut dyn WidgetPodVisitor) {}
fn visit_children_mut(&mut self, _visitor: &mut dyn WidgetPodMutVisitor) {}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PaintBoundaryMode {
Flat,
Explicit,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LayerOptions {
pub paint_boundary: PaintBoundaryMode,
pub composition_mode: LayerCompositionMode,
}
impl LayerOptions {
pub const fn emits_layer(self) -> bool {
matches!(self.paint_boundary, PaintBoundaryMode::Explicit)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StackOrderPolicy {
Stable,
FocusFronted,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StackHostOptions {
pub order_policy: StackOrderPolicy,
}
impl Default for StackHostOptions {
fn default() -> Self {
Self {
order_policy: StackOrderPolicy::Stable,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StackSurfaceOptions {
pub dynamic_ordering: bool,
pub transient: bool,
pub hit_test: bool,
}
impl Default for StackSurfaceOptions {
fn default() -> Self {
Self {
dynamic_ordering: true,
transient: false,
hit_test: true,
}
}
}
impl Default for LayerOptions {
fn default() -> Self {
Self {
paint_boundary: PaintBoundaryMode::Flat,
composition_mode: LayerCompositionMode::Normal,
}
}
}
pub struct SingleChild {
child: WidgetPod,
}
impl SingleChild {
pub fn new<W>(child: W) -> Self
where
W: Widget + 'static,
{
Self::from_pod(WidgetPod::new(child))
}
pub fn new_with_paint_boundary<W>(child: W) -> Self
where
W: Widget + 'static,
{
let mut child = WidgetPod::new(child);
child.force_paint_boundary = true;
Self::from_pod(child)
}
pub fn with_paint_boundary(mut self) -> Self {
self.child.force_paint_boundary = true;
self
}
pub fn from_pod(child: WidgetPod) -> Self {
Self { child }
}
pub fn child(&self) -> &WidgetPod {
&self.child
}
pub fn child_mut(&mut self) -> &mut WidgetPod {
&mut self.child
}
pub fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
self.child.measure(ctx, constraints)
}
pub fn measure_size(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
self.child.probe_measure(ctx, constraints)
}
pub fn measure_axis(
&mut self,
ctx: &mut MeasureCtx,
constraints: Constraints,
axis: Axis,
) -> f32 {
self.child.probe_measure_axis(ctx, constraints, axis)
}
pub fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
self.child.arrange(ctx, bounds);
}
pub fn arrange_transformed(
&mut self,
ctx: &mut ArrangeCtx,
bounds: Rect,
transform: Transform,
) {
self.child.arrange_transformed(ctx, bounds, transform);
}
pub fn set_bounds(&mut self, bounds: Rect) {
self.child.set_bounds(bounds);
}
pub fn paint(&self, ctx: &mut PaintCtx) {
self.child.paint(ctx);
}
pub fn semantics(&self, ctx: &mut SemanticsCtx) {
self.child.semantics(ctx);
}
pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
visitor.visit(&self.child);
}
pub fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
visitor.visit(&mut self.child);
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum FocusRestorePolicy {
LastFocused,
FirstFocusable,
#[default]
LastFocusedOrFirstFocusable,
}
#[derive(Debug, Default)]
struct FocusScopeStateInner {
last_focused: Option<WidgetId>,
restore_requested: bool,
restore_forced: bool,
}
#[derive(Clone, Debug)]
pub struct FocusScopeState {
inner: Arc<Mutex<FocusScopeStateInner>>,
restore_revision: Signal<u64>,
last_focused_signal: Signal<Option<WidgetId>>,
}
impl FocusScopeState {
pub fn new() -> Self {
Self {
inner: Arc::new(Mutex::new(FocusScopeStateInner::default())),
restore_revision: Signal::named("FocusScopeState::restore", 0),
last_focused_signal: Signal::named("FocusScopeState::last_focused", None),
}
}
pub fn last_focused(&self) -> Option<WidgetId> {
self.lock_inner().last_focused
}
pub fn last_focused_observable(
&self,
) -> impl Observable<Option<WidgetId>> + Clone + Send + Sync + 'static {
self.last_focused_signal
.select_named("FocusScopeState::last_focused", |widget| *widget)
}
pub fn request_restore(&self) -> bool {
let changed = {
let mut inner = self.lock_inner();
if inner.restore_requested {
false
} else {
inner.restore_requested = true;
true
}
};
if changed {
self.restore_revision
.update(|revision| *revision = revision.wrapping_add(1));
}
changed
}
pub fn request_focus(&self) -> bool {
self.lock_inner().restore_forced = true;
self.request_restore()
}
pub fn clear(&self) {
let restore_was_requested = {
let mut inner = self.lock_inner();
let restore_was_requested = inner.restore_requested;
inner.last_focused = None;
inner.restore_requested = false;
inner.restore_forced = false;
restore_was_requested
};
self.last_focused_signal.set(None);
if restore_was_requested {
self.restore_revision
.update(|revision| *revision = revision.wrapping_add(1));
}
}
fn remember(&self, widget_id: WidgetId) {
let changed = {
let mut inner = self.lock_inner();
let changed = inner.last_focused != Some(widget_id);
inner.last_focused = Some(widget_id);
changed
};
if changed {
self.last_focused_signal.set(Some(widget_id));
}
}
fn restore_requested(&self) -> bool {
self.lock_inner().restore_requested
}
fn complete_restore(&self) -> bool {
let mut inner = self.lock_inner();
inner.restore_requested = false;
std::mem::take(&mut inner.restore_forced)
}
fn lock_inner(&self) -> std::sync::MutexGuard<'_, FocusScopeStateInner> {
self.inner
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
impl Default for FocusScopeState {
fn default() -> Self {
Self::new()
}
}
pub struct FocusScope {
state: FocusScopeState,
restore_policy: FocusRestorePolicy,
child: SingleChild,
}
impl FocusScope {
pub fn new<W>(child: W) -> Self
where
W: Widget + 'static,
{
Self {
state: FocusScopeState::new(),
restore_policy: FocusRestorePolicy::default(),
child: SingleChild::new(child),
}
}
pub fn state(mut self, state: FocusScopeState) -> Self {
self.state = state;
self
}
pub fn restore_policy(mut self, restore_policy: FocusRestorePolicy) -> Self {
self.restore_policy = restore_policy;
self
}
pub fn child(&self) -> &WidgetPod {
self.child.child()
}
pub fn child_mut(&mut self) -> &mut WidgetPod {
self.child.child_mut()
}
fn restore_target(&self) -> Option<WidgetId> {
let last_focused = self
.state
.last_focused()
.filter(|target| pod_contains(self.child.child(), *target));
match self.restore_policy {
FocusRestorePolicy::LastFocused => last_focused,
FocusRestorePolicy::FirstFocusable => first_focusable(self.child.child()),
FocusRestorePolicy::LastFocusedOrFirstFocusable => {
last_focused.or_else(|| first_focusable(self.child.child()))
}
}
}
fn remember_current_focus(&self, focused_widget_id: Option<WidgetId>) {
if let Some(focused) = focused_widget_id
&& pod_contains(self.child.child(), focused)
{
self.state.remember(focused);
}
}
}
impl Widget for FocusScope {
fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
self.remember_current_focus(ctx.focused_widget_id());
if matches!(event, Event::Wake(WakeEvent::AnimationFrame { .. }))
&& self.state.restore_requested()
{
let target = self.restore_target();
let forced = self.state.complete_restore();
let focused_elsewhere = !forced
&& ctx
.focused_widget_id()
.is_some_and(|focused| !pod_contains(self.child.child(), focused));
if !focused_elsewhere && let Some(target) = target {
ctx.request_focus_for(target);
ctx.request_paint();
ctx.request_semantics();
ctx.set_handled();
}
}
}
fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
let _ = ctx.observe(&self.state.restore_revision);
if self.state.restore_requested() {
ctx.request_animation_frame();
}
self.child.measure(ctx, constraints)
}
fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
self.child.arrange(ctx, bounds);
}
fn paint(&self, ctx: &mut PaintCtx) {
self.remember_current_focus(ctx.focused_widget_id());
self.child.paint(ctx);
}
fn semantics(&self, ctx: &mut SemanticsCtx) {
self.remember_current_focus(ctx.focused_widget_id());
self.child.semantics(ctx);
}
fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
self.child.visit_children(visitor);
}
fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
self.child.visit_children_mut(visitor);
}
}
fn pod_contains(root: &WidgetPod, target: WidgetId) -> bool {
if root.id() == target {
return true;
}
struct Finder {
target: WidgetId,
found: bool,
}
impl WidgetPodVisitor for Finder {
fn visit(&mut self, child: &WidgetPod) {
if self.found {
return;
}
if child.id() == self.target {
self.found = true;
} else {
child.visit_children(self);
}
}
}
let mut finder = Finder {
target,
found: false,
};
root.visit_children(&mut finder);
finder.found
}
fn first_focusable(root: &WidgetPod) -> Option<WidgetId> {
if root.accepts_focus() {
return Some(root.id());
}
struct Finder {
target: Option<WidgetId>,
}
impl WidgetPodVisitor for Finder {
fn visit(&mut self, child: &WidgetPod) {
if self.target.is_some() {
return;
}
if child.accepts_focus() {
self.target = Some(child.id());
} else {
child.visit_children(self);
}
}
}
let mut finder = Finder { target: None };
root.visit_children(&mut finder);
finder.target
}
#[derive(Default)]
pub struct WidgetChildren {
children: Vec<WidgetPod>,
}
impl WidgetChildren {
pub fn new() -> Self {
Self::default()
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
children: Vec::with_capacity(capacity),
}
}
pub fn push<W>(&mut self, child: W)
where
W: Widget + 'static,
{
self.push_pod(WidgetPod::new(child));
}
pub fn push_pod(&mut self, child: WidgetPod) {
self.children.push(child);
}
pub fn len(&self) -> usize {
self.children.len()
}
pub fn is_empty(&self) -> bool {
self.children.is_empty()
}
pub fn as_slice(&self) -> &[WidgetPod] {
&self.children
}
pub fn as_mut_slice(&mut self) -> &mut [WidgetPod] {
&mut self.children
}
pub fn measure_child(
&mut self,
index: usize,
ctx: &mut MeasureCtx,
constraints: Constraints,
) -> Size {
self.children[index].measure(ctx, constraints)
}
pub fn intrinsic_size_child(
&mut self,
index: usize,
ctx: &mut MeasureCtx,
axis: Axis,
available_cross: f32,
) -> IntrinsicSize {
self.children[index].intrinsic_size(ctx, axis, available_cross)
}
pub fn arrange_child(&mut self, index: usize, ctx: &mut ArrangeCtx, bounds: Rect) {
self.children[index].arrange(ctx, bounds);
}
pub fn paint(&self, ctx: &mut PaintCtx) {
for child in &self.children {
child.paint(ctx);
}
}
pub fn semantics(&self, ctx: &mut SemanticsCtx) {
for child in &self.children {
child.semantics(ctx);
}
}
pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
for child in &self.children {
visitor.visit(child);
}
}
pub fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
for child in &mut self.children {
visitor.visit(child);
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct KeyedReconcile {
pub inserted: usize,
pub removed: usize,
pub moved: usize,
pub updated: usize,
pub unchanged: usize,
pub duplicate_keys: usize,
}
struct KeyedChild<K, T> {
key: K,
value: Signal<T>,
child: WidgetPod,
}
pub struct KeyedChildren<K, T> {
entries: Vec<KeyedChild<K, T>>,
}
impl<K, T> KeyedChildren<K, T> {
pub const fn new() -> Self {
Self {
entries: Vec::new(),
}
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = (&K, &Signal<T>, &WidgetPod)> {
self.entries
.iter()
.map(|entry| (&entry.key, &entry.value, &entry.child))
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&K, &Signal<T>, &mut WidgetPod)> {
self.entries
.iter_mut()
.map(|entry| (&entry.key, &entry.value, &mut entry.child))
}
pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
for entry in &self.entries {
visitor.visit(&entry.child);
}
}
pub fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
for entry in &mut self.entries {
visitor.visit(&mut entry.child);
}
}
}
impl<K, T> KeyedChildren<K, T>
where
K: Clone + Eq + Hash,
T: Clone + PartialEq + 'static,
{
pub fn reconcile<I, KF, B, W>(
&mut self,
items: I,
mut key_for: KF,
mut build: B,
) -> KeyedReconcile
where
I: IntoIterator<Item = T>,
KF: FnMut(&T) -> K,
B: FnMut(&K, Signal<T>) -> W,
W: Widget + 'static,
{
let previous_len = self.entries.len();
let mut previous = std::mem::take(&mut self.entries)
.into_iter()
.enumerate()
.map(|(index, entry)| (entry.key.clone(), (index, entry)))
.collect::<HashMap<_, _>>();
let mut seen = HashSet::new();
let mut next = Vec::new();
let mut report = KeyedReconcile::default();
for item in items {
let key = key_for(&item);
if !seen.insert(key.clone()) {
report.duplicate_keys += 1;
continue;
}
let next_index = next.len();
if let Some((previous_index, entry)) = previous.remove(&key) {
if previous_index != next_index {
report.moved += 1;
}
if entry.value.set(item) {
report.updated += 1;
} else {
report.unchanged += 1;
}
next.push(entry);
} else {
let value = Signal::named("Keyed item", item);
let child = WidgetPod::new(build(&key, value.clone()));
next.push(KeyedChild { key, value, child });
report.inserted += 1;
}
}
report.removed = previous.len();
debug_assert_eq!(previous_len + report.inserted, next.len() + report.removed);
self.entries = next;
report
}
}
impl<K, T> Default for KeyedChildren<K, T> {
fn default() -> Self {
Self::new()
}
}
pub struct WidgetPod {
id: WidgetId,
layout_state: LayoutState,
probe_cache: Option<Box<ProbeCache>>,
query_context: Option<crate::measure_cache::QueryContext>,
last_probe_invalidation: u64,
force_paint_boundary: bool,
inert: bool,
observed_phases: Cell<u8>,
widget: Box<dyn Widget>,
}
impl Drop for WidgetPod {
fn drop(&mut self) {
crate::layout_work::record(|work| work.dropped += 1);
crate::reactive::clear_widget(self.id);
}
}
#[derive(Default)]
struct ProbeCache {
revision: u64,
promoted: bool,
measurements: [Option<(Constraints, Option<Axis>, Size)>; 4],
intrinsics: [Option<(f32, IntrinsicSize)>; 2],
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct LayoutState {
measured_size: Size,
arranged_bounds: Rect,
relative_presentation_transform: Transform,
presentation_transform: Transform,
last_constraints: Constraints,
measure_valid: bool,
arrange_valid: bool,
}
impl Default for LayoutState {
fn default() -> Self {
Self {
measured_size: Size::ZERO,
arranged_bounds: Rect::ZERO,
relative_presentation_transform: Transform::IDENTITY,
presentation_transform: Transform::IDENTITY,
last_constraints: Constraints::default(),
measure_valid: false,
arrange_valid: false,
}
}
}
impl WidgetPod {
pub fn new<W>(widget: W) -> Self
where
W: Widget + 'static,
{
Self::new_boxed(Box::new(widget))
}
pub fn new_boxed(widget: Box<dyn Widget>) -> Self {
crate::layout_work::record(|work| work.constructed += 1);
Self {
id: WidgetId::new(NEXT_WIDGET_ID.fetch_add(1, Ordering::Relaxed)),
layout_state: LayoutState::default(),
probe_cache: None,
query_context: None,
last_probe_invalidation: 0,
force_paint_boundary: false,
inert: false,
observed_phases: Cell::new(0),
widget,
}
}
pub const fn id(&self) -> WidgetId {
self.id
}
pub const fn is_inert(&self) -> bool {
self.inert
}
pub fn set_inert(&mut self, inert: bool) {
self.inert = inert;
}
pub fn debug_name(&self) -> &'static str {
self.widget.debug_name()
}
pub fn diagnostics_snapshot(&self) -> WidgetDiagnosticsSnapshot {
let mut ctx = WidgetDiagnosticsCtx::default();
self.widget.diagnostics(&mut ctx);
WidgetDiagnosticsSnapshot {
widget_id: self.id,
widget_name: self.widget.debug_name(),
entries: ctx.into_entries(),
}
}
pub fn collect_diagnostics(&self, output: &mut Vec<WidgetDiagnosticsSnapshot>) {
let snapshot = self.diagnostics_snapshot();
if !snapshot.entries.is_empty() {
output.push(snapshot);
}
let mut visitor = CollectDiagnosticsVisitor { output };
self.visit_children(&mut visitor);
}
pub const fn bounds(&self) -> Rect {
self.layout_state.arranged_bounds
}
pub const fn measured_size(&self) -> Size {
self.layout_state.measured_size
}
pub const fn presentation_transform(&self) -> Transform {
self.layout_state.presentation_transform
}
pub fn set_bounds(&mut self, bounds: Rect) {
let delta = bounds.origin - self.layout_state.arranged_bounds.origin;
crate::layout_work::record(|work| work.translations += u64::from(delta != Vector::ZERO));
self.layout_state.arranged_bounds = bounds;
self.layout_state.measured_size = bounds.size;
self.layout_state.arrange_valid = true;
self.translate_descendants(delta);
}
pub fn probe_measure(&mut self, parent_ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
self.probe_measure_query(parent_ctx, constraints, None)
}
pub fn probe_measure_axis(
&mut self,
parent_ctx: &mut MeasureCtx,
constraints: Constraints,
axis: Axis,
) -> f32 {
let size = self.probe_measure_query(parent_ctx, constraints, Some(axis));
match axis {
Axis::Horizontal => size.width,
Axis::Vertical => size.height,
}
}
fn probe_measure_query(
&mut self,
parent_ctx: &mut MeasureCtx,
constraints: Constraints,
axis: Option<Axis>,
) -> Size {
crate::layout_work::record(|work| work.probe_requests += 1);
self.invalidate_probes(parent_ctx);
if let Some(size) = self.probe_cache.as_ref().and_then(|cache| {
cache
.measurements
.iter()
.flatten()
.find(|(key, kind, _)| *key == constraints && *kind == axis)
.map(|(_, _, size)| *size)
}) {
crate::layout_work::record(|work| work.probe_cache_hits += 1);
return size;
}
let cache = self.probe_cache.get_or_insert_with(Default::default);
let revision = cache.revision;
let shared = parent_ctx
.query_cache
.as_ref()
.filter(|_| parent_ctx.scope.reusable_queries && cache.measurements[3].is_some());
let key = shared
.and_then(|_| crate::measure_cache::QueryKey::new(self.id, revision, constraints))
.map(|key| key.with_axis(axis));
let cached = shared
.zip(parent_ctx.query_context)
.zip(key.as_ref())
.and_then(|((shared, context), key)| {
let mut window = shared.borrow_mut();
if !cache.promoted {
for (constraints, axis, size) in cache.measurements.iter().flatten() {
if let Some(key) =
crate::measure_cache::QueryKey::new(self.id, revision, *constraints)
{
window.put(context, key.with_axis(*axis), *size);
}
}
cache.promoted = true;
}
window.get(context, key)
});
let size = if let Some(size) = cached {
crate::layout_work::record(|work| {
work.probe_cache_hits += 1;
work.shared_probe_cache_hits += 1;
});
size
} else {
let size = self.measure_impl(parent_ctx, constraints, true, axis);
if let Some(cache) = parent_ctx
.query_cache
.as_ref()
.filter(|_| parent_ctx.scope.reusable_queries)
&& let Some(context) = parent_ctx.query_context
&& let Some(key) = key
{
cache.borrow_mut().put(context, key, size);
}
size
};
let cache = self.probe_cache.get_or_insert_with(Default::default);
if cache.measurements[0].is_none_or(|(key, kind, _)| key != constraints || kind != axis) {
cache.measurements.rotate_right(1);
}
cache.measurements[0] = Some((constraints, axis, size));
size
}
fn invalidate_probes(&mut self, ctx: &MeasureCtx) -> bool {
let context = ctx.query_context;
let context_changed = self.query_context != context;
self.query_context = context;
let dirty = context_changed || ctx.child_force() || ctx.scope().must_remeasure(self.id);
if context_changed {
self.layout_state.measure_valid = false;
self.layout_state.arrange_valid = false;
}
if dirty
&& (context_changed
|| !ctx.scope().reusable_queries
|| self.last_probe_invalidation != ctx.scope().generation)
{
if let Some(cache) = &mut self.probe_cache {
let revision = cache.revision.wrapping_add(1);
**cache = ProbeCache {
revision,
..Default::default()
};
}
if context_changed || self.last_probe_invalidation != ctx.scope().generation {
crate::reactive::clear_probe_observations(self.id, &self.observed_phases);
}
self.last_probe_invalidation = ctx.scope().generation;
}
dirty
}
pub fn measure(&mut self, parent_ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
self.measure_impl(parent_ctx, constraints, false, None)
}
fn measure_impl(
&mut self,
parent_ctx: &mut MeasureCtx,
constraints: Constraints,
size_only: bool,
axis: Option<Axis>,
) -> Size {
let probing = size_only || parent_ctx.probing;
crate::layout_work::record(|work| work.measure_requests += 1);
let force = parent_ctx.child_force();
let must_remeasure = self.invalidate_probes(parent_ctx);
if !probing
&& !must_remeasure
&& self.layout_state.measure_valid
&& self.layout_state.last_constraints == constraints
{
crate::layout_work::record(|work| work.measure_cache_hits += 1);
return self.layout_state.measured_size;
}
crate::layout_work::record(|work| {
work.measure_executions += 1;
work.size_measure_executions += u64::from(size_only);
work.forced_measures += u64::from(must_remeasure);
work.constraint_changes += u64::from(
self.layout_state.measure_valid
&& self.layout_state.last_constraints != constraints,
);
work.first_measures += u64::from(!self.layout_state.measure_valid);
});
let mut child_ctx = parent_ctx.child(self.id, self.layout_state.arranged_bounds, force);
child_ctx.probing = probing;
let started = start_widget_timing();
let observations = ObservationScope::new(
parent_ctx.window_id(),
self.id,
if probing {
ObservationPhase::MeasureProbe
} else {
ObservationPhase::Measure
},
&self.observed_phases,
);
let size = if let Some(axis) = axis {
let extent = self.widget.measure_axis(&mut child_ctx, constraints, axis);
match axis {
Axis::Horizontal => Size::new(extent, 0.0),
Axis::Vertical => Size::new(0.0, extent),
}
} else if size_only {
self.widget.measure_size(&mut child_ctx, constraints)
} else {
self.widget.measure(&mut child_ctx, constraints)
};
drop(observations);
record_widget_timing(
self.id,
self.widget.debug_name(),
WidgetTimingPhase::Measure,
started,
);
if axis.is_none() {
self.layout_state.measured_size = size;
self.layout_state.last_constraints = constraints;
}
self.layout_state.measure_valid = !size_only;
if must_remeasure {
self.layout_state.arrange_valid = false;
}
parent_ctx.extend_invalidations(child_ctx.take_invalidations());
parent_ctx.extend_wake_requests(child_ctx.take_wake_requests());
size
}
pub fn intrinsic_size(
&mut self,
parent_ctx: &mut MeasureCtx,
axis: Axis,
available_cross: f32,
) -> IntrinsicSize {
crate::layout_work::record(|work| match axis {
Axis::Horizontal => work.intrinsic_horizontal += 1,
Axis::Vertical => work.intrinsic_vertical += 1,
});
self.invalidate_probes(parent_ctx);
let axis_index = match axis {
Axis::Horizontal => 0,
Axis::Vertical => 1,
};
let cross = available_cross;
if let Some((key, size)) = self
.probe_cache
.as_ref()
.and_then(|cache| cache.intrinsics[axis_index])
&& key == cross
{
crate::layout_work::record(|work| work.intrinsic_cache_hits += 1);
return size;
}
crate::layout_work::record(|work| work.intrinsic_executions += 1);
let force = parent_ctx.child_force();
let mut child_ctx = parent_ctx.child(self.id, self.layout_state.arranged_bounds, force);
child_ctx.probing = true;
self.layout_state.measure_valid = false;
let started = start_widget_timing();
let phase = match axis {
Axis::Horizontal => ObservationPhase::IntrinsicHorizontal,
Axis::Vertical => ObservationPhase::IntrinsicVertical,
};
let observations = ObservationScope::new(
parent_ctx.window_id(),
self.id,
phase,
&self.observed_phases,
);
let intrinsic = self.widget.intrinsic_size(&mut child_ctx, axis, cross);
drop(observations);
record_widget_timing(
self.id,
self.widget.debug_name(),
WidgetTimingPhase::Measure,
started,
);
parent_ctx.extend_invalidations(child_ctx.take_invalidations());
parent_ctx.extend_wake_requests(child_ctx.take_wake_requests());
let intrinsic = IntrinsicSize::new(intrinsic.minimum, intrinsic.natural);
self.probe_cache
.get_or_insert_with(Default::default)
.intrinsics[axis_index] = Some((cross, intrinsic));
intrinsic
}
pub fn arrange(&mut self, parent_ctx: &mut ArrangeCtx, bounds: Rect) {
self.arrange_with_transform(parent_ctx, bounds, Transform::IDENTITY);
}
pub fn arrange_transformed(
&mut self,
parent_ctx: &mut ArrangeCtx,
bounds: Rect,
transform: Transform,
) {
self.arrange_with_transform(parent_ctx, bounds, transform);
}
fn arrange_with_transform(
&mut self,
parent_ctx: &mut ArrangeCtx,
bounds: Rect,
transform: Transform,
) {
crate::layout_work::record(|work| work.arrange_requests += 1);
let presentation_transform = transform.then(parent_ctx.presentation_transform());
if self.layout_state.arrange_valid
&& !parent_ctx.scope().must_rearrange(self.id)
&& self.layout_state.arranged_bounds == bounds
{
self.layout_state.relative_presentation_transform = transform;
if self.layout_state.presentation_transform != presentation_transform {
self.layout_state.presentation_transform = presentation_transform;
let mut visitor = ReprojectPresentationVisitor {
parent_transform: presentation_transform,
};
self.visit_children_mut(&mut visitor);
}
crate::layout_work::record(|work| work.arrange_cache_hits += 1);
return;
}
crate::layout_work::record(|work| work.arrange_executions += 1);
let size_changed = self.layout_state.arranged_bounds.size != bounds.size;
let delta = bounds.origin - self.layout_state.arranged_bounds.origin;
crate::layout_work::record(|work| work.translations += u64::from(delta != Vector::ZERO));
self.layout_state.arranged_bounds = bounds;
self.layout_state.relative_presentation_transform = transform;
self.layout_state.presentation_transform = presentation_transform;
self.layout_state.arrange_valid = true;
self.translate_descendants(delta);
let mut child_ctx = ArrangeCtx::new_at_with_transform(
parent_ctx.window_id(),
self.id,
parent_ctx.dpi(),
parent_ctx.current_time(),
self.layout_state.presentation_transform,
Rc::clone(parent_ctx.scope_rc()),
);
if size_changed {
child_ctx.request_paint();
}
let started = start_widget_timing();
let observations = ObservationScope::new(
parent_ctx.window_id(),
self.id,
ObservationPhase::Arrange,
&self.observed_phases,
);
self.widget.arrange(&mut child_ctx, bounds);
drop(observations);
record_widget_timing(
self.id,
self.widget.debug_name(),
WidgetTimingPhase::Arrange,
started,
);
parent_ctx.extend_invalidations(child_ctx.take_invalidations());
parent_ctx.extend_wake_requests(child_ctx.take_wake_requests());
}
pub fn paint(&self, parent_ctx: &mut PaintCtx) {
self.paint_into(parent_ctx, true);
}
fn paint_into(&self, parent_ctx: &mut PaintCtx, emit_layer: bool) {
let presentation_transform = self.layout_state.presentation_transform;
let relative_transform =
relative_transform(presentation_transform, parent_ctx.presentation_transform());
let reusable = self.widget.supports_output_reuse();
parent_ctx.output_reusable &= reusable;
let output_cache = parent_ctx
.output_cache
.as_ref()
.filter(|_| reusable)
.cloned();
let key = crate::output_cache::GeometryKey {
bounds: self.bounds(),
transform: presentation_transform,
};
let cached = output_cache.as_ref().and_then(|cache| {
cache.paint(self.id, key, &parent_ctx.text_system.text_layout_registry())
});
if let Some(fragment) = &cached
&& relative_transform.is_identity()
&& !(emit_layer
&& presentation_transform.is_identity()
&& self.current_layer_options().emits_layer())
{
crate::layout_work::record(|work| work.paint_cache_hits += 1);
parent_ctx.record_widget_paint_bounds(
self.id,
fragment
.scene
.paint_bounds()
.unwrap_or(self.layout_state.arranged_bounds),
);
parent_ctx.scene.append_ref(&fragment.scene);
parent_ctx
.widget_paint_bounds
.extend_from_slice(&fragment.bounds);
parent_ctx.extend_ime_composition_rect(fragment.ime);
return;
}
let mut child_ctx = PaintCtx::new_with_transform(
parent_ctx.window_id(),
self.id,
self.layout_state.arranged_bounds,
parent_ctx.focused_widget_id(),
parent_ctx.dpi(),
Arc::clone(&parent_ctx.text_system),
Arc::clone(&parent_ctx.font_registry),
Arc::clone(&parent_ctx.image_registry),
presentation_transform,
)
.with_frame_time(parent_ctx.frame_time);
child_ctx.output_cache = output_cache.clone();
let (mut scene, images, mut widget_paint_bounds, mut ime_composition_rect) =
if let Some(fragment) = cached {
crate::layout_work::record(|work| work.paint_cache_hits += 1);
(
fragment.scene.clone(),
Vec::new(),
fragment.bounds.clone(),
fragment.ime,
)
} else {
crate::layout_work::record(|work| work.paint_executions += 1);
let started = start_widget_timing();
let observations = ObservationScope::new(
parent_ctx.window_id(),
self.id,
ObservationPhase::Paint,
&self.observed_phases,
);
self.widget.paint(&mut child_ctx);
drop(observations);
record_widget_timing(
self.id,
self.widget.debug_name(),
WidgetTimingPhase::Paint,
started,
);
parent_ctx.output_reusable &= child_ctx.output_reusable;
let can_reuse = child_ctx.output_reusable;
let parts = child_ctx.into_parts();
if can_reuse
&& parts.1.is_empty()
&& let Some(cache) = &output_cache
{
cache.put_paint(self.id, key, &parts.0, &parts.2, parts.3);
}
parts
};
if !relative_transform.is_identity() {
let mut transformed = Scene::new();
transformed.push(SceneCommand::PushTransform {
transform: relative_transform,
});
transformed.append(scene);
transformed.push(SceneCommand::PopTransform);
scene = transformed;
for (_, bounds) in &mut widget_paint_bounds {
*bounds = relative_transform.transform_rect_bbox(*bounds);
}
ime_composition_rect =
ime_composition_rect.map(|bounds| relative_transform.transform_rect_bbox(bounds));
}
let paint_bounds = scene.paint_bounds().unwrap_or_else(|| {
relative_transform.transform_rect_bbox(self.layout_state.arranged_bounds)
});
parent_ctx.record_widget_paint_bounds(self.id, paint_bounds);
if emit_layer
&& presentation_transform.is_identity()
&& self.current_layer_options().emits_layer()
{
parent_ctx.push_layer(
self.build_layer_descriptor(&scene, parent_ctx.frame_time),
scene,
);
} else {
parent_ctx.append_scene(scene);
}
parent_ctx.extend_widget_paint_bounds(widget_paint_bounds);
parent_ctx.extend_images(images);
parent_ctx.extend_ime_composition_rect(ime_composition_rect);
}
pub(crate) fn paint_layer_contents_for(
&mut self,
target: WidgetId,
parent_ctx: &mut PaintCtx,
) -> bool {
self.find_mut(target, &mut |pod| {
pod.paint_into(parent_ctx, false);
})
.is_some()
}
pub(crate) fn layer_descriptor_for(
&mut self,
target: WidgetId,
scene: &Scene,
frame_time: f64,
) -> Option<SceneLayerDescriptor> {
self.find_mut(target, &mut |pod| {
pod.build_layer_descriptor(scene, frame_time)
})
}
pub fn semantics(&self, parent_ctx: &mut SemanticsCtx) {
if self.inert {
return;
}
let presentation_transform = self.layout_state.presentation_transform;
let relative_transform =
relative_transform(presentation_transform, parent_ctx.presentation_transform());
let reusable = self.widget.supports_output_reuse();
parent_ctx.output_reusable &= reusable;
let output_cache = parent_ctx
.output_cache
.as_ref()
.filter(|_| reusable)
.cloned();
let key = crate::output_cache::GeometryKey {
bounds: self.bounds(),
transform: presentation_transform,
};
if let Some(nodes) = output_cache
.as_ref()
.and_then(|cache| cache.semantics(self.id, key))
{
crate::layout_work::record(|work| work.semantics_cache_hits += 1);
parent_ctx.extend_nodes(nodes.iter().cloned().map(|mut node| {
if !relative_transform.is_identity() {
node.bounds = relative_transform.transform_rect_bbox(node.bounds);
}
node
}));
return;
}
let mut child_ctx = SemanticsCtx::new_with_transform(
parent_ctx.window_id(),
self.id,
parent_ctx.root_widget_id(),
self.layout_state.arranged_bounds,
parent_ctx.focused_widget_id(),
presentation_transform,
);
child_ctx.output_cache = output_cache.clone();
let mut nodes = {
crate::layout_work::record(|work| work.semantics_executions += 1);
let started = start_widget_timing();
let observations = ObservationScope::new(
parent_ctx.window_id(),
self.id,
ObservationPhase::Semantics,
&self.observed_phases,
);
self.widget.semantics(&mut child_ctx);
drop(observations);
record_widget_timing(
self.id,
self.widget.debug_name(),
WidgetTimingPhase::Semantics,
started,
);
parent_ctx.output_reusable &= child_ctx.output_reusable;
let can_reuse = child_ctx.output_reusable;
let nodes = child_ctx.into_nodes();
if can_reuse && let Some(cache) = &output_cache {
cache.put_semantics(self.id, key, &nodes);
}
nodes
};
if !relative_transform.is_identity() {
for node in &mut nodes {
node.bounds = relative_transform.transform_rect_bbox(node.bounds);
}
}
parent_ctx.extend_nodes(nodes);
}
pub fn accepts_focus(&self) -> bool {
self.widget.accepts_focus()
}
pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
self.widget.visit_children(visitor);
}
pub(crate) fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
self.widget.visit_children_mut(visitor);
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn dispatch_event_for_path(
&mut self,
path: &[WidgetId],
window_id: WindowId,
dpi_info: DpiInfo,
current_time: f64,
phase: EventPhase,
focused_widget: Option<WidgetId>,
services: &HostServices,
command_sender: &CommandSender,
event: &Event,
) -> Option<EventDispatch> {
self.find_mut_path(path, &mut |pod| {
pod.dispatch_event(
window_id,
dpi_info,
current_time,
phase,
focused_widget,
services,
command_sender,
event,
)
})
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn dispatch_event_for(
&mut self,
target: WidgetId,
window_id: WindowId,
dpi_info: DpiInfo,
current_time: f64,
phase: EventPhase,
focused_widget: Option<WidgetId>,
services: &HostServices,
command_sender: &CommandSender,
event: &Event,
) -> Option<EventDispatch> {
self.find_mut(target, &mut |pod| {
pod.dispatch_event(
window_id,
dpi_info,
current_time,
phase,
focused_widget,
services,
command_sender,
event,
)
})
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn dispatch_command_for_path(
&mut self,
path: &[WidgetId],
window_id: WindowId,
dpi_info: DpiInfo,
current_time: f64,
focused_widget: Option<WidgetId>,
services: &HostServices,
command_sender: &CommandSender,
command: &Command<'_>,
) -> Option<EventDispatch> {
self.find_mut_path(path, &mut |pod| {
pod.dispatch_command(
window_id,
dpi_info,
current_time,
focused_widget,
services,
command_sender,
command,
)
})
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn dispatch_command_for(
&mut self,
target: WidgetId,
window_id: WindowId,
dpi_info: DpiInfo,
current_time: f64,
focused_widget: Option<WidgetId>,
services: &HostServices,
command_sender: &CommandSender,
command: &Command<'_>,
) -> Option<EventDispatch> {
self.find_mut(target, &mut |pod| {
pod.dispatch_command(
window_id,
dpi_info,
current_time,
focused_widget,
services,
command_sender,
command,
)
})
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn notify_focus_change_for(
&mut self,
target: WidgetId,
window_id: WindowId,
dpi_info: DpiInfo,
current_time: f64,
focused_widget: Option<WidgetId>,
services: &HostServices,
command_sender: &CommandSender,
focused: bool,
) -> Option<EventDispatch> {
self.find_mut(target, &mut |pod| {
pod.focus_changed(
window_id,
dpi_info,
current_time,
focused_widget,
services,
command_sender,
focused,
)
})
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn notify_focus_change_for_path(
&mut self,
path: &[WidgetId],
window_id: WindowId,
dpi_info: DpiInfo,
current_time: f64,
focused_widget: Option<WidgetId>,
services: &HostServices,
command_sender: &CommandSender,
focused: bool,
) -> Option<EventDispatch> {
self.find_mut_path(path, &mut |pod| {
pod.focus_changed(
window_id,
dpi_info,
current_time,
focused_widget,
services,
command_sender,
focused,
)
})
}
#[allow(clippy::too_many_arguments)]
fn dispatch_event(
&mut self,
window_id: WindowId,
dpi_info: DpiInfo,
current_time: f64,
phase: EventPhase,
focused_widget: Option<WidgetId>,
services: &HostServices,
command_sender: &CommandSender,
event: &Event,
) -> EventDispatch {
let local_event = event_for_transform(
event,
self.layout_state
.presentation_transform
.inverse()
.unwrap_or(Transform::IDENTITY),
);
let mut ctx = EventCtx::new(
window_id,
self.id,
self.layout_state.arranged_bounds,
dpi_info,
current_time,
phase,
focused_widget,
services.clone(),
command_sender.clone(),
);
self.widget.event(&mut ctx, &local_event);
let mut drag_requests = ctx.take_drag_requests();
for request in &mut drag_requests {
match request {
DragRequest::Begin(request) => {
request.position = self
.layout_state
.presentation_transform
.transform_point(request.position);
}
DragRequest::RefreshTargets => {}
}
}
EventDispatch {
handled: ctx.is_handled(),
invalidations: ctx.take_invalidations(),
focus_request: ctx.take_focus_request(),
wake_requests: ctx.take_wake_requests(),
pointer_capture_requests: ctx.take_pointer_capture_requests(),
cursor_requests: ctx.take_cursor_requests(),
drag_requests,
drop_acceptances: ctx.take_drop_acceptances(),
posted_events: ctx.take_posted_events(),
posted_commands: ctx.take_posted_commands(),
}
}
#[allow(clippy::too_many_arguments)]
fn dispatch_command(
&mut self,
window_id: WindowId,
dpi_info: DpiInfo,
current_time: f64,
focused_widget: Option<WidgetId>,
services: &HostServices,
command_sender: &CommandSender,
command: &Command<'_>,
) -> EventDispatch {
let mut ctx = EventCtx::new(
window_id,
self.id,
self.layout_state.arranged_bounds,
dpi_info,
current_time,
EventPhase::Target,
focused_widget,
services.clone(),
command_sender.clone(),
);
self.widget.command(&mut ctx, command);
ctx.into_dispatch()
}
fn focus_changed(
&mut self,
window_id: WindowId,
dpi_info: DpiInfo,
current_time: f64,
focused_widget: Option<WidgetId>,
services: &HostServices,
command_sender: &CommandSender,
focused: bool,
) -> EventDispatch {
let mut ctx = EventCtx::new(
window_id,
self.id,
self.layout_state.arranged_bounds,
dpi_info,
current_time,
EventPhase::Target,
focused_widget,
services.clone(),
command_sender.clone(),
);
self.widget.focus_changed(&mut ctx, focused);
EventDispatch {
handled: ctx.is_handled(),
invalidations: ctx.take_invalidations(),
focus_request: ctx.take_focus_request(),
wake_requests: ctx.take_wake_requests(),
pointer_capture_requests: ctx.take_pointer_capture_requests(),
cursor_requests: ctx.take_cursor_requests(),
drag_requests: ctx.take_drag_requests(),
drop_acceptances: ctx.take_drop_acceptances(),
posted_events: ctx.take_posted_events(),
posted_commands: ctx.take_posted_commands(),
}
}
fn find_mut<R, F>(&mut self, target: WidgetId, f: &mut F) -> Option<R>
where
F: FnMut(&mut WidgetPod) -> R,
{
if self.id == target {
return Some(f(self));
}
let mut result = None;
let mut visitor = FindMutVisitor {
target,
callback: f,
result: &mut result,
};
self.visit_children_mut(&mut visitor);
result
}
fn find_mut_path<R, F>(&mut self, path: &[WidgetId], f: &mut F) -> Option<R>
where
F: FnMut(&mut WidgetPod) -> R,
{
let (¤t, rest) = path.split_first()?;
if current != self.id {
return None;
}
if rest.is_empty() {
return Some(f(self));
}
let mut result = None;
let mut visitor = FindPathMutVisitor {
path: rest,
callback: f,
result: &mut result,
};
self.visit_children_mut(&mut visitor);
result
}
fn translate_descendants(&mut self, delta: Vector) {
if delta == Vector::ZERO {
return;
}
let mut visitor = TranslateVisitor { delta };
self.visit_children_mut(&mut visitor);
}
fn translate_subtree(&mut self, delta: Vector) {
if delta == Vector::ZERO {
return;
}
self.layout_state.arranged_bounds = self.layout_state.arranged_bounds.translate(delta);
self.translate_descendants(delta);
}
fn reproject_presentation_subtree(&mut self, parent_transform: Transform) {
self.layout_state.presentation_transform = self
.layout_state
.relative_presentation_transform
.then(parent_transform);
let mut visitor = ReprojectPresentationVisitor {
parent_transform: self.layout_state.presentation_transform,
};
self.visit_children_mut(&mut visitor);
}
pub(crate) fn build_layer_descriptor(
&self,
scene: &Scene,
frame_time: f64,
) -> SceneLayerDescriptor {
let options = self.current_layer_options();
SceneLayerDescriptor::new(
SceneLayerId::from_widget(self.id),
self.id,
self.layout_state.arranged_bounds,
)
.with_content_bounds(
scene
.content_bounds()
.unwrap_or(self.layout_state.arranged_bounds),
)
.with_paint_bounds(
scene
.paint_bounds()
.unwrap_or(self.layout_state.arranged_bounds),
)
.with_properties(self.current_layer_properties(frame_time))
.with_clip_to_ancestors(matches!(
options.composition_mode,
LayerCompositionMode::Normal
))
.with_composition_mode(options.composition_mode)
}
pub(crate) fn current_layer_options(&self) -> LayerOptions {
let mut options = self.widget.layer_options();
if self.force_paint_boundary {
options.paint_boundary = PaintBoundaryMode::Explicit;
}
if !self.layout_state.presentation_transform.is_identity() {
options.paint_boundary = PaintBoundaryMode::Flat;
options.composition_mode = LayerCompositionMode::Normal;
}
options
}
pub(crate) fn current_layer_properties(&self, frame_time: f64) -> LayerProperties {
self.widget.layer_properties_at(frame_time)
}
pub(crate) fn current_paint_boundary_mode(&self) -> PaintBoundaryMode {
self.current_layer_options().paint_boundary
}
pub(crate) fn current_stack_host_options(&self) -> Option<StackHostOptions> {
self.widget.stack_host_options()
}
pub(crate) fn current_stack_surface_options(&self) -> Option<StackSurfaceOptions> {
self.widget.stack_surface_options()
}
pub(crate) fn current_hit_test_self(&self) -> bool {
self.widget.hit_test_self()
}
pub(crate) fn current_overlay_options(&self) -> Option<OverlayOptions> {
self.widget.overlay_options()
}
pub(crate) fn layer_composition_mode_for(
&mut self,
target: WidgetId,
) -> Option<LayerCompositionMode> {
self.find_mut(target, &mut |pod| {
pod.current_layer_options().composition_mode
})
}
}
struct ReprojectPresentationVisitor {
parent_transform: Transform,
}
impl WidgetPodMutVisitor for ReprojectPresentationVisitor {
fn visit(&mut self, pod: &mut WidgetPod) {
pod.reproject_presentation_subtree(self.parent_transform);
}
}
struct TranslateVisitor {
delta: Vector,
}
impl WidgetPodMutVisitor for TranslateVisitor {
fn visit(&mut self, child: &mut WidgetPod) {
child.translate_subtree(self.delta);
}
}
struct CollectDiagnosticsVisitor<'a> {
output: &'a mut Vec<WidgetDiagnosticsSnapshot>,
}
impl WidgetPodVisitor for CollectDiagnosticsVisitor<'_> {
fn visit(&mut self, child: &WidgetPod) {
child.collect_diagnostics(self.output);
}
}
struct FindMutVisitor<'a, F, R>
where
F: FnMut(&mut WidgetPod) -> R,
{
target: WidgetId,
callback: &'a mut F,
result: &'a mut Option<R>,
}
impl<F, R> WidgetPodMutVisitor for FindMutVisitor<'_, F, R>
where
F: FnMut(&mut WidgetPod) -> R,
{
fn visit(&mut self, child: &mut WidgetPod) {
if self.result.is_none() {
*self.result = child.find_mut(self.target, self.callback);
}
}
}
struct FindPathMutVisitor<'a, F, R>
where
F: FnMut(&mut WidgetPod) -> R,
{
path: &'a [WidgetId],
callback: &'a mut F,
result: &'a mut Option<R>,
}
impl<F, R> WidgetPodMutVisitor for FindPathMutVisitor<'_, F, R>
where
F: FnMut(&mut WidgetPod) -> R,
{
fn visit(&mut self, child: &mut WidgetPod) {
if self.result.is_none() && self.path.first().copied() == Some(child.id) {
*self.result = child.find_mut_path(self.path, self.callback);
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FocusRequest {
Focus(WidgetId),
Clear,
Keep,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum WakeRequest {
ScheduleTimer {
token: TimerToken,
deadline: f64,
target: WidgetId,
},
CancelTimer {
token: TimerToken,
},
RegisterAsync {
token: AsyncWakeToken,
target: WidgetId,
},
UnregisterAsync {
token: AsyncWakeToken,
},
RequestAnimationFrame {
target: WidgetId,
},
Motion {
target: WidgetId,
kind: InvalidationKind,
until: f64,
},
MotionEnd {
target: WidgetId,
kind: InvalidationKind,
until: f64,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PointerCaptureRequest {
Capture { pointer_id: u64, target: WidgetId },
Release { pointer_id: u64 },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CursorRequest {
Grab {
target: WidgetId,
mode: CursorGrabMode,
},
Visibility {
target: WidgetId,
visible: bool,
},
}
#[derive(Debug, Clone)]
pub(crate) struct BeginDragRequest {
pub session_id: DragSessionId,
pub scope_id: DragScopeId,
pub pointer_id: u64,
pub source: WidgetId,
pub position: Point,
pub payload: DragPayload,
pub allowed_effects: DropEffects,
pub preview_label: Option<String>,
}
#[derive(Debug, Clone)]
pub(crate) enum DragRequest {
Begin(BeginDragRequest),
RefreshTargets,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct DropAcceptanceRequest {
pub target: WidgetId,
pub effect: DropEffect,
}
#[derive(Debug, Clone)]
pub(crate) struct PostedEventRequest {
pub target: WidgetId,
pub event: Event,
}
#[derive(Debug, Clone)]
pub(crate) struct PostedCommandRequest {
pub command: QueuedCommand,
}
#[derive(Debug, Clone)]
pub(crate) struct EventDispatch {
pub handled: bool,
pub invalidations: Vec<InvalidationRequest>,
pub focus_request: Option<FocusRequest>,
pub wake_requests: Vec<WakeRequest>,
pub pointer_capture_requests: Vec<PointerCaptureRequest>,
pub cursor_requests: Vec<CursorRequest>,
pub drag_requests: Vec<DragRequest>,
pub drop_acceptances: Vec<DropAcceptanceRequest>,
pub posted_events: Vec<PostedEventRequest>,
pub posted_commands: Vec<PostedCommandRequest>,
}
#[derive(Debug, Clone, Default)]
pub(crate) struct HostServices {
pub(crate) clipboard: Clipboard,
pub(crate) url_opener: UrlOpener,
}
#[derive(Debug, Clone)]
pub struct EventCtx {
window_id: WindowId,
widget_id: WidgetId,
bounds: Rect,
dpi_info: DpiInfo,
current_time: f64,
phase: EventPhase,
focused_widget_id: Option<WidgetId>,
services: HostServices,
command_sender: CommandSender,
handled: bool,
invalidations: Vec<InvalidationRequest>,
focus_request: Option<FocusRequest>,
wake_requests: Vec<WakeRequest>,
pointer_capture_requests: Vec<PointerCaptureRequest>,
cursor_requests: Vec<CursorRequest>,
drag_requests: Vec<DragRequest>,
drop_acceptances: Vec<DropAcceptanceRequest>,
posted_events: Vec<PostedEventRequest>,
posted_commands: Vec<PostedCommandRequest>,
}
impl EventCtx {
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
window_id: WindowId,
widget_id: WidgetId,
bounds: Rect,
dpi_info: DpiInfo,
current_time: f64,
phase: EventPhase,
focused_widget_id: Option<WidgetId>,
services: HostServices,
command_sender: CommandSender,
) -> Self {
Self {
window_id,
widget_id,
bounds,
dpi_info,
current_time,
phase,
focused_widget_id,
services,
command_sender,
handled: false,
invalidations: Vec::new(),
focus_request: None,
wake_requests: Vec::new(),
pointer_capture_requests: Vec::new(),
cursor_requests: Vec::new(),
drag_requests: Vec::new(),
drop_acceptances: Vec::new(),
posted_events: Vec::new(),
posted_commands: Vec::new(),
}
}
fn into_dispatch(mut self) -> EventDispatch {
EventDispatch {
handled: self.is_handled(),
invalidations: self.take_invalidations(),
focus_request: self.take_focus_request(),
wake_requests: self.take_wake_requests(),
pointer_capture_requests: self.take_pointer_capture_requests(),
cursor_requests: self.take_cursor_requests(),
drag_requests: self.take_drag_requests(),
drop_acceptances: self.take_drop_acceptances(),
posted_events: self.take_posted_events(),
posted_commands: self.take_posted_commands(),
}
}
pub const fn window_id(&self) -> WindowId {
self.window_id
}
pub const fn widget_id(&self) -> WidgetId {
self.widget_id
}
pub fn observe<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
where
O: Observable<T> + ?Sized,
{
crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
}
pub fn record_rebuild(&self, widget_name: &'static str, reason: impl Into<String>) {
crate::diagnostics::record_widget_rebuild(
self.window_id,
self.widget_id,
widget_name,
reason,
);
}
pub const fn bounds(&self) -> Rect {
self.bounds
}
pub const fn dpi(&self) -> DpiInfo {
self.dpi_info
}
pub const fn current_time(&self) -> f64 {
self.current_time
}
pub fn motion_policy(&self) -> MotionPolicy {
crate::motion_policy()
}
pub fn animate<T>(&mut self, motion: &mut Motion<T>, target: T, spec: AnimationSpec) -> bool
where
T: Interpolate + Copy + PartialEq,
{
self.animate_after(motion, target, 0.0, spec)
}
pub fn animate_after<T>(
&mut self,
motion: &mut Motion<T>,
target: T,
delay: f64,
spec: AnimationSpec,
) -> bool
where
T: Interpolate + Copy + PartialEq,
{
let before = motion.target();
let until = motion.start_after(target, self.current_time, delay, spec);
if before != target {
self.request_widget(motion.invalidation());
}
if let Some(until) = until {
self.track_motion(until, motion.invalidation());
}
until.is_some()
}
pub fn track_motion(&mut self, until: f64, kind: InvalidationKind) {
self.track_motion_for(self.widget_id, until, kind);
}
pub fn track_motion_for(&mut self, target: WidgetId, until: f64, kind: InvalidationKind) {
self.wake_requests.push(WakeRequest::Motion {
target,
kind,
until,
});
}
pub fn track_motion_end(&mut self, until: f64, kind: InvalidationKind) {
self.track_motion_end_for(self.widget_id, until, kind);
}
pub fn track_motion_end_for(&mut self, target: WidgetId, until: f64, kind: InvalidationKind) {
self.wake_requests.push(WakeRequest::MotionEnd {
target,
kind,
until,
});
}
pub const fn phase(&self) -> EventPhase {
self.phase
}
pub const fn focused_widget_id(&self) -> Option<WidgetId> {
self.focused_widget_id
}
pub fn is_focused(&self) -> bool {
self.focused_widget_id == Some(self.widget_id)
}
pub const fn is_handled(&self) -> bool {
self.handled
}
pub fn set_handled(&mut self) {
self.handled = true;
}
pub fn clipboard(&self) -> &Clipboard {
&self.services.clipboard
}
pub fn clipboard_text(&self) -> Option<String> {
self.services.clipboard.text()
}
pub fn set_clipboard_text(&mut self, text: impl AsRef<str>) {
self.services.clipboard.set_text(text);
}
pub fn url_opener(&self) -> &UrlOpener {
&self.services.url_opener
}
pub fn open_url(&mut self, url: impl AsRef<str>) -> bool {
self.services.url_opener.open(url)
}
pub fn command_sender(&self) -> &CommandSender {
&self.command_sender
}
pub fn post_event(&mut self, target: WidgetId, event: Event) {
self.posted_events
.push(PostedEventRequest { target, event });
}
pub fn post_command<T>(&mut self, target: WidgetId, key: CommandKey<T>, payload: T)
where
T: Send + Sync + 'static,
{
self.posted_commands.push(PostedCommandRequest {
command: queued_command(
CommandTarget::Widget {
window_id: self.window_id,
widget_id: target,
},
CommandDelivery::Directed,
key,
payload,
),
});
}
pub fn request_focus(&mut self) {
self.focus_request = Some(FocusRequest::Focus(self.widget_id));
}
pub fn request_focus_for(&mut self, widget_id: WidgetId) {
self.focus_request = Some(FocusRequest::Focus(widget_id));
}
pub fn clear_focus(&mut self) {
self.focus_request = Some(FocusRequest::Clear);
}
pub fn keep_focus(&mut self) {
self.focus_request = Some(FocusRequest::Keep);
}
pub fn schedule_timer_at(&mut self, deadline: f64) -> TimerToken {
let token = TimerToken::new(NEXT_TIMER_TOKEN.fetch_add(1, Ordering::Relaxed));
self.wake_requests.push(WakeRequest::ScheduleTimer {
token,
deadline,
target: self.widget_id,
});
token
}
pub fn schedule_timer_after(&mut self, delay: f64) -> TimerToken {
self.schedule_timer_at(self.current_time + delay)
}
pub fn cancel_timer(&mut self, token: TimerToken) {
self.wake_requests.push(WakeRequest::CancelTimer { token });
}
pub fn register_async_wakeup(&mut self) -> AsyncWakeToken {
let token = AsyncWakeToken::new(NEXT_ASYNC_WAKE_TOKEN.fetch_add(1, Ordering::Relaxed));
self.wake_requests.push(WakeRequest::RegisterAsync {
token,
target: self.widget_id,
});
token
}
pub fn unregister_async_wakeup(&mut self, token: AsyncWakeToken) {
self.wake_requests
.push(WakeRequest::UnregisterAsync { token });
}
pub fn request_animation_frame(&mut self) {
self.wake_requests.push(WakeRequest::RequestAnimationFrame {
target: self.widget_id,
});
}
pub fn request_pointer_capture(&mut self, pointer_id: u64) {
self.pointer_capture_requests
.push(PointerCaptureRequest::Capture {
pointer_id,
target: self.widget_id,
});
}
pub fn release_pointer_capture(&mut self, pointer_id: u64) {
self.pointer_capture_requests
.push(PointerCaptureRequest::Release { pointer_id });
}
pub fn request_cursor_grab(&mut self, mode: CursorGrabMode) {
self.cursor_requests.push(CursorRequest::Grab {
target: self.widget_id,
mode,
});
}
pub fn request_cursor_visibility(&mut self, visible: bool) {
self.cursor_requests.push(CursorRequest::Visibility {
target: self.widget_id,
visible,
});
}
pub fn begin_drag(
&mut self,
scope_id: DragScopeId,
pointer_id: u64,
position: Point,
payload: DragPayload,
allowed_effects: impl Into<DropEffects>,
preview_label: Option<String>,
) -> DragSessionId {
let session_id = DragSessionId::new(NEXT_DRAG_SESSION_ID.fetch_add(1, Ordering::Relaxed));
self.drag_requests
.push(DragRequest::Begin(BeginDragRequest {
session_id,
scope_id,
pointer_id,
source: self.widget_id,
position,
payload,
allowed_effects: allowed_effects.into(),
preview_label,
}));
session_id
}
pub fn refresh_drag_targets(&mut self) {
self.drag_requests.push(DragRequest::RefreshTargets);
}
pub fn accept_drop(&mut self, effect: DropEffect) {
if effect.is_none() {
return;
}
self.drop_acceptances.push(DropAcceptanceRequest {
target: self.widget_id,
effect,
});
}
pub fn request(&mut self, request: InvalidationRequest) {
self.invalidations.push(request);
}
pub fn request_measure(&mut self) {
self.request_widget(InvalidationKind::Measure);
}
pub fn request_arrange(&mut self) {
self.request_widget(InvalidationKind::Arrange);
}
pub fn request_ordering(&mut self) {
self.request_widget(InvalidationKind::Ordering);
}
pub fn request_paint(&mut self) {
self.request_widget(InvalidationKind::Paint);
}
pub fn request_paint_rect(&mut self, rect: Rect) {
self.request(
InvalidationRequest::new(
InvalidationTarget::Widget(self.widget_id),
InvalidationKind::Paint,
)
.with_region(rect),
);
}
pub fn request_transform(&mut self) {
self.request_widget(InvalidationKind::Transform);
}
pub fn request_effect(&mut self) {
self.request_widget(InvalidationKind::Effect);
}
pub fn request_visibility(&mut self) {
self.request_widget(InvalidationKind::Visibility);
}
pub fn request_hit_test(&mut self) {
self.request_widget(InvalidationKind::HitTest);
}
pub fn request_text(&mut self) {
self.request_widget(InvalidationKind::Text);
}
pub fn request_semantics(&mut self) {
self.request_widget(InvalidationKind::Semantics);
}
pub fn request_resources(&mut self) {
self.request_widget(InvalidationKind::Resources);
}
pub fn invalidations(&self) -> &[InvalidationRequest] {
&self.invalidations
}
pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationRequest> {
std::mem::take(&mut self.invalidations)
}
pub(crate) fn take_focus_request(&mut self) -> Option<FocusRequest> {
self.focus_request.take()
}
pub(crate) fn take_wake_requests(&mut self) -> Vec<WakeRequest> {
std::mem::take(&mut self.wake_requests)
}
pub(crate) fn take_pointer_capture_requests(&mut self) -> Vec<PointerCaptureRequest> {
std::mem::take(&mut self.pointer_capture_requests)
}
pub(crate) fn take_cursor_requests(&mut self) -> Vec<CursorRequest> {
std::mem::take(&mut self.cursor_requests)
}
pub(crate) fn take_drag_requests(&mut self) -> Vec<DragRequest> {
std::mem::take(&mut self.drag_requests)
}
pub(crate) fn take_drop_acceptances(&mut self) -> Vec<DropAcceptanceRequest> {
std::mem::take(&mut self.drop_acceptances)
}
pub(crate) fn take_posted_events(&mut self) -> Vec<PostedEventRequest> {
std::mem::take(&mut self.posted_events)
}
pub(crate) fn take_posted_commands(&mut self) -> Vec<PostedCommandRequest> {
std::mem::take(&mut self.posted_commands)
}
fn request_widget(&mut self, kind: InvalidationKind) {
self.request(InvalidationRequest::new(
InvalidationTarget::Widget(self.widget_id),
kind,
));
}
}
static NEXT_MEASURE_GENERATION: AtomicU64 = AtomicU64::new(1);
#[derive(Debug)]
pub(crate) struct MeasureScope {
generation: u64,
reusable_queries: bool,
force_all: bool,
dirty: HashSet<WidgetId>,
subtree_roots: HashSet<WidgetId>,
}
#[derive(Debug, Default)]
pub(crate) struct ArrangeScope {
force_all: bool,
dirty: HashSet<WidgetId>,
}
impl ArrangeScope {
pub(crate) fn force_all() -> Self {
Self {
force_all: true,
dirty: HashSet::new(),
}
}
pub(crate) fn scoped(dirty: HashSet<WidgetId>) -> Self {
Self {
force_all: false,
dirty,
}
}
fn must_rearrange(&self, widget_id: WidgetId) -> bool {
self.force_all || self.dirty.contains(&widget_id)
}
}
impl Default for MeasureScope {
fn default() -> Self {
Self {
generation: NEXT_MEASURE_GENERATION.fetch_add(1, Ordering::Relaxed),
reusable_queries: true,
force_all: false,
dirty: HashSet::new(),
subtree_roots: HashSet::new(),
}
}
}
impl MeasureScope {
pub(crate) fn is_full_invalidation(&self) -> bool {
self.force_all
}
pub(crate) fn force_all() -> Self {
Self {
force_all: true,
dirty: HashSet::new(),
subtree_roots: HashSet::new(),
..Self::default()
}
}
pub(crate) fn scoped(dirty: HashSet<WidgetId>, subtree_roots: HashSet<WidgetId>) -> Self {
Self {
force_all: false,
dirty,
subtree_roots,
..Self::default()
}
}
fn must_remeasure(&self, widget_id: WidgetId) -> bool {
self.force_all || self.dirty.contains(&widget_id)
}
fn forces_subtree(&self, widget_id: WidgetId) -> bool {
self.subtree_roots.contains(&widget_id)
}
}
#[derive(Debug, Clone)]
pub struct MeasureCtx {
window_id: WindowId,
widget_id: WidgetId,
bounds: Rect,
layout: LayoutContext,
current_time: f64,
invalidations: Vec<InvalidationRequest>,
wake_requests: Vec<WakeRequest>,
scope: Rc<MeasureScope>,
force: bool,
probing: bool,
query_cache: Option<crate::measure_cache::SharedQueryCache>,
query_context: Option<crate::measure_cache::QueryContext>,
}
impl MeasureCtx {
pub fn with_layout(
window_id: WindowId,
widget_id: WidgetId,
bounds: Rect,
layout: LayoutContext,
) -> Self {
Self::with_layout_scoped(
window_id,
widget_id,
bounds,
layout,
0.0,
Rc::new(MeasureScope {
reusable_queries: false,
..MeasureScope::force_all()
}),
true,
)
}
pub(crate) fn with_layout_scoped(
window_id: WindowId,
widget_id: WidgetId,
bounds: Rect,
layout: LayoutContext,
current_time: f64,
scope: Rc<MeasureScope>,
force: bool,
) -> Self {
Self {
window_id,
widget_id,
bounds,
layout,
current_time,
invalidations: Vec::new(),
wake_requests: Vec::new(),
scope,
force,
probing: false,
query_cache: None,
query_context: None,
}
}
#[cfg(test)]
pub(crate) fn new(
window_id: WindowId,
widget_id: WidgetId,
bounds: Rect,
dpi_info: DpiInfo,
text_system: Arc<TextSystem>,
font_registry: Arc<FontRegistry>,
image_registry: Arc<ImageRegistry>,
) -> Self {
Self::with_layout(
window_id,
widget_id,
bounds,
LayoutContext::new(dpi_info, text_system, font_registry, image_registry),
)
}
pub(crate) fn new_scoped_at(
window_id: WindowId,
widget_id: WidgetId,
bounds: Rect,
dpi_info: DpiInfo,
text_system: Arc<TextSystem>,
font_registry: Arc<FontRegistry>,
image_registry: Arc<ImageRegistry>,
scope: Rc<MeasureScope>,
current_time: f64,
) -> Self {
Self::with_layout_scoped(
window_id,
widget_id,
bounds,
LayoutContext::new(dpi_info, text_system, font_registry, image_registry),
current_time,
scope,
false,
)
}
pub(crate) fn set_query_cache(&mut self, cache: crate::measure_cache::SharedQueryCache) {
self.query_context = Some(cache.borrow().context());
self.query_cache = Some(cache);
}
pub(crate) fn scope(&self) -> &MeasureScope {
&self.scope
}
pub(crate) fn child_force(&self) -> bool {
self.force || self.scope.forces_subtree(self.widget_id)
}
pub(crate) fn child(&self, widget_id: WidgetId, bounds: Rect, force: bool) -> Self {
let mut child = Self::with_layout_scoped(
self.window_id,
widget_id,
bounds,
self.layout.clone(),
self.current_time,
Rc::clone(&self.scope),
force,
);
child.probing = self.probing;
child.query_cache = self.query_cache.clone();
child.query_context = self.query_context;
child
}
pub const fn window_id(&self) -> WindowId {
self.window_id
}
pub const fn widget_id(&self) -> WidgetId {
self.widget_id
}
pub fn observe<T, O>(&self, observable: &O) -> T
where
O: Observable<T> + ?Sized,
{
self.observe_with(observable, InvalidationKind::Measure)
}
pub fn observe_with<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
where
O: Observable<T> + ?Sized,
{
crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
}
pub fn record_rebuild(&self, widget_name: &'static str, reason: impl Into<String>) {
crate::diagnostics::record_widget_rebuild(
self.window_id,
self.widget_id,
widget_name,
reason,
);
}
pub const fn bounds(&self) -> Rect {
self.bounds
}
pub const fn layout(&self) -> &LayoutContext {
&self.layout
}
pub const fn dpi(&self) -> DpiInfo {
self.layout.dpi()
}
pub const fn current_time(&self) -> f64 {
self.current_time
}
pub fn motion_policy(&self) -> MotionPolicy {
crate::motion_policy()
}
pub fn animate<T>(&mut self, motion: &mut Motion<T>, target: T, spec: AnimationSpec) -> bool
where
T: Interpolate + Copy + PartialEq,
{
self.animate_after(motion, target, 0.0, spec)
}
pub fn animate_after<T>(
&mut self,
motion: &mut Motion<T>,
target: T,
delay: f64,
spec: AnimationSpec,
) -> bool
where
T: Interpolate + Copy + PartialEq,
{
let before = motion.target();
let until = motion.start_after(target, self.current_time, delay, spec);
if before != target {
self.request_widget(motion.invalidation());
}
if let Some(until) = until {
self.track_motion(until, motion.invalidation());
}
until.is_some()
}
pub fn track_motion(&mut self, until: f64, kind: InvalidationKind) {
self.track_motion_for(self.widget_id, until, kind);
}
pub fn track_motion_for(&mut self, target: WidgetId, until: f64, kind: InvalidationKind) {
self.wake_requests.push(WakeRequest::Motion {
target,
kind,
until,
});
}
pub fn track_motion_end(&mut self, until: f64, kind: InvalidationKind) {
self.track_motion_end_for(self.widget_id, until, kind);
}
pub fn track_motion_end_for(&mut self, target: WidgetId, until: f64, kind: InvalidationKind) {
self.wake_requests.push(WakeRequest::MotionEnd {
target,
kind,
until,
});
}
pub fn request(&mut self, request: InvalidationRequest) {
self.invalidations.push(request);
}
pub fn request_measure(&mut self) {
self.request_widget(InvalidationKind::Measure);
}
pub fn request_arrange(&mut self) {
self.request_widget(InvalidationKind::Arrange);
}
pub fn request_ordering(&mut self) {
self.request_widget(InvalidationKind::Ordering);
}
pub fn request_paint(&mut self) {
self.request_widget(InvalidationKind::Paint);
}
pub fn request_semantics(&mut self) {
self.request_widget(InvalidationKind::Semantics);
}
pub fn request_animation_frame(&mut self) {
self.wake_requests.push(WakeRequest::RequestAnimationFrame {
target: self.widget_id,
});
}
pub fn invalidations(&self) -> &[InvalidationRequest] {
&self.invalidations
}
pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationRequest> {
std::mem::take(&mut self.invalidations)
}
pub(crate) fn take_wake_requests(&mut self) -> Vec<WakeRequest> {
std::mem::take(&mut self.wake_requests)
}
pub(crate) fn extend_invalidations(&mut self, invalidations: Vec<InvalidationRequest>) {
self.invalidations.extend(invalidations);
}
pub(crate) fn extend_wake_requests(&mut self, wake_requests: Vec<WakeRequest>) {
self.wake_requests.extend(wake_requests);
}
fn request_widget(&mut self, kind: InvalidationKind) {
self.request(InvalidationRequest::new(
InvalidationTarget::Widget(self.widget_id),
kind,
));
}
}
#[derive(Debug, Clone)]
pub struct ArrangeCtx {
window_id: WindowId,
widget_id: WidgetId,
dpi_info: DpiInfo,
current_time: f64,
presentation_transform: Transform,
scope: Rc<ArrangeScope>,
invalidations: Vec<InvalidationRequest>,
wake_requests: Vec<WakeRequest>,
}
impl ArrangeCtx {
#[cfg(test)]
pub(crate) fn new(window_id: WindowId, widget_id: WidgetId, dpi_info: DpiInfo) -> Self {
Self::new_at(window_id, widget_id, dpi_info, 0.0)
}
#[cfg(test)]
pub(crate) fn new_at(
window_id: WindowId,
widget_id: WidgetId,
dpi_info: DpiInfo,
current_time: f64,
) -> Self {
Self::new_at_with_transform(
window_id,
widget_id,
dpi_info,
current_time,
Transform::IDENTITY,
Rc::new(ArrangeScope::force_all()),
)
}
pub(crate) fn new_scoped_at(
window_id: WindowId,
widget_id: WidgetId,
dpi_info: DpiInfo,
current_time: f64,
scope: Rc<ArrangeScope>,
) -> Self {
Self::new_at_with_transform(
window_id,
widget_id,
dpi_info,
current_time,
Transform::IDENTITY,
scope,
)
}
pub(crate) fn new_at_with_transform(
window_id: WindowId,
widget_id: WidgetId,
dpi_info: DpiInfo,
current_time: f64,
presentation_transform: Transform,
scope: Rc<ArrangeScope>,
) -> Self {
Self {
window_id,
widget_id,
dpi_info,
current_time,
presentation_transform,
scope,
invalidations: Vec::new(),
wake_requests: Vec::new(),
}
}
pub const fn window_id(&self) -> WindowId {
self.window_id
}
pub const fn widget_id(&self) -> WidgetId {
self.widget_id
}
pub const fn presentation_transform(&self) -> Transform {
self.presentation_transform
}
pub(crate) fn scope(&self) -> &ArrangeScope {
self.scope.as_ref()
}
pub(crate) fn scope_rc(&self) -> &Rc<ArrangeScope> {
&self.scope
}
pub fn observe<T, O>(&self, observable: &O) -> T
where
O: Observable<T> + ?Sized,
{
self.observe_with(observable, InvalidationKind::Arrange)
}
pub fn observe_with<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
where
O: Observable<T> + ?Sized,
{
crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
}
pub const fn dpi(&self) -> DpiInfo {
self.dpi_info
}
pub const fn current_time(&self) -> f64 {
self.current_time
}
pub fn motion_policy(&self) -> MotionPolicy {
crate::motion_policy()
}
pub fn animate<T>(&mut self, motion: &mut Motion<T>, target: T, spec: AnimationSpec) -> bool
where
T: Interpolate + Copy + PartialEq,
{
self.animate_after(motion, target, 0.0, spec)
}
pub fn animate_after<T>(
&mut self,
motion: &mut Motion<T>,
target: T,
delay: f64,
spec: AnimationSpec,
) -> bool
where
T: Interpolate + Copy + PartialEq,
{
let before = motion.target();
let until = motion.start_after(target, self.current_time, delay, spec);
if before != target {
self.request_widget(motion.invalidation());
}
if let Some(until) = until {
self.track_motion(until, motion.invalidation());
}
until.is_some()
}
pub fn track_motion(&mut self, until: f64, kind: InvalidationKind) {
self.track_motion_for(self.widget_id, until, kind);
}
pub fn track_motion_for(&mut self, target: WidgetId, until: f64, kind: InvalidationKind) {
self.wake_requests.push(WakeRequest::Motion {
target,
kind,
until,
});
}
pub fn track_motion_end(&mut self, until: f64, kind: InvalidationKind) {
self.track_motion_end_for(self.widget_id, until, kind);
}
pub fn track_motion_end_for(&mut self, target: WidgetId, until: f64, kind: InvalidationKind) {
self.wake_requests.push(WakeRequest::MotionEnd {
target,
kind,
until,
});
}
pub fn request(&mut self, request: InvalidationRequest) {
self.invalidations.push(request);
}
pub fn request_measure(&mut self) {
self.request_widget(InvalidationKind::Measure);
}
pub fn request_arrange(&mut self) {
self.request_widget(InvalidationKind::Arrange);
}
pub fn request_ordering(&mut self) {
self.request_widget(InvalidationKind::Ordering);
}
pub fn request_paint(&mut self) {
self.request_widget(InvalidationKind::Paint);
}
pub fn request_semantics(&mut self) {
self.request_widget(InvalidationKind::Semantics);
}
pub fn request_transform(&mut self) {
self.request_widget(InvalidationKind::Transform);
}
pub fn request_animation_frame(&mut self) {
self.wake_requests.push(WakeRequest::RequestAnimationFrame {
target: self.widget_id,
});
}
pub fn invalidations(&self) -> &[InvalidationRequest] {
&self.invalidations
}
pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationRequest> {
std::mem::take(&mut self.invalidations)
}
pub(crate) fn take_wake_requests(&mut self) -> Vec<WakeRequest> {
std::mem::take(&mut self.wake_requests)
}
pub(crate) fn extend_invalidations(&mut self, invalidations: Vec<InvalidationRequest>) {
self.invalidations.extend(invalidations);
}
pub(crate) fn extend_wake_requests(&mut self, wake_requests: Vec<WakeRequest>) {
self.wake_requests.extend(wake_requests);
}
fn request_widget(&mut self, kind: InvalidationKind) {
self.request(InvalidationRequest::new(
InvalidationTarget::Widget(self.widget_id),
kind,
));
}
}
#[derive(Debug, Clone)]
pub struct PaintCtx {
pub(crate) output_cache: Option<crate::output_cache::OutputScope>,
output_reusable: bool,
window_id: WindowId,
widget_id: WidgetId,
focused_widget_id: Option<WidgetId>,
bounds: Rect,
presentation_transform: Transform,
dpi_info: DpiInfo,
text_system: Arc<TextSystem>,
font_registry: Arc<FontRegistry>,
image_registry: Arc<ImageRegistry>,
scene: Scene,
images: Vec<(ImageHandle, PaintImageResource)>,
widget_paint_bounds: Vec<(WidgetId, Rect)>,
ime_composition_rect: Option<Rect>,
frame_time: f64,
}
macro_rules! impl_animate_ctx {
($($ctx:ty),*) => {$(
impl crate::motion::AnimateCtx for $ctx {
fn animate_after<T>(
&mut self,
motion: &mut Motion<T>,
target: T,
delay: f64,
spec: AnimationSpec,
) -> bool
where
T: Interpolate + Copy + PartialEq,
{
<$ctx>::animate_after(self, motion, target, delay, spec)
}
}
)*};
}
impl_animate_ctx!(EventCtx, MeasureCtx, ArrangeCtx);
impl FrameClock for PaintCtx {
fn frame_time(&self) -> f64 {
self.frame_time
}
}
impl FrameClock for EventCtx {
fn frame_time(&self) -> f64 {
self.current_time
}
}
impl FrameClock for MeasureCtx {
fn frame_time(&self) -> f64 {
self.current_time
}
}
impl FrameClock for ArrangeCtx {
fn frame_time(&self) -> f64 {
self.current_time
}
}
#[derive(Debug, Clone)]
pub(crate) enum PaintImageResource {
Cpu(RegisteredImage),
External(RegisteredExternalImage),
}
impl PaintCtx {
pub fn motion_policy(&self) -> MotionPolicy {
crate::motion_policy()
}
pub fn output_color_range(&self) -> Option<crate::OutputColorRange> {
self.observe(&crate::window_output_color_range_signal(self.window_id))
}
pub(crate) fn new(
window_id: WindowId,
widget_id: WidgetId,
bounds: Rect,
focused_widget_id: Option<WidgetId>,
dpi_info: DpiInfo,
text_system: Arc<TextSystem>,
font_registry: Arc<FontRegistry>,
image_registry: Arc<ImageRegistry>,
) -> Self {
Self::new_with_transform(
window_id,
widget_id,
bounds,
focused_widget_id,
dpi_info,
text_system,
font_registry,
image_registry,
Transform::IDENTITY,
)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn new_with_transform(
window_id: WindowId,
widget_id: WidgetId,
bounds: Rect,
focused_widget_id: Option<WidgetId>,
dpi_info: DpiInfo,
text_system: Arc<TextSystem>,
font_registry: Arc<FontRegistry>,
image_registry: Arc<ImageRegistry>,
presentation_transform: Transform,
) -> Self {
Self {
output_cache: None,
output_reusable: true,
window_id,
widget_id,
focused_widget_id,
bounds,
presentation_transform,
dpi_info,
text_system,
font_registry,
image_registry,
scene: Scene::new(),
images: Vec::new(),
widget_paint_bounds: Vec::new(),
ime_composition_rect: None,
frame_time: 0.0,
}
}
pub(crate) const fn with_frame_time(mut self, frame_time: f64) -> Self {
self.frame_time = frame_time;
self
}
pub const fn frame_time(&self) -> f64 {
self.frame_time
}
pub const fn window_id(&self) -> WindowId {
self.window_id
}
pub const fn widget_id(&self) -> WidgetId {
self.widget_id
}
pub const fn presentation_transform(&self) -> Transform {
self.presentation_transform
}
pub fn observe<T, O>(&self, observable: &O) -> T
where
O: Observable<T> + ?Sized,
{
self.observe_with(observable, InvalidationKind::Paint)
}
pub fn observe_with<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
where
O: Observable<T> + ?Sized,
{
crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
}
pub const fn focused_widget_id(&self) -> Option<WidgetId> {
self.focused_widget_id
}
pub fn is_focused(&self) -> bool {
self.focused_widget_id == Some(self.widget_id)
}
pub const fn bounds(&self) -> Rect {
self.bounds
}
pub const fn dpi(&self) -> DpiInfo {
self.dpi_info
}
pub fn measure_text(
&self,
text: impl Into<String>,
style: TextStyle,
) -> sui_core::Result<TextMeasurement> {
self.text_system
.measure_text(text, style, self.font_registry.as_ref())
}
pub fn shape_text(
&self,
text: impl Into<String>,
box_size: Size,
style: TextStyle,
) -> sui_core::Result<TextLayout> {
self.text_system
.shape_text(text, box_size, style, self.font_registry.as_ref())
}
pub fn layout_text_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout> {
self.text_system
.layout_document(request, self.font_registry.as_ref())
}
pub fn clear(&mut self, color: Color) {
self.scene.push(SceneCommand::Clear(color));
}
pub fn fill(&mut self, path: impl Into<Path>, brush: impl Into<Brush>) {
self.scene.push(SceneCommand::FillPath {
path: path.into(),
brush: brush.into(),
});
}
pub fn fill_rect(&mut self, rect: Rect, brush: impl Into<Brush>) {
self.scene.push(SceneCommand::FillRect {
rect,
brush: brush.into(),
});
}
pub fn fill_bounds(&mut self, brush: impl Into<Brush>) {
self.fill_rect(self.bounds, brush);
}
pub fn stroke(&mut self, path: impl Into<Path>, brush: impl Into<Brush>, stroke: StrokeStyle) {
self.scene.push(SceneCommand::StrokePath {
path: path.into(),
brush: brush.into(),
stroke,
});
}
pub fn stroke_rect(&mut self, rect: Rect, brush: impl Into<Brush>, stroke: StrokeStyle) {
self.scene.push(SceneCommand::StrokeRect {
rect,
brush: brush.into(),
stroke,
});
}
pub fn stroke_bounds(&mut self, brush: impl Into<Brush>, stroke: StrokeStyle) {
self.stroke_rect(self.bounds, brush, stroke);
}
pub fn draw_text(&mut self, rect: Rect, text: impl Into<String>, style: TextStyle) {
let text = text.into();
let paint_color = style.color;
let mut layout_style = style.clone();
layout_style.color = Color::WHITE;
let layout_run = TextRun {
rect,
text: text.clone(),
style: layout_style,
};
let fallback_run = TextRun { rect, text, style };
match self.text_system.shape_text_run_persistent(
Some(stable_text_run_handle(&layout_run)),
&layout_run,
self.font_registry.as_ref(),
) {
Ok(layout) => self.scene.push(SceneCommand::DrawShapedText(
ShapedText::new(rect.origin, &layout).with_color(paint_color),
)),
Err(_) => self.scene.push(SceneCommand::DrawText(fallback_run)),
}
}
pub fn draw_text_layout(&mut self, origin: Point, layout: &TextLayout) {
let persistent = self.text_system.adopt_layout(layout.clone());
self.draw_persistent_text_layout(origin, &persistent);
}
pub fn draw_text_layout_with_color(
&mut self,
origin: Point,
layout: &TextLayout,
color: Color,
) {
let persistent = self.text_system.adopt_layout(layout.clone());
self.draw_persistent_text_layout_with_color(origin, &persistent, color);
}
pub fn draw_persistent_text_layout(&mut self, origin: Point, layout: &PersistentTextLayout) {
self.text_system.touch_persistent_layout(layout);
self.scene
.push(SceneCommand::DrawShapedText(ShapedText::new(
origin, layout,
)));
}
pub fn draw_persistent_text_layout_with_color(
&mut self,
origin: Point,
layout: &PersistentTextLayout,
color: Color,
) {
self.text_system.touch_persistent_layout(layout);
self.scene.push(SceneCommand::DrawShapedText(
ShapedText::new(origin, layout).with_color(color),
));
}
pub fn draw_persistent_text_layout_window(
&mut self,
origin: Point,
layout: &PersistentTextLayout,
line_range: std::ops::Range<usize>,
) {
self.text_system.touch_persistent_layout(layout);
self.scene
.push(SceneCommand::DrawShapedTextWindow(ShapedTextWindow::new(
origin, layout, line_range,
)));
}
pub fn draw_persistent_text_layout_window_with_color(
&mut self,
origin: Point,
layout: &PersistentTextLayout,
line_range: std::ops::Range<usize>,
color: Color,
) {
self.text_system.touch_persistent_layout(layout);
self.scene.push(SceneCommand::DrawShapedTextWindow(
ShapedTextWindow::new(origin, layout, line_range).with_color(color),
));
}
pub fn label(&mut self, rect: Rect, text: impl Into<String>, color: Color) {
self.draw_text(rect, text, TextStyle::new(color));
}
pub fn push_text_render_policy(&mut self, policy: TextRenderPolicy) {
self.scene.push(SceneCommand::PushTextRenderPolicy {
policy: policy.normalized(),
});
}
pub fn pop_text_render_policy(&mut self) {
self.scene.push(SceneCommand::PopTextRenderPolicy);
}
pub fn draw_image(&mut self, rect: Rect, image: sui_core::ImageHandle) {
self.scene.push(SceneCommand::DrawImage {
rect,
source: ImageSource::new(image),
});
}
pub fn image_registered(&self, image: ImageHandle) -> bool {
self.image_registry.contains(image)
|| self.images.iter().any(|(handle, _)| *handle == image)
}
pub fn draw_image_source(&mut self, rect: Rect, source: ImageSource) {
self.scene.push(SceneCommand::DrawImage { rect, source });
}
pub fn draw_image_quad(&mut self, points: [Point; 4], image: ImageHandle) {
self.draw_image_quad_source(points, ImageSource::new(image));
}
pub fn draw_image_quad_source(&mut self, points: [Point; 4], source: ImageSource) {
self.scene
.push(SceneCommand::DrawImageQuad { points, source });
}
pub fn widget_image_handle(&self, slot: u64) -> ImageHandle {
let mut hasher = DefaultHasher::new();
self.widget_id.hash(&mut hasher);
slot.hash(&mut hasher);
ImageHandle::new(WIDGET_IMAGE_HANDLE_NAMESPACE | (hasher.finish() >> 1))
}
pub fn register_image(&mut self, handle: ImageHandle, image: RegisteredImage) {
self.images.push((handle, PaintImageResource::Cpu(image)));
}
pub fn register_external_image(&mut self, handle: ImageHandle, image: RegisteredExternalImage) {
self.images
.push((handle, PaintImageResource::External(image)));
}
pub fn draw_shader_rect(&mut self, rect: Rect, shader: WidgetShader) {
self.scene
.push(SceneCommand::DrawShaderRect { rect, shader });
}
pub fn fill_rrect(&mut self, rect: Rect, radii: [f32; 4], brush: impl Into<Brush>) {
self.scene.push(SceneCommand::FillRoundedRect {
rect,
radii,
brush: brush.into(),
border: None,
shadow: None,
});
}
pub fn fill_rrect_bordered(
&mut self,
rect: Rect,
radii: [f32; 4],
brush: impl Into<Brush>,
border: Border,
) {
self.scene.push(SceneCommand::FillRoundedRect {
rect,
radii,
brush: brush.into(),
border: Some(border),
shadow: None,
});
}
pub fn draw_shadow(&mut self, rect: Rect, radii: [f32; 4], shadow: ShadowParams) {
self.scene.push(SceneCommand::FillRoundedRect {
rect,
radii,
brush: Brush::Solid(Color::TRANSPARENT),
border: None,
shadow: Some(shadow),
});
}
pub fn fill_rrect_with_shadow(
&mut self,
rect: Rect,
radii: [f32; 4],
brush: impl Into<Brush>,
shadow: ShadowParams,
) {
self.scene.push(SceneCommand::FillRoundedRect {
rect,
radii,
brush: brush.into(),
border: None,
shadow: Some(shadow),
});
}
pub fn push_clip(&mut self, path: impl Into<Path>) {
self.scene
.push(SceneCommand::PushClipPath { path: path.into() });
}
pub fn push_clip_rect(&mut self, rect: Rect) {
self.scene.push(SceneCommand::PushClip { rect });
}
pub fn pop_clip(&mut self) {
self.scene.push(SceneCommand::PopClip);
}
pub fn push_transform(&mut self, transform: Transform) {
self.scene.push(SceneCommand::PushTransform { transform });
}
pub fn with_transform<R>(
&mut self,
transform: Transform,
paint: impl FnOnce(&mut PaintCtx) -> R,
) -> R {
let presentation_transform = transform.then(self.presentation_transform);
let mut child_ctx = PaintCtx::new_with_transform(
self.window_id,
self.widget_id,
self.bounds,
self.focused_widget_id,
self.dpi_info,
Arc::clone(&self.text_system),
Arc::clone(&self.font_registry),
Arc::clone(&self.image_registry),
presentation_transform,
)
.with_frame_time(self.frame_time);
let output = paint(&mut child_ctx);
let (scene, images, mut widget_paint_bounds, ime_composition_rect) = child_ctx.into_parts();
if !scene.commands().is_empty() {
self.scene.push(SceneCommand::PushTransform { transform });
self.scene.append(scene);
self.scene.push(SceneCommand::PopTransform);
}
for (_, bounds) in &mut widget_paint_bounds {
*bounds = transform.transform_rect_bbox(*bounds);
}
self.extend_widget_paint_bounds(widget_paint_bounds);
self.extend_images(images);
self.extend_ime_composition_rect(
ime_composition_rect.map(|bounds| transform.transform_rect_bbox(bounds)),
);
output
}
pub fn translate(&mut self, delta: Vector) {
self.push_transform(Transform::translation_vector(delta));
}
pub fn pop_transform(&mut self) {
self.scene.push(SceneCommand::PopTransform);
}
pub fn push(&mut self, command: SceneCommand) {
self.scene.push(command);
}
pub fn push_retained_scene_layer(&mut self, owner: WidgetId, bounds: Rect, scene: Arc<Scene>) {
let content_bounds = scene.content_bounds().unwrap_or(bounds);
let paint_bounds = scene.paint_bounds().unwrap_or(bounds);
let descriptor = SceneLayerDescriptor::new(SceneLayerId::from_widget(owner), owner, bounds)
.with_content_bounds(content_bounds)
.with_paint_bounds(paint_bounds)
.with_hit_test(false);
self.scene
.push(SceneCommand::Layer(SceneLayer::from_shared_descriptor(
descriptor, scene,
)));
self.record_widget_paint_bounds(owner, paint_bounds);
}
pub fn with_retained_scene_layer<R>(
&mut self,
owner: WidgetId,
bounds: Rect,
paint: impl FnOnce(&mut PaintCtx) -> R,
) -> R {
let mut child_ctx = PaintCtx::new_with_transform(
self.window_id,
owner,
bounds,
self.focused_widget_id,
self.dpi_info,
Arc::clone(&self.text_system),
Arc::clone(&self.font_registry),
Arc::clone(&self.image_registry),
self.presentation_transform,
)
.with_frame_time(self.frame_time);
child_ctx.output_cache = self.output_cache.clone();
let output = paint(&mut child_ctx);
self.output_reusable &= child_ctx.output_reusable;
let (scene, images, widget_paint_bounds, ime_composition_rect) = child_ctx.into_parts();
if !scene.commands().is_empty() {
self.push_retained_scene_layer(owner, bounds, Arc::new(scene));
}
self.extend_widget_paint_bounds(widget_paint_bounds);
self.extend_images(images);
self.extend_ime_composition_rect(ime_composition_rect);
output
}
pub fn scene(&self) -> &Scene {
&self.scene
}
pub fn scene_mut(&mut self) -> &mut Scene {
&mut self.scene
}
pub fn set_ime_composition_rect(&mut self, rect: Rect) {
self.ime_composition_rect = Some(rect);
}
pub fn clear_ime_composition_rect(&mut self) {
self.ime_composition_rect = None;
}
pub const fn ime_composition_rect(&self) -> Option<Rect> {
self.ime_composition_rect
}
pub(crate) fn push_layer(&mut self, descriptor: SceneLayerDescriptor, scene: Scene) {
self.scene
.push(SceneCommand::Layer(SceneLayer::from_descriptor(
descriptor, scene,
)));
}
pub(crate) fn append_scene(&mut self, scene: Scene) {
self.scene.append(scene);
}
pub(crate) fn record_widget_paint_bounds(&mut self, widget_id: WidgetId, paint_bounds: Rect) {
self.widget_paint_bounds.push((widget_id, paint_bounds));
}
pub(crate) fn extend_widget_paint_bounds(
&mut self,
mut widget_paint_bounds: Vec<(WidgetId, Rect)>,
) {
if self.widget_paint_bounds.is_empty() {
self.widget_paint_bounds = widget_paint_bounds;
} else {
self.widget_paint_bounds.append(&mut widget_paint_bounds);
}
}
pub(crate) fn extend_images(&mut self, images: Vec<(ImageHandle, PaintImageResource)>) {
self.images.extend(images);
}
pub(crate) fn extend_ime_composition_rect(&mut self, ime_composition_rect: Option<Rect>) {
if ime_composition_rect.is_some() {
self.ime_composition_rect = ime_composition_rect;
}
}
pub(crate) fn into_parts(
self,
) -> (
Scene,
Vec<(ImageHandle, PaintImageResource)>,
Vec<(WidgetId, Rect)>,
Option<Rect>,
) {
(
self.scene,
self.images,
self.widget_paint_bounds,
self.ime_composition_rect,
)
}
}
fn stable_text_run_handle(run: &TextRun) -> TextLayoutHandle {
let mut hasher = DefaultHasher::new();
run.text.hash(&mut hasher);
run.rect.size.width.to_bits().hash(&mut hasher);
run.rect.size.height.to_bits().hash(&mut hasher);
run.style.font.map(|font| font.get()).hash(&mut hasher);
run.style.font_size.to_bits().hash(&mut hasher);
run.style.line_height.to_bits().hash(&mut hasher);
run.style.weight.value().hash(&mut hasher);
run.style.style.hash(&mut hasher);
run.style.stretch.hash(&mut hasher);
run.style.features.hash(&mut hasher);
TextLayoutHandle::new(hasher.finish().max(1))
}
#[derive(Debug, Clone)]
pub struct SemanticsCtx {
pub(crate) output_cache: Option<crate::output_cache::OutputScope>,
output_reusable: bool,
window_id: WindowId,
widget_id: WidgetId,
root_widget_id: WidgetId,
focused_widget_id: Option<WidgetId>,
bounds: Rect,
presentation_transform: Transform,
nodes: Vec<SemanticsNode>,
}
impl SemanticsCtx {
pub(crate) fn new(
window_id: WindowId,
widget_id: WidgetId,
root_widget_id: WidgetId,
bounds: Rect,
focused_widget_id: Option<WidgetId>,
) -> Self {
Self::new_with_transform(
window_id,
widget_id,
root_widget_id,
bounds,
focused_widget_id,
Transform::IDENTITY,
)
}
pub(crate) fn new_with_transform(
window_id: WindowId,
widget_id: WidgetId,
root_widget_id: WidgetId,
bounds: Rect,
focused_widget_id: Option<WidgetId>,
presentation_transform: Transform,
) -> Self {
Self {
output_cache: None,
output_reusable: true,
window_id,
widget_id,
root_widget_id,
focused_widget_id,
bounds,
presentation_transform,
nodes: Vec::new(),
}
}
pub const fn window_id(&self) -> WindowId {
self.window_id
}
pub const fn widget_id(&self) -> WidgetId {
self.widget_id
}
pub fn observe<T, O>(&self, observable: &O) -> T
where
O: Observable<T> + ?Sized,
{
self.observe_with(observable, InvalidationKind::Semantics)
}
pub fn observe_with<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
where
O: Observable<T> + ?Sized,
{
crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
}
pub const fn root_widget_id(&self) -> WidgetId {
self.root_widget_id
}
pub const fn focused_widget_id(&self) -> Option<WidgetId> {
self.focused_widget_id
}
pub fn is_focused(&self) -> bool {
self.focused_widget_id == Some(self.widget_id)
}
pub const fn bounds(&self) -> Rect {
self.bounds
}
pub const fn presentation_transform(&self) -> Transform {
self.presentation_transform
}
pub fn push(&mut self, node: SemanticsNode) {
self.nodes.push(node);
}
pub fn nodes(&self) -> &[SemanticsNode] {
&self.nodes
}
pub(crate) fn extend_nodes(&mut self, nodes: impl IntoIterator<Item = SemanticsNode>) {
self.nodes.extend(nodes);
}
pub(crate) fn into_nodes(self) -> Vec<SemanticsNode> {
self.nodes
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use crate::CommandSender;
use super::{
ArrangeCtx, EventCtx, EventPhase, HostServices, KeyedChildren, MeasureCtx, MeasureScope,
PaintCtx, SemanticsCtx, SingleChild, WakeRequest, Widget, WidgetChildren, WidgetPod,
WidgetPodMutVisitor, WidgetPodVisitor, relative_transform,
};
use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use sui_core::{
Color, DpiInfo, ImageHandle, InvalidationKind, Point, Rect, SemanticsNode, SemanticsRole,
Size, Transform, Vector, WidgetId, WindowId,
};
#[test]
fn relative_transform_canonicalizes_shared_transform_roundoff() {
let parent = Transform::new(0.32, 0.0, 0.0, 0.32, 1430.0, 510.0);
let roundoff = Transform::new(0.32000002, 0.0, 0.0, 0.31999996, 1430.0001, 509.99994);
assert_eq!(relative_transform(roundoff, parent), Transform::IDENTITY);
let translated = Transform::new(0.32, 0.0, 0.0, 0.32, 1430.01, 510.0);
assert!(!relative_transform(translated, parent).is_identity());
}
use sui_layout::{Constraints, LayoutContext};
use sui_scene::{ImageRegistry, RegisteredImage, SceneCommand, StrokeStyle};
use sui_text::{FontRegistry, FontWeight, TextRun, TextStyle, TextSystem};
fn measure_ctx(window_id: WindowId, widget_id: WidgetId) -> MeasureCtx {
MeasureCtx::new(
window_id,
widget_id,
Rect::ZERO,
DpiInfo::default(),
std::sync::Arc::new(TextSystem::new()),
std::sync::Arc::new(FontRegistry::new()),
std::sync::Arc::new(ImageRegistry::new()),
)
}
#[test]
fn measure_ctx_wraps_reusable_layout_context() {
let mut images = ImageRegistry::new();
images.insert(
ImageHandle::new(9),
RegisteredImage::from_rgba8(3, 2, vec![255; 3 * 2 * 4]).unwrap(),
);
let layout = LayoutContext::new(
DpiInfo::new(
1.5,
Some(144.0),
Size::new(200.0, 100.0),
Size::new(300.0, 150.0),
),
Arc::new(TextSystem::new()),
Arc::new(FontRegistry::new()),
Arc::new(images),
);
let measure = MeasureCtx::with_layout(
WindowId::new(1),
WidgetId::new(2),
Rect::new(4.0, 6.0, 32.0, 18.0),
layout.clone(),
);
assert_eq!(measure.dpi(), layout.dpi());
assert_eq!(measure.bounds(), Rect::new(4.0, 6.0, 32.0, 18.0));
assert_eq!(
measure.layout().image_size(ImageHandle::new(9)),
Some(Size::new(3.0, 2.0))
);
}
#[test]
fn measure_and_paint_ctx_expose_dpi_info() {
let dpi = DpiInfo::new(
2.0,
Some(192.0),
sui_core::Size::new(320.0, 180.0),
sui_core::Size::new(640.0, 360.0),
);
let measure = MeasureCtx::new(
WindowId::new(1),
WidgetId::new(2),
Rect::ZERO,
dpi,
std::sync::Arc::new(TextSystem::new()),
std::sync::Arc::new(FontRegistry::new()),
std::sync::Arc::new(ImageRegistry::new()),
);
let paint = PaintCtx::new(
WindowId::new(1),
WidgetId::new(2),
Rect::new(0.0, 0.0, 120.0, 60.0),
None,
dpi,
Arc::new(TextSystem::new()),
Arc::new(FontRegistry::new()),
Arc::new(ImageRegistry::new()),
);
let event = EventCtx::new(
WindowId::new(1),
WidgetId::new(2),
Rect::new(0.0, 0.0, 120.0, 60.0),
dpi,
0.0,
EventPhase::Target,
None,
HostServices::default(),
CommandSender::new(),
);
assert_eq!(measure.dpi(), dpi);
assert_eq!(paint.dpi(), dpi);
assert_eq!(event.dpi(), dpi);
}
struct LabelWidget;
impl Widget for LabelWidget {
fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> sui_core::Size {
constraints.clamp(sui_core::Size::new(48.0, 20.0))
}
fn paint(&self, ctx: &mut PaintCtx) {
ctx.fill_bounds(Color::rgba(0.2, 0.3, 0.4, 1.0));
}
fn semantics(&self, ctx: &mut SemanticsCtx) {
ctx.push(SemanticsNode::new(
ctx.widget_id(),
SemanticsRole::Text,
ctx.bounds(),
));
}
}
struct BoundsLeaf;
impl Widget for BoundsLeaf {
fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
constraints.max
}
fn paint(&self, ctx: &mut PaintCtx) {
ctx.fill_rect(
Rect::new(10.0, 10.0, 80.0, 50.0),
Color::rgba(0.2, 0.3, 0.4, 1.0),
);
}
}
struct BoundsWrapper {
child: WidgetPod,
clip: Option<Rect>,
translation: Vector,
}
impl BoundsWrapper {
fn new(child: impl Widget + 'static, clip: Option<Rect>, translation: Vector) -> Self {
Self {
child: WidgetPod::new(child),
clip,
translation,
}
}
}
impl Widget for BoundsWrapper {
fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
self.child.measure(ctx, constraints)
}
fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
self.child.arrange(ctx, bounds);
}
fn paint(&self, ctx: &mut PaintCtx) {
if let Some(clip) = self.clip {
ctx.push_clip_rect(clip);
}
if self.translation != Vector::ZERO {
ctx.translate(self.translation);
}
self.child.paint(ctx);
if self.translation != Vector::ZERO {
ctx.pop_transform();
}
if self.clip.is_some() {
ctx.pop_clip();
}
}
fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
visitor.visit(&self.child);
}
fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
visitor.visit(&mut self.child);
}
}
#[test]
fn event_ctx_tracks_widget_scoped_invalidations_and_focus() {
let mut ctx = EventCtx::new(
WindowId::new(1),
WidgetId::new(2),
Rect::new(8.0, 12.0, 24.0, 36.0),
DpiInfo::default(),
0.0,
EventPhase::Target,
None,
HostServices::default(),
CommandSender::new(),
);
ctx.request_measure();
ctx.request_paint_rect(Rect::new(8.0, 12.0, 24.0, 36.0));
ctx.request_transform();
ctx.request_effect();
ctx.request_visibility();
ctx.request_animation_frame();
ctx.request_focus();
ctx.set_handled();
assert!(ctx.is_handled());
assert_eq!(ctx.bounds(), Rect::new(8.0, 12.0, 24.0, 36.0));
assert_eq!(ctx.invalidations().len(), 5);
assert_eq!(ctx.invalidations()[0].kind, InvalidationKind::Measure);
assert_eq!(
ctx.invalidations()[1].region,
Some(Rect::new(8.0, 12.0, 24.0, 36.0))
);
assert_eq!(ctx.invalidations()[2].kind, InvalidationKind::Transform);
assert_eq!(ctx.invalidations()[3].kind, InvalidationKind::Effect);
assert_eq!(ctx.invalidations()[4].kind, InvalidationKind::Visibility);
assert_eq!(
ctx.take_wake_requests(),
vec![WakeRequest::RequestAnimationFrame {
target: WidgetId::new(2)
}]
);
}
#[test]
fn request_animation_frame_enqueues_widget_for_next_frame() {
let mut ctx = EventCtx::new(
WindowId::new(4),
WidgetId::new(9),
Rect::new(0.0, 0.0, 20.0, 10.0),
DpiInfo::default(),
16.0,
EventPhase::Target,
None,
HostServices::default(),
CommandSender::new(),
);
ctx.request_animation_frame();
assert_eq!(
ctx.take_wake_requests(),
vec![WakeRequest::RequestAnimationFrame {
target: WidgetId::new(9)
}]
);
}
struct CountingChild {
measures: Rc<Cell<u32>>,
}
impl Widget for CountingChild {
fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> sui_core::Size {
self.measures.set(self.measures.get() + 1);
constraints.clamp(sui_core::Size::new(10.0, 10.0))
}
}
struct PassthroughParent {
child: WidgetPod,
}
impl Widget for PassthroughParent {
fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> sui_core::Size {
self.child.measure(ctx, constraints)
}
fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
visitor.visit(&self.child);
}
fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
visitor.visit(&mut self.child);
}
}
fn scoped_measure_ctx(root_id: WidgetId, scope: MeasureScope) -> MeasureCtx {
MeasureCtx::new_scoped_at(
WindowId::new(1),
root_id,
Rect::ZERO,
DpiInfo::default(),
Arc::new(TextSystem::new()),
Arc::new(FontRegistry::new()),
Arc::new(ImageRegistry::new()),
Rc::new(scope),
0.0,
)
}
#[test]
fn scalar_probes_preserve_final_state_and_have_bounded_storage() {
struct Probe {
calls: Rc<Cell<u32>>,
width: Rc<Cell<f32>>,
}
impl Widget for Probe {
fn measure(&mut self, _: &mut MeasureCtx, constraints: Constraints) -> Size {
self.calls.set(self.calls.get() + 1);
self.width.set(constraints.max.width);
constraints.clamp(Size::new(30.0, 10.0))
}
}
let calls = Rc::new(Cell::new(0));
let width = Rc::new(Cell::new(0.0));
let mut pod = WidgetPod::new(Probe {
calls: calls.clone(),
width: width.clone(),
});
let root = WidgetId::new(u64::MAX);
let constraint = |width| Constraints::tight(Size::new(width, 10.0));
let mut clean = scoped_measure_ctx(root, MeasureScope::default());
pod.probe_measure(&mut clean, constraint(10.0));
pod.probe_measure(&mut clean, constraint(20.0));
pod.measure(&mut clean, constraint(100.0));
let before = calls.get();
assert_eq!(pod.probe_measure(&mut clean, constraint(10.0)).width, 10.0);
pod.measure(&mut clean, constraint(100.0));
assert_eq!(calls.get(), before);
assert_eq!(width.get(), 100.0);
assert_eq!(pod.measured_size().width, 100.0);
pod.probe_measure(&mut clean, constraint(30.0));
pod.probe_measure(&mut clean, constraint(40.0));
pod.probe_measure(&mut clean, constraint(50.0));
pod.probe_measure(&mut clean, constraint(10.0)); assert_eq!(calls.get(), before + 4);
assert_eq!(
pod.probe_cache
.as_ref()
.unwrap()
.measurements
.iter()
.flatten()
.count(),
4
);
}
#[test]
fn size_only_hooks_require_explicit_forwarding_and_final_commit() {
struct Leaf {
queries: Rc<Cell<u32>>,
commits: Rc<Cell<u32>>,
width: Rc<Cell<f32>>,
}
impl Widget for Leaf {
fn measure_size(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
self.queries.set(self.queries.get() + 1);
c.clamp(Size::new(20.0, 10.0))
}
fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
self.commits.set(self.commits.get() + 1);
self.width.set(c.max.width);
c.clamp(Size::new(20.0, 10.0))
}
}
struct Forwarder(WidgetPod);
impl Widget for Forwarder {
fn measure_size(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
self.0.probe_measure(ctx, c)
}
fn measure(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
self.0.measure(ctx, c);
self.0.measured_size()
}
}
let queries = Rc::new(Cell::new(0));
let commits = Rc::new(Cell::new(0));
let width = Rc::new(Cell::new(0.0));
let mut pod = WidgetPod::new(Forwarder(WidgetPod::new(Leaf {
queries: queries.clone(),
commits: commits.clone(),
width: width.clone(),
})));
let mut ctx = scoped_measure_ctx(WidgetId::new(u64::MAX), MeasureScope::default());
let c = Constraints::tight(Size::new(100.0, 10.0));
assert_eq!(pod.probe_measure(&mut ctx, c), c.max);
assert_eq!(queries.get(), 1);
assert_eq!(commits.get(), 0);
assert_eq!(width.get(), 0.0);
assert_eq!(pod.measure(&mut ctx, c), c.max);
assert_eq!(
commits.get(),
1,
"a size probe cannot satisfy final measurement"
);
pod.probe_measure(&mut ctx, Constraints::tight(Size::new(50.0, 10.0)));
pod.measure(&mut ctx, c);
assert_eq!(commits.get(), 2);
assert_eq!(width.get(), 100.0);
}
#[test]
fn default_size_hook_preserves_stateful_child_measure_contract() {
struct Leaf(Rc<Cell<f32>>);
impl Widget for Leaf {
fn measure_size(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
Size::new(c.max.width, 10.0)
}
fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
self.0.set(c.max.width);
Size::new(c.max.width, 10.0)
}
}
struct Legacy {
child: WidgetPod,
width: Rc<Cell<f32>>,
}
impl Widget for Legacy {
fn measure(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
self.child.measure(ctx, c);
Size::new(self.width.get(), 10.0)
}
}
let width = Rc::new(Cell::new(0.0));
let mut pod = WidgetPod::new(Legacy {
child: WidgetPod::new(Leaf(width.clone())),
width: width.clone(),
});
let mut ctx = scoped_measure_ctx(WidgetId::new(u64::MAX), MeasureScope::default());
let c = |width| Constraints::new(Size::ZERO, Size::new(width, 20.0));
assert_eq!(pod.probe_measure(&mut ctx, c(100.0)).width, 100.0);
assert_eq!(pod.probe_measure(&mut ctx, c(200.0)).width, 200.0);
assert_eq!(pod.probe_measure(&mut ctx, c(100.0)).width, 100.0);
assert_eq!(pod.measure(&mut ctx, c(100.0)).width, 100.0);
assert_eq!(width.get(), 100.0);
}
#[test]
fn axis_queries_are_distinct_and_invalidate_with_the_window_context() {
use sui_layout::Axis;
struct Leaf(Rc<Cell<u32>>, Rc<Cell<f32>>);
impl Widget for Leaf {
fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
self.0.set(self.0.get() + 1);
c.clamp(Size::new(self.1.get(), 13.0))
}
}
let calls = Rc::new(Cell::new(0));
let value = Rc::new(Cell::new(27.0));
let mut pod = WidgetPod::new(Leaf(calls.clone(), value.clone()));
let shared = crate::measure_cache::MeasureQueryCache::shared();
let root = WidgetId::new(u64::MAX);
let mut ctx = scoped_measure_ctx(root, MeasureScope::default());
ctx.set_query_cache(shared.clone());
let c = Constraints::new(Size::ZERO, Size::new(100.0, 100.0));
for width in 100..110 {
let c = Constraints::new(Size::ZERO, Size::new(width as f32, 100.0));
assert_eq!(pod.probe_measure_axis(&mut ctx, c, Axis::Horizontal), 27.0);
assert_eq!(pod.probe_measure_axis(&mut ctx, c, Axis::Vertical), 13.0);
assert_eq!(pod.probe_measure(&mut ctx, c), Size::new(27.0, 13.0));
}
let before = calls.get();
assert_eq!(pod.probe_measure_axis(&mut ctx, c, Axis::Horizontal), 27.0);
assert_eq!(pod.probe_measure_axis(&mut ctx, c, Axis::Vertical), 13.0);
assert_eq!(pod.probe_measure(&mut ctx, c), Size::new(27.0, 13.0));
assert_eq!(
calls.get(),
before,
"overflow hits must preserve query kind"
);
assert_eq!(pod.measure(&mut ctx, c), Size::new(27.0, 13.0));
assert_eq!(calls.get(), before + 1, "axis hits cannot commit layout");
value.set(41.0);
shared.borrow_mut().invalidate_context();
let mut next = scoped_measure_ctx(root, MeasureScope::default());
next.set_query_cache(shared);
assert_eq!(pod.probe_measure_axis(&mut next, c, Axis::Horizontal), 41.0);
assert_eq!(pod.measure(&mut next, c), Size::new(41.0, 13.0));
}
#[test]
fn window_query_cache_reuses_evicted_local_entries_and_respects_all_invalidations() {
struct Leaf(Rc<Cell<f32>>, Rc<Cell<u32>>);
impl Widget for Leaf {
fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
self.1.set(self.1.get() + 1);
c.clamp(Size::new(self.0.get(), 10.0))
}
}
let value = Rc::new(Cell::new(20.0));
let calls = Rc::new(Cell::new(0));
let mut pod = WidgetPod::new(Leaf(value.clone(), calls.clone()));
let shared = crate::measure_cache::MeasureQueryCache::shared();
let root = WidgetId::new(u64::MAX);
let mut clean = scoped_measure_ctx(root, MeasureScope::default());
clean.set_query_cache(shared.clone());
let constraint = |width| Constraints::new(Size::ZERO, Size::new(width, 20.0));
for width in 100..104 {
pod.probe_measure(&mut clean, constraint(width as f32));
}
for width in 100..104 {
let key = crate::measure_cache::QueryKey::new(
pod.id(),
pod.probe_cache.as_ref().unwrap().revision,
constraint(width as f32),
)
.unwrap();
let mut window = shared.borrow_mut();
let context = window.context();
assert!(
window.get(context, &key).is_none(),
"small query sets should stay in the local cache"
);
}
for width in 104..110 {
pod.probe_measure(&mut clean, constraint(width as f32));
}
let before = calls.get();
assert_eq!(pod.probe_measure(&mut clean, constraint(100.0)).width, 20.0);
assert_eq!(
calls.get(),
before,
"the window cache should survive local eviction"
);
value.set(30.0);
let mut dirty = scoped_measure_ctx(
root,
MeasureScope::scoped(HashSet::from([pod.id()]), HashSet::new()),
);
dirty.set_query_cache(shared.clone());
assert_eq!(pod.probe_measure(&mut dirty, constraint(100.0)).width, 30.0);
pod.measure(&mut clean, constraint(100.0));
value.set(40.0);
shared.borrow_mut().invalidate_context(); clean.set_query_cache(shared.clone()); assert_eq!(pod.measure(&mut clean, constraint(100.0)).width, 40.0);
let mut external =
MeasureCtx::with_layout(clean.window_id(), root, Rect::ZERO, clean.layout().clone());
value.set(50.0);
assert_eq!(
pod.probe_measure(&mut external, constraint(100.0)).width,
50.0
);
value.set(60.0);
assert_eq!(
pod.probe_measure(&mut external, constraint(100.0)).width,
60.0
);
assert_eq!(pod.probe_measure(&mut clean, constraint(100.0)).width, 60.0);
let mut other = scoped_measure_ctx(root, MeasureScope::default());
other.set_query_cache(crate::measure_cache::MeasureQueryCache::shared());
value.set(70.0);
assert_eq!(pod.measure(&mut other, constraint(100.0)).width, 70.0);
}
#[test]
fn probe_invalidation_discards_all_constraints_and_preserves_forced_callbacks() {
struct Probe(Rc<Cell<u32>>);
impl Widget for Probe {
fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
self.0.set(self.0.get() + 1);
ctx.request_paint();
ctx.request_animation_frame();
constraints.clamp(Size::new(self.0.get() as f32, 10.0))
}
}
let calls = Rc::new(Cell::new(0));
let mut pod = WidgetPod::new(Probe(calls.clone()));
let root = WidgetId::new(u64::MAX);
let a = Constraints::new(Size::ZERO, Size::new(100.0, 10.0));
let b = Constraints::new(Size::ZERO, Size::new(200.0, 10.0));
let mut initial = scoped_measure_ctx(root, MeasureScope::force_all());
pod.probe_measure(&mut initial, a);
pod.probe_measure(&mut initial, b);
let mut dirty = scoped_measure_ctx(
root,
MeasureScope::scoped(HashSet::from([pod.id()]), HashSet::new()),
);
pod.probe_measure(&mut dirty, a);
pod.measure(&mut dirty, a);
pod.measure(&mut dirty, a);
assert_eq!(
calls.get(),
5,
"forced ordinary callbacks must still execute"
);
assert_eq!(dirty.invalidations.len(), 3);
assert_eq!(dirty.wake_requests.len(), 3);
let mut clean = scoped_measure_ctx(root, MeasureScope::default());
pod.probe_measure(&mut clean, b);
assert_eq!(
calls.get(),
6,
"an unqueried constraint survived invalidation"
);
let mut subtree = scoped_measure_ctx(
root,
MeasureScope::scoped(HashSet::new(), HashSet::from([root])),
);
pod.probe_measure(&mut subtree, b);
assert_eq!(calls.get(), 7);
let mut resized = scoped_measure_ctx(root, MeasureScope::force_all());
pod.probe_measure(&mut resized, b);
assert_eq!(calls.get(), 8);
}
#[test]
fn external_measure_context_keeps_full_measure_semantics_when_reused() {
struct Leaf(Rc<Cell<f32>>);
impl Widget for Leaf {
fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
c.clamp(Size::new(self.0.get(), 10.0))
}
}
struct Parent(WidgetPod);
impl Widget for Parent {
fn measure(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
let natural = self.0.probe_measure(ctx, Constraints::UNBOUNDED);
self.0.measure(ctx, c);
c.clamp(natural)
}
}
let value = Rc::new(Cell::new(20.0));
let mut pod = WidgetPod::new(Parent(WidgetPod::new(Leaf(value.clone()))));
let root = WidgetId::new(u64::MAX);
let template = scoped_measure_ctx(root, MeasureScope::force_all());
let mut ctx = MeasureCtx::with_layout(
template.window_id(),
root,
Rect::ZERO,
template.layout().clone(),
);
let constraints = Constraints::new(Size::ZERO, Size::new(100.0, 20.0));
assert_eq!(pod.measure(&mut ctx, constraints).width, 20.0);
value.set(40.0);
assert_eq!(pod.measure(&mut ctx, constraints).width, 40.0);
}
#[test]
fn dirty_probes_reuse_results_within_a_pass_but_final_measurement_still_executes() {
let calls = Rc::new(Cell::new(0));
let mut pod = WidgetPod::new(CountingChild {
measures: calls.clone(),
});
let root = WidgetId::new(u64::MAX);
let constraints = Constraints::tight(Size::new(100.0, 10.0));
let mut pass = scoped_measure_ctx(root, MeasureScope::force_all());
pod.probe_measure(&mut pass, constraints);
pod.probe_measure(&mut pass, constraints);
assert_eq!(calls.get(), 1);
pod.measure(&mut pass, constraints);
pod.measure(&mut pass, constraints);
assert_eq!(calls.get(), 3);
pod.intrinsic_size(&mut pass, sui_layout::Axis::Horizontal, 10.0);
pod.intrinsic_size(&mut pass, sui_layout::Axis::Horizontal, 10.0);
assert_eq!(calls.get(), 4);
let mut next = scoped_measure_ctx(root, MeasureScope::force_all());
pod.probe_measure(&mut next, constraints);
assert_eq!(
calls.get(),
5,
"a new dirty pass must invalidate the previous queries"
);
}
#[test]
fn intrinsic_cache_keys_include_axis_and_cross_extent() {
struct Probe(Rc<Cell<u32>>);
impl Widget for Probe {
fn intrinsic_size(
&mut self,
_: &mut MeasureCtx,
axis: sui_layout::Axis,
cross: f32,
) -> sui_layout::IntrinsicSize {
self.0.set(self.0.get() + 1);
let offset = if axis == sui_layout::Axis::Horizontal {
1.0
} else {
2.0
};
sui_layout::IntrinsicSize::fixed(cross + offset)
}
}
let calls = Rc::new(Cell::new(0));
let mut pod = WidgetPod::new(Probe(calls.clone()));
let root = WidgetId::new(u64::MAX);
let mut clean = scoped_measure_ctx(root, MeasureScope::default());
for _ in 0..2 {
assert_eq!(
pod.intrinsic_size(&mut clean, sui_layout::Axis::Horizontal, 10.0)
.natural,
11.0
);
assert_eq!(
pod.intrinsic_size(&mut clean, sui_layout::Axis::Vertical, 10.0)
.natural,
12.0
);
}
assert_eq!(calls.get(), 2);
assert_eq!(
pod.intrinsic_size(&mut clean, sui_layout::Axis::Horizontal, 20.0)
.natural,
21.0
);
assert_eq!(calls.get(), 3);
let mut dirty = scoped_measure_ctx(
root,
MeasureScope::scoped(HashSet::from([pod.id()]), HashSet::new()),
);
pod.measure(&mut dirty, Constraints::tight(Size::new(10.0, 10.0)));
pod.intrinsic_size(&mut clean, sui_layout::Axis::Vertical, 10.0);
assert_eq!(
calls.get(),
4,
"ordinary dirty measurement must also clear intrinsic probes"
);
}
#[test]
fn intrinsic_probe_cannot_leave_a_cached_final_layout_in_the_wrong_state() {
struct StatefulMeasure(Rc<Cell<f32>>);
impl Widget for StatefulMeasure {
fn measure(&mut self, _: &mut MeasureCtx, constraints: Constraints) -> Size {
self.0.set(constraints.max.width);
constraints.clamp(Size::new(20.0, 20.0))
}
}
let committed_width = Rc::new(Cell::new(0.0));
let mut pod = WidgetPod::new(StatefulMeasure(committed_width.clone()));
let root = WidgetId::new(u64::MAX);
let final_constraints = Constraints::tight(Size::new(100.0, 20.0));
let mut initial = scoped_measure_ctx(root, MeasureScope::force_all());
pod.measure(&mut initial, final_constraints);
let mut clean =
scoped_measure_ctx(root, MeasureScope::scoped(HashSet::new(), HashSet::new()));
pod.intrinsic_size(&mut clean, sui_layout::Axis::Horizontal, 20.0);
pod.measure(&mut clean, final_constraints);
assert_eq!(
committed_width.get(),
100.0,
"a scalar cache hit did not restore the final layout state"
);
}
#[test]
fn measure_cache_skips_clean_subtrees_and_forces_changed_ones() {
let measures = Rc::new(Cell::new(0u32));
let child = WidgetPod::new(CountingChild {
measures: Rc::clone(&measures),
});
let mut parent = WidgetPod::new(PassthroughParent { child });
let parent_id = parent.id();
let outside = WidgetId::new(u64::MAX);
let constraints = Constraints::tight(sui_core::Size::new(10.0, 10.0));
let mut ctx = scoped_measure_ctx(outside, MeasureScope::force_all());
parent.measure(&mut ctx, constraints);
assert_eq!(measures.get(), 1, "initial pass must measure the child");
let mut ctx = scoped_measure_ctx(
outside,
MeasureScope::scoped(HashSet::new(), HashSet::new()),
);
parent.measure(&mut ctx, constraints);
assert_eq!(measures.get(), 1, "clean subtree must be skipped");
let mut dirty = HashSet::new();
dirty.insert(parent_id);
let mut ctx = scoped_measure_ctx(outside, MeasureScope::scoped(dirty, HashSet::new()));
parent.measure(&mut ctx, constraints);
assert_eq!(
measures.get(),
1,
"ancestor-only re-measure must not force the subtree"
);
let mut dirty = HashSet::new();
dirty.insert(parent_id);
let mut roots = HashSet::new();
roots.insert(parent_id);
let mut ctx = scoped_measure_ctx(outside, MeasureScope::scoped(dirty, roots));
parent.measure(&mut ctx, constraints);
assert_eq!(
measures.get(),
2,
"a changed widget must force its descendants to re-measure"
);
}
#[test]
fn widget_pod_merges_child_measure_arrange_paint_and_semantics() {
let mut pod = WidgetPod::new(LabelWidget);
pod.set_bounds(Rect::new(4.0, 6.0, 0.0, 0.0));
let mut measure = measure_ctx(WindowId::new(3), WidgetId::new(4));
let size = pod.measure(
&mut measure,
Constraints::tight(sui_core::Size::new(64.0, 32.0)),
);
let mut arrange = ArrangeCtx::new(WindowId::new(3), WidgetId::new(4), DpiInfo::default());
pod.arrange(&mut arrange, Rect::new(4.0, 6.0, 64.0, 32.0));
let mut paint = PaintCtx::new(
WindowId::new(3),
WidgetId::new(4),
Rect::new(0.0, 0.0, 120.0, 60.0),
None,
DpiInfo::default(),
Arc::new(TextSystem::new()),
Arc::new(FontRegistry::new()),
Arc::new(ImageRegistry::new()),
);
pod.paint(&mut paint);
let mut semantics = SemanticsCtx::new(
WindowId::new(3),
WidgetId::new(4),
WidgetId::new(4),
Rect::new(0.0, 0.0, 120.0, 60.0),
None,
);
pod.semantics(&mut semantics);
assert_eq!(size, sui_core::Size::new(64.0, 32.0));
assert_eq!(pod.bounds(), Rect::new(4.0, 6.0, 64.0, 32.0));
assert_eq!(paint.scene().commands().len(), 1);
assert!(matches!(
paint.scene().commands()[0],
SceneCommand::FillRect { .. }
));
assert_eq!(semantics.nodes().len(), 1);
}
#[test]
fn remeasured_subtree_arranges_children_outside_the_dirty_scope() {
let window_id = WindowId::new(1);
let parent_id = WidgetId::new(2);
struct ArrangedBounds(Rc<std::cell::Cell<Rect>>);
impl Widget for ArrangedBounds {
fn measure(&mut self, _: &mut MeasureCtx, constraints: Constraints) -> Size {
constraints.max
}
fn arrange(&mut self, _: &mut ArrangeCtx, bounds: Rect) {
self.0.set(bounds);
}
}
let actual = Rc::new(std::cell::Cell::new(Rect::new(0.0, 0.0, 0.0, 0.0)));
let mut pod = WidgetPod::new(BoundsWrapper::new(
ArrangedBounds(actual.clone()),
None,
Vector::ZERO,
));
let mut measure = measure_ctx(window_id, parent_id);
pod.measure(&mut measure, Constraints::tight(Size::new(100.0, 80.0)));
let mut arrange = ArrangeCtx::new(window_id, parent_id, DpiInfo::default());
pod.arrange(&mut arrange, Rect::new(0.0, 0.0, 100.0, 80.0));
pod.measure(&mut measure, Constraints::tight(Size::new(180.0, 80.0)));
let mut arrange = ArrangeCtx::new_scoped_at(
window_id,
parent_id,
DpiInfo::default(),
0.0,
Rc::new(super::ArrangeScope::scoped(
[parent_id].into_iter().collect(),
)),
);
pod.arrange(&mut arrange, Rect::new(0.0, 0.0, 180.0, 80.0));
struct BoundsVisitor(Vec<Rect>);
impl WidgetPodVisitor for BoundsVisitor {
fn visit(&mut self, child: &WidgetPod) {
self.0.push(child.bounds());
}
}
let mut visitor = BoundsVisitor(Vec::new());
pod.visit_children(&mut visitor);
assert_eq!(visitor.0, vec![Rect::new(0.0, 0.0, 180.0, 80.0)]);
assert_eq!(actual.get(), Rect::new(0.0, 0.0, 180.0, 80.0));
}
#[test]
fn single_child_wraps_measure_arrange_and_visitation() {
struct CaptureVisitor {
ids: Vec<WidgetId>,
}
impl WidgetPodVisitor for CaptureVisitor {
fn visit(&mut self, child: &WidgetPod) {
self.ids.push(child.id());
}
}
impl WidgetPodMutVisitor for CaptureVisitor {
fn visit(&mut self, child: &mut WidgetPod) {
self.ids.push(child.id());
}
}
let mut child = SingleChild::new(LabelWidget);
let mut measure = measure_ctx(WindowId::new(7), WidgetId::new(8));
let size = child.measure(
&mut measure,
Constraints::tight(sui_core::Size::new(80.0, 24.0)),
);
let mut arrange = ArrangeCtx::new(WindowId::new(7), WidgetId::new(8), DpiInfo::default());
child.arrange(&mut arrange, Rect::new(12.0, 18.0, 80.0, 24.0));
let mut visitor = CaptureVisitor { ids: Vec::new() };
child.visit_children(&mut visitor);
child.visit_children_mut(&mut visitor);
assert_eq!(size, sui_core::Size::new(80.0, 24.0));
assert_eq!(child.child().bounds(), Rect::new(12.0, 18.0, 80.0, 24.0));
assert_eq!(visitor.ids, vec![child.child().id(), child.child().id()]);
}
#[test]
fn widget_children_bulk_paint_and_semantics_delegate_to_all_children() {
let mut children = WidgetChildren::with_capacity(2);
children.push(LabelWidget);
children.push(LabelWidget);
let mut measure = measure_ctx(WindowId::new(9), WidgetId::new(10));
children.measure_child(
0,
&mut measure,
Constraints::tight(sui_core::Size::new(40.0, 18.0)),
);
children.measure_child(
1,
&mut measure,
Constraints::tight(sui_core::Size::new(60.0, 18.0)),
);
let mut arrange = ArrangeCtx::new(WindowId::new(9), WidgetId::new(10), DpiInfo::default());
children.arrange_child(0, &mut arrange, Rect::new(0.0, 0.0, 40.0, 18.0));
children.arrange_child(1, &mut arrange, Rect::new(44.0, 0.0, 60.0, 18.0));
let mut paint = PaintCtx::new(
WindowId::new(9),
WidgetId::new(10),
Rect::new(0.0, 0.0, 120.0, 40.0),
None,
DpiInfo::default(),
Arc::new(TextSystem::new()),
Arc::new(FontRegistry::new()),
Arc::new(ImageRegistry::new()),
);
children.paint(&mut paint);
let mut semantics = SemanticsCtx::new(
WindowId::new(9),
WidgetId::new(10),
WidgetId::new(10),
Rect::new(0.0, 0.0, 120.0, 40.0),
None,
);
children.semantics(&mut semantics);
assert_eq!(children.len(), 2);
assert_eq!(paint.scene().commands().len(), 2);
assert_eq!(semantics.nodes().len(), 2);
}
#[test]
fn keyed_children_preserve_pods_and_update_item_signals() {
let mut children = KeyedChildren::<u64, (u64, String)>::new();
let first = children.reconcile(
[(1, "one".to_string()), (2, "two".to_string())],
|item| item.0,
|_key, _value| LabelWidget,
);
assert_eq!(first.inserted, 2);
let first_ids = children
.iter()
.map(|(key, _, child)| (*key, child.id()))
.collect::<HashMap<_, _>>();
let second = children.reconcile(
[
(2, "two updated".to_string()),
(1, "one".to_string()),
(3, "three".to_string()),
],
|item| item.0,
|_key, _value| LabelWidget,
);
assert_eq!(second.inserted, 1);
assert_eq!(second.removed, 0);
assert_eq!(second.moved, 2);
assert_eq!(second.updated, 1);
assert_eq!(second.unchanged, 1);
let entries = children
.iter()
.map(|(key, value, child)| (*key, value.get(), child.id()))
.collect::<Vec<_>>();
assert_eq!(
entries.iter().map(|(key, _, _)| *key).collect::<Vec<_>>(),
vec![2, 1, 3]
);
assert_eq!(entries[0].1.1, "two updated");
assert_eq!(entries[0].2, first_ids[&2]);
assert_eq!(entries[1].2, first_ids[&1]);
}
#[test]
fn nested_paint_wrappers_preserve_content_and_clipped_paint_bounds() {
let inner = BoundsWrapper::new(
BoundsLeaf,
Some(Rect::new(0.0, 0.0, 60.0, 60.0)),
Vector::new(0.0, 7.0),
);
let outer = BoundsWrapper::new(
inner,
Some(Rect::new(0.0, 0.0, 100.0, 100.0)),
Vector::new(5.0, 0.0),
);
let mut root = WidgetPod::new(BoundsWrapper::new(outer, None, Vector::ZERO));
let window_id = WindowId::new(17);
let root_id = WidgetId::new(18);
let bounds = Rect::new(0.0, 0.0, 120.0, 100.0);
let mut measure = measure_ctx(window_id, root_id);
root.measure(&mut measure, Constraints::tight(bounds.size));
let mut arrange = ArrangeCtx::new(window_id, root_id, DpiInfo::default());
root.arrange(&mut arrange, bounds);
let mut paint = PaintCtx::new(
window_id,
root_id,
bounds,
None,
DpiInfo::default(),
Arc::new(TextSystem::new()),
Arc::new(FontRegistry::new()),
Arc::new(ImageRegistry::new()),
);
root.paint(&mut paint);
assert_eq!(
paint.scene().content_bounds(),
Some(Rect::new(15.0, 17.0, 80.0, 50.0))
);
assert_eq!(
paint.scene().paint_bounds(),
Some(Rect::new(15.0, 17.0, 50.0, 43.0))
);
assert_eq!(
paint.scene().paint_bounds(),
paint.scene().clone().paint_bounds()
);
}
#[test]
fn paint_ctx_emits_extended_scene_commands() {
let mut paint = PaintCtx::new(
WindowId::new(11),
WidgetId::new(12),
Rect::new(0.0, 0.0, 120.0, 60.0),
None,
DpiInfo::default(),
Arc::new(TextSystem::new()),
Arc::new(FontRegistry::new()),
Arc::new(ImageRegistry::new()),
);
let mut path = sui_core::Path::builder();
path.move_to(Point::new(4.0, 5.0))
.line_to(Point::new(24.0, 5.0))
.line_to(Point::new(14.0, 15.0))
.close();
paint.stroke(path.build(), Color::WHITE, StrokeStyle::new(2.0));
paint.draw_text(
Rect::new(8.0, 10.0, 80.0, 20.0),
"hello",
TextStyle::new(Color::BLACK),
);
paint.draw_image(
Rect::new(0.0, 0.0, 16.0, 16.0),
sui_core::ImageHandle::new(3),
);
paint.push_clip(sui_core::Path::circle(Point::new(12.0, 12.0), 8.0));
paint.push_clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0));
paint.translate(Vector::new(3.0, 4.0));
paint.pop_transform();
paint.pop_clip();
paint.pop_clip();
assert!(matches!(
paint.scene().commands()[0],
SceneCommand::StrokePath { .. }
));
assert!(matches!(
paint.scene().commands()[1],
SceneCommand::DrawShapedText(_)
));
assert!(matches!(
paint.scene().commands()[2],
SceneCommand::DrawImage { .. }
));
assert!(matches!(
paint.scene().commands()[3],
SceneCommand::PushClipPath { .. }
));
assert!(matches!(
paint.scene().commands()[4],
SceneCommand::PushClip { .. }
));
assert!(matches!(
paint.scene().commands()[5],
SceneCommand::PushTransform { .. }
));
assert!(matches!(
paint.scene().commands()[6],
SceneCommand::PopTransform
));
assert!(matches!(paint.scene().commands()[7], SceneCommand::PopClip));
assert!(matches!(paint.scene().commands()[8], SceneCommand::PopClip));
}
#[test]
fn stable_text_run_handle_ignores_color_and_includes_layout_style() {
let run = TextRun {
rect: Rect::new(8.0, 10.0, 80.0, 20.0),
text: "hello".to_string(),
style: TextStyle::new(Color::BLACK),
};
let mut recolored = run.clone();
recolored.style.color = Color::WHITE;
let mut bold = run.clone();
bold.style.weight = FontWeight::BOLD;
assert_eq!(
super::stable_text_run_handle(&run),
super::stable_text_run_handle(&recolored)
);
assert_ne!(
super::stable_text_run_handle(&run),
super::stable_text_run_handle(&bold)
);
}
#[test]
fn paint_ctx_draw_text_uses_color_override_for_paint_color() {
let text_system = Arc::new(TextSystem::new());
let mut paint = PaintCtx::new(
WindowId::new(12),
WidgetId::new(13),
Rect::new(0.0, 0.0, 120.0, 60.0),
None,
DpiInfo::default(),
Arc::clone(&text_system),
Arc::new(FontRegistry::new()),
Arc::new(ImageRegistry::new()),
);
let paint_color = Color::BLACK;
paint.draw_text(
Rect::new(8.0, 10.0, 80.0, 20.0),
"hello",
TextStyle::new(paint_color),
);
let SceneCommand::DrawShapedText(text) = &paint.scene().commands()[0] else {
panic!("draw_text should emit shaped text when layout succeeds");
};
assert_eq!(text.color_override, Some(paint_color));
let registry = text_system.text_layout_registry();
let layout = text
.resolve(registry.as_ref())
.expect("drawn shaped text should resolve from the registry");
assert_eq!(layout.style().color, Color::WHITE);
}
#[test]
fn paint_ctx_draw_persistent_text_layout_reinserts_pruned_layout() {
let text_system = Arc::new(TextSystem::new());
let layout = text_system
.shape_text_persistent(
None,
"held",
Size::new(80.0, 20.0),
TextStyle::new(Color::WHITE),
&FontRegistry::new(),
)
.unwrap();
text_system.retain_persistent_layouts(&std::collections::HashSet::new());
assert!(!text_system.text_layout_registry().contains(layout.handle()));
let mut paint = PaintCtx::new(
WindowId::new(12),
WidgetId::new(13),
Rect::new(0.0, 0.0, 120.0, 60.0),
None,
DpiInfo::default(),
Arc::clone(&text_system),
Arc::new(FontRegistry::new()),
Arc::new(ImageRegistry::new()),
);
paint.draw_persistent_text_layout(Point::ZERO, &layout);
assert!(text_system.text_layout_registry().contains(layout.handle()));
assert!(matches!(
paint.scene().commands()[0],
SceneCommand::DrawShapedText(_)
));
}
#[test]
fn text_layout_shapes_in_measure_and_paints_as_shaped_scene_output() {
let layout = measure_ctx(WindowId::new(13), WidgetId::new(14))
.layout()
.shape_text(
"hello",
sui_core::Size::new(80.0, 20.0),
TextStyle::new(Color::BLACK),
)
.unwrap();
let mut paint = PaintCtx::new(
WindowId::new(13),
WidgetId::new(14),
Rect::new(0.0, 0.0, 120.0, 60.0),
None,
DpiInfo::default(),
Arc::new(TextSystem::new()),
Arc::new(FontRegistry::new()),
Arc::new(ImageRegistry::new()),
);
let origin = Point::new(8.0, 10.0);
paint.draw_text_layout(origin, &layout);
paint.set_ime_composition_rect(layout.caret_rect(3).translate(origin.to_vector()));
assert!(matches!(
paint.scene().commands()[0],
SceneCommand::DrawShapedText(_)
));
assert!(paint.ime_composition_rect().is_some());
assert!(!layout.selection_rects(1..4).is_empty());
}
}