#[cfg(any(feature = "inspector", debug_assertions))]
use crate::Inspector;
use crate::{
Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
AsyncWindowContext, AtlasTile, AvailableSpace, Background, BlendMode, BorderStyle, Bounds,
BoxShadow, Capslock, Context, Corners, CursorStyle, Decorations, DevicePixels,
DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity,
EntityId, EventEmitter, FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs,
Hsla, InputHandler, InputPreference, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent,
Keystroke, KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent,
MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels,
PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point,
PolychromeSprite, ProgressBarState, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams,
RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeAnchor, ResizeEdge,
SMOOTH_SVG_SCALE_FACTOR, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow,
SharedString, Size, StrikethroughStyle, Style, SubscriberSet, Subscription, SystemWindowTab,
SystemWindowTabController, TabStopMap, TaffyLayoutEngine, Task, TextStyle, TextStyleRefinement,
ThermalState, TransformationMatrix, Underline, UnderlineStyle, WindowAppearance,
WindowBackgroundAppearance, WindowBounds, WindowControls, WindowDecorations, WindowOptions,
WindowParams, WindowState, WindowTextSystem, WindowVisibility, point, prelude::*, px, rems,
size, transparent_black,
};
use anyhow::{Context as _, Result, anyhow};
use collections::{FxHashMap, FxHashSet};
#[cfg(target_os = "macos")]
use core_video::pixel_buffer::CVPixelBuffer;
use derive_more::{Deref, DerefMut};
use futures::channel::oneshot;
#[cfg(feature = "input-latency-histogram")]
use hdrhistogram::Histogram;
use itertools::FoldWhile::{Continue, Done};
use itertools::Itertools;
use parking_lot::{RwLock, RwLockUpgradableReadGuard};
use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
use refineable::Refineable;
use slotmap::SlotMap;
use smallvec::SmallVec;
use std::{
any::{Any, TypeId},
borrow::Cow,
cell::{Cell, RefCell},
cmp,
fmt::{Debug, Display},
hash::{Hash, Hasher},
marker::PhantomData,
mem,
ops::{DerefMut, Range},
rc::Rc,
sync::{
Arc, Weak,
atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
},
time::{Duration, Instant},
};
use util::post_inc;
use util::{ResultExt, measure};
use uuid::Uuid;
pub(crate) mod a11y;
mod prompts;
use crate::util::{
atomic_incr_if_not_zero, ceil_to_device_pixel, floor_to_device_pixel, round_half_toward_zero,
round_half_toward_zero_f64, round_stroke_to_device_pixel, round_to_device_pixel,
};
use a11y::{A11y, ROOT_NODE_ID};
pub use prompts::*;
#[doc(hidden)]
pub const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1536.), px(864.));
#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
pub enum DispatchPhase {
#[default]
Bubble,
Capture,
}
impl DispatchPhase {
#[inline]
pub fn bubble(self) -> bool {
self == DispatchPhase::Bubble
}
#[inline]
pub fn capture(self) -> bool {
self == DispatchPhase::Capture
}
}
struct WindowInvalidatorInner {
pub dirty: bool,
pub draw_phase: DrawPhase,
pub dirty_views: FxHashSet<EntityId>,
pub update_count: usize,
}
#[derive(Clone)]
pub(crate) struct WindowInvalidator {
inner: Rc<RefCell<WindowInvalidatorInner>>,
}
impl WindowInvalidator {
pub fn new() -> Self {
WindowInvalidator {
inner: Rc::new(RefCell::new(WindowInvalidatorInner {
dirty: true,
draw_phase: DrawPhase::None,
dirty_views: FxHashSet::default(),
update_count: 0,
})),
}
}
pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
let mut inner = self.inner.borrow_mut();
inner.update_count += 1;
inner.dirty_views.insert(entity);
if inner.draw_phase == DrawPhase::None {
inner.dirty = true;
cx.push_effect(Effect::Notify { emitter: entity });
true
} else {
false
}
}
pub fn is_dirty(&self) -> bool {
self.inner.borrow().dirty
}
pub fn set_dirty(&self, dirty: bool) {
let mut inner = self.inner.borrow_mut();
inner.dirty = dirty;
if dirty {
inner.update_count += 1;
}
}
pub fn set_phase(&self, phase: DrawPhase) {
self.inner.borrow_mut().draw_phase = phase
}
pub fn update_count(&self) -> usize {
self.inner.borrow().update_count
}
pub fn take_views(&self) -> FxHashSet<EntityId> {
mem::take(&mut self.inner.borrow_mut().dirty_views)
}
pub fn replace_views(&self, views: FxHashSet<EntityId>) {
self.inner.borrow_mut().dirty_views = views;
}
pub fn not_drawing(&self) -> bool {
self.inner.borrow().draw_phase == DrawPhase::None
}
#[track_caller]
pub fn debug_assert_paint(&self) {
debug_assert!(
matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
"this method can only be called during paint"
);
}
#[track_caller]
pub fn debug_assert_prepaint(&self) {
debug_assert!(
matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
"this method can only be called during request_layout, or prepaint"
);
}
#[track_caller]
pub fn debug_assert_paint_or_prepaint(&self) {
debug_assert!(
matches!(
self.inner.borrow().draw_phase,
DrawPhase::Paint | DrawPhase::Prepaint
),
"this method can only be called during request_layout, prepaint, or paint"
);
}
}
type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
pub(crate) type AnyWindowFocusListener =
Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
pub(crate) struct WindowFocusEvent {
pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
}
impl WindowFocusEvent {
pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
!self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
}
pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
}
}
pub struct FocusOutEvent {
pub blurred: WeakFocusHandle,
}
slotmap::new_key_type! {
pub struct FocusId;
}
pub(crate) static ELEMENT_ARENA_SIZE: std::sync::atomic::AtomicUsize =
std::sync::atomic::AtomicUsize::new(1024 * 1024);
thread_local! {
pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(
Arena::new(ELEMENT_ARENA_SIZE.load(std::sync::atomic::Ordering::Relaxed))
);
}
struct ElementArenaScope;
impl ElementArenaScope {
fn enter() -> Self {
ELEMENT_ARENA.with_borrow_mut(Arena::begin_scope);
Self
}
}
impl Drop for ElementArenaScope {
fn drop(&mut self) {
ELEMENT_ARENA.with_borrow_mut(Arena::end_scope);
}
}
fn draw_in_progress() -> bool {
ELEMENT_ARENA.with(|arena| {
arena
.try_borrow()
.map(|arena| arena.has_active_scope())
.unwrap_or(true)
})
}
#[must_use]
pub struct ArenaClearNeeded;
impl ArenaClearNeeded {
pub fn clear(self) {
ELEMENT_ARENA.with_borrow_mut(|element_arena| {
element_arena.clear();
});
}
}
#[derive(Default)]
pub(crate) struct FocusMap {
pub(crate) handles: SlotMap<FocusId, FocusRef>,
pub(crate) dropped_handles: Vec<FocusId>,
}
pub(crate) struct FocusRef {
pub(crate) ref_count: AtomicUsize,
pub(crate) tab_index: isize,
pub(crate) tab_stop: bool,
}
impl FocusId {
pub fn is_focused(&self, window: &Window) -> bool {
window.focus == Some(*self)
}
pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
window
.focused(cx)
.is_some_and(|focused| self.contains(focused.id, window))
}
pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
let focused = window.focused(cx);
focused.is_some_and(|focused| focused.id.contains(*self, window))
}
pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
window
.rendered_frame
.dispatch_tree
.focus_contains(*self, other)
}
}
pub struct FocusHandle {
pub(crate) id: FocusId,
handles: Arc<RwLock<FocusMap>>,
pub tab_index: isize,
pub tab_stop: bool,
}
impl std::fmt::Debug for FocusHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("FocusHandle({:?})", self.id))
}
}
impl FocusHandle {
pub(crate) fn new(handles: &Arc<RwLock<FocusMap>>) -> Self {
let id = handles.write().handles.insert(FocusRef {
ref_count: AtomicUsize::new(1),
tab_index: 0,
tab_stop: false,
});
Self {
id,
tab_index: 0,
tab_stop: false,
handles: handles.clone(),
}
}
pub(crate) fn for_id(id: FocusId, handles: &Arc<RwLock<FocusMap>>) -> Option<Self> {
let lock = handles.read();
let focus = lock.handles.get(id)?;
if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
return None;
}
Some(Self {
id,
tab_index: focus.tab_index,
tab_stop: focus.tab_stop,
handles: handles.clone(),
})
}
pub fn tab_index(mut self, index: isize) -> Self {
self.tab_index = index;
if let Some(focus) = self.handles.write().handles.get_mut(self.id) {
focus.tab_index = index;
}
self
}
pub fn tab_stop(mut self, tab_stop: bool) -> Self {
self.tab_stop = tab_stop;
if let Some(focus) = self.handles.write().handles.get_mut(self.id) {
focus.tab_stop = tab_stop;
}
self
}
pub fn downgrade(&self) -> WeakFocusHandle {
WeakFocusHandle {
id: self.id,
handles: Arc::downgrade(&self.handles),
}
}
pub fn focus(&self, window: &mut Window) {
window.focus(self)
}
pub fn is_focused(&self, window: &Window) -> bool {
self.id.is_focused(window)
}
pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
self.id.contains_focused(window, cx)
}
pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
self.id.within_focused(window, cx)
}
pub fn contains(&self, other: &Self, window: &Window) -> bool {
self.id.contains(other.id, window)
}
pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
if let Some(node_id) = window
.rendered_frame
.dispatch_tree
.focusable_node_id(self.id)
{
window.dispatch_action_on_node(node_id, action, cx)
}
}
}
impl Clone for FocusHandle {
fn clone(&self) -> Self {
Self::for_id(self.id, &self.handles).unwrap()
}
}
impl PartialEq for FocusHandle {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for FocusHandle {}
impl Drop for FocusHandle {
fn drop(&mut self) {
let handles = self.handles.upgradable_read();
let focus = handles.handles.get(self.id).expect("focus handle missing");
let previous_count = focus.ref_count.fetch_sub(1, SeqCst);
assert_ne!(previous_count, 0, "over-released focus handle");
if previous_count == 1 {
RwLockUpgradableReadGuard::upgrade(handles)
.dropped_handles
.push(self.id);
}
}
}
#[derive(Clone, Debug)]
pub struct WeakFocusHandle {
pub(crate) id: FocusId,
pub(crate) handles: Weak<RwLock<FocusMap>>,
}
impl WeakFocusHandle {
pub fn upgrade(&self) -> Option<FocusHandle> {
let handles = self.handles.upgrade()?;
FocusHandle::for_id(self.id, &handles)
}
}
impl PartialEq for WeakFocusHandle {
fn eq(&self, other: &WeakFocusHandle) -> bool {
self.id == other.id
}
}
impl Eq for WeakFocusHandle {}
impl PartialEq<FocusHandle> for WeakFocusHandle {
fn eq(&self, other: &FocusHandle) -> bool {
self.id == other.id
}
}
impl PartialEq<WeakFocusHandle> for FocusHandle {
fn eq(&self, other: &WeakFocusHandle) -> bool {
self.id == other.id
}
}
pub trait Focusable: 'static {
fn focus_handle(&self, cx: &App) -> FocusHandle;
}
impl<V: Focusable> Focusable for Entity<V> {
fn focus_handle(&self, cx: &App) -> FocusHandle {
self.read(cx).focus_handle(cx)
}
}
pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
pub struct DismissEvent;
type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
pub(crate) type AnyMouseListener =
Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
#[derive(Clone)]
pub(crate) struct CursorStyleRequest {
pub(crate) hitbox_id: Option<HitboxId>,
pub(crate) style: CursorStyle,
}
#[derive(Default, Eq, PartialEq)]
pub(crate) struct HitTest {
pub(crate) ids: SmallVec<[HitboxId; 8]>,
pub(crate) hover_hitbox_count: usize,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WindowControlArea {
Drag,
Close,
Max,
Min,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct HitboxId(u64);
impl HitboxId {
pub fn is_hovered(self, window: &Window) -> bool {
if window.captured_hitbox == Some(self) {
return true;
}
if window.last_input_was_keyboard() {
return false;
}
self.hit_test(window)
}
pub(crate) fn is_hovered_ignoring_last_input(self, window: &Window) -> bool {
if window.captured_hitbox == Some(self) {
return true;
}
self.hit_test(window)
}
fn hit_test(self, window: &Window) -> bool {
let hit_test = &window.mouse_hit_test;
for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
if self == *id {
return true;
}
}
false
}
pub fn should_handle_scroll(self, window: &Window) -> bool {
window.mouse_hit_test.ids.contains(&self)
}
fn next(mut self) -> HitboxId {
HitboxId(self.0.wrapping_add(1))
}
}
#[derive(Clone, Debug, Deref)]
pub struct Hitbox {
pub id: HitboxId,
#[deref]
pub bounds: Bounds<Pixels>,
pub content_mask: ContentMask<Pixels>,
pub behavior: HitboxBehavior,
}
impl Hitbox {
pub fn is_hovered(&self, window: &Window) -> bool {
self.id.is_hovered(window)
}
pub fn is_hovered_at(&self, position: Point<Pixels>, window: &Window) -> bool {
let hit_test = window.rendered_frame.hit_test(position);
hit_test
.ids
.iter()
.take(hit_test.hover_hitbox_count)
.any(|id| self.id == *id)
}
pub fn should_handle_scroll(&self, window: &Window) -> bool {
self.id.should_handle_scroll(window)
}
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum HitboxBehavior {
#[default]
Normal,
BlockMouse,
BlockMouseExceptScroll,
}
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct TooltipId(usize);
impl TooltipId {
pub fn is_hovered(&self, window: &Window) -> bool {
window
.tooltip_bounds
.as_ref()
.is_some_and(|tooltip_bounds| {
tooltip_bounds.id == *self
&& tooltip_bounds.bounds.contains(&window.mouse_position())
})
}
}
pub(crate) struct TooltipBounds {
id: TooltipId,
bounds: Bounds<Pixels>,
}
#[derive(Clone)]
pub(crate) struct TooltipRequest {
id: TooltipId,
tooltip: AnyTooltip,
}
pub(crate) struct DeferredDraw {
current_view: EntityId,
priority: usize,
parent_node: DispatchNodeId,
element_id_stack: SmallVec<[ElementId; 32]>,
text_style_stack: SmallVec<[TextStyleRefinement; 4]>,
element: Option<AnyElement>,
absolute_offset: Point<Pixels>,
prepaint_range: Range<PrepaintStateIndex>,
paint_range: Range<PaintIndex>,
}
pub(crate) struct Frame {
pub(crate) focus: Option<FocusId>,
pub(crate) window_active: bool,
pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
accessed_element_states: Vec<(GlobalElementId, TypeId)>,
pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
pub(crate) dispatch_tree: DispatchTree,
pub(crate) scene: Scene,
pub(crate) hitboxes: Vec<Hitbox>,
pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
pub(crate) deferred_draws: Vec<DeferredDraw>,
pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
pub(crate) cursor_styles: Vec<CursorStyleRequest>,
#[cfg(any(test, feature = "test-support"))]
pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
#[cfg(any(test, feature = "test-support"))]
debug_bounds_records: Vec<(String, Bounds<Pixels>)>,
#[cfg(any(feature = "inspector", debug_assertions))]
pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
#[cfg(any(feature = "inspector", debug_assertions))]
pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
pub(crate) tab_stops: TabStopMap,
}
#[derive(Clone, Default)]
pub(crate) struct PrepaintStateIndex {
hitboxes_index: usize,
tooltips_index: usize,
deferred_draws_index: usize,
dispatch_tree_index: usize,
accessed_element_states_index: usize,
line_layout_index: LineLayoutIndex,
}
#[derive(Clone, Default)]
pub(crate) struct PaintIndex {
scene_index: usize,
#[cfg(any(test, feature = "test-support"))]
debug_bounds_index: usize,
mouse_listeners_index: usize,
input_handlers_index: usize,
cursor_styles_index: usize,
accessed_element_states_index: usize,
tab_handle_index: usize,
line_layout_index: LineLayoutIndex,
}
impl Frame {
#[cfg(any(test, feature = "test-support"))]
pub(crate) fn record_debug_bounds(&mut self, selector: String, bounds: Bounds<Pixels>) {
self.debug_bounds.insert(selector.clone(), bounds);
self.debug_bounds_records.push((selector, bounds));
}
pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
Frame {
focus: None,
window_active: false,
element_states: FxHashMap::default(),
accessed_element_states: Vec::new(),
mouse_listeners: Vec::new(),
dispatch_tree,
scene: Scene::default(),
hitboxes: Vec::new(),
window_control_hitboxes: Vec::new(),
deferred_draws: Vec::new(),
input_handlers: Vec::new(),
tooltip_requests: Vec::new(),
cursor_styles: Vec::new(),
#[cfg(any(test, feature = "test-support"))]
debug_bounds: FxHashMap::default(),
#[cfg(any(test, feature = "test-support"))]
debug_bounds_records: Vec::new(),
#[cfg(any(feature = "inspector", debug_assertions))]
next_inspector_instance_ids: FxHashMap::default(),
#[cfg(any(feature = "inspector", debug_assertions))]
inspector_hitboxes: FxHashMap::default(),
tab_stops: TabStopMap::default(),
}
}
pub(crate) fn clear(&mut self) {
self.element_states.clear();
self.accessed_element_states.clear();
self.mouse_listeners.clear();
self.dispatch_tree.clear();
self.scene.clear();
self.input_handlers.clear();
self.tooltip_requests.clear();
self.cursor_styles.clear();
self.hitboxes.clear();
self.window_control_hitboxes.clear();
self.deferred_draws.clear();
self.tab_stops.clear();
self.focus = None;
#[cfg(any(test, feature = "test-support"))]
{
self.debug_bounds.clear();
self.debug_bounds_records.clear();
}
#[cfg(any(feature = "inspector", debug_assertions))]
{
self.next_inspector_instance_ids.clear();
self.inspector_hitboxes.clear();
}
}
pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
self.cursor_styles
.iter()
.rev()
.fold_while(None, |style, request| match request.hitbox_id {
None => Done(Some(request.style)),
Some(hitbox_id) => Continue(style.or_else(|| {
hitbox_id
.is_hovered_ignoring_last_input(window)
.then_some(request.style)
})),
})
.into_inner()
}
pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
let mut set_hover_hitbox_count = false;
let mut hit_test = HitTest::default();
for hitbox in self.hitboxes.iter().rev() {
let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
if bounds.contains(&position) {
hit_test.ids.push(hitbox.id);
if !set_hover_hitbox_count
&& hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
{
hit_test.hover_hitbox_count = hit_test.ids.len();
set_hover_hitbox_count = true;
}
if hitbox.behavior == HitboxBehavior::BlockMouse {
break;
}
}
}
if !set_hover_hitbox_count {
hit_test.hover_hitbox_count = hit_test.ids.len();
}
hit_test
}
pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
self.focus
.map(|focus_id| self.dispatch_tree.focus_path(focus_id))
.unwrap_or_default()
}
pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
for element_state_key in &self.accessed_element_states {
if let Some((element_state_key, element_state)) =
prev_frame.element_states.remove_entry(element_state_key)
{
self.element_states.insert(element_state_key, element_state);
}
}
self.scene.finish();
}
}
#[derive(Clone, Debug)]
pub(crate) struct InputRateTracker {
timestamps: Vec<Instant>,
window: Duration,
inputs_per_second: u32,
sustain_until: Instant,
sustain_duration: Duration,
}
impl Default for InputRateTracker {
fn default() -> Self {
Self {
timestamps: Vec::new(),
window: Duration::from_millis(100),
inputs_per_second: 60,
sustain_until: Instant::now(),
sustain_duration: Duration::from_secs(1),
}
}
}
impl InputRateTracker {
pub fn record_input(&mut self) {
let now = Instant::now();
self.timestamps.push(now);
self.timestamps
.retain(|&t| now.duration_since(t) <= self.window);
let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
if self.timestamps.len() as u128 >= min_events {
self.sustain_until = now + self.sustain_duration;
}
}
pub fn is_high_rate(&self) -> bool {
Instant::now() < self.sustain_until
}
}
const THIRTY_FPS_INTERVAL: Duration = Duration::from_micros(33333);
const SIXTY_FPS_INTERVAL: Duration = Duration::from_micros(16667);
const FRAME_INTERVAL_TOLERANCE: Duration = Duration::from_millis(1);
#[derive(Default)]
struct FramePacer {
last_frame: Option<Instant>,
}
impl FramePacer {
fn should_defer(&mut self, now: Instant, minimum_interval: Option<Duration>) -> bool {
if let Some(interval) = minimum_interval
&& let Some(last_frame) = self.last_frame
{
let deadline = last_frame + interval;
if now + FRAME_INTERVAL_TOLERANCE < deadline {
return true;
}
self.last_frame = Some(if now.saturating_duration_since(deadline) <= interval / 4 {
deadline
} else {
now
});
} else {
self.last_frame = Some(now);
}
false
}
}
fn minimum_frame_interval(
should_throttle: bool,
inactive_without_high_rate_input: bool,
inactive_frame_interval: Option<Duration>,
thermal_state: ThermalState,
power_mode: crate::PowerMode,
) -> Option<Duration> {
if !should_throttle {
return None;
}
[
inactive_frame_interval.filter(|_| inactive_without_high_rate_input),
(power_mode == crate::PowerMode::LowPower).then_some(THIRTY_FPS_INTERVAL),
matches!(
thermal_state,
ThermalState::Critical | ThermalState::Serious
)
.then_some(SIXTY_FPS_INTERVAL),
]
.into_iter()
.flatten()
.max()
}
#[cfg(feature = "input-latency-histogram")]
pub struct InputLatencySnapshot {
pub latency_histogram: Histogram<u64>,
pub events_per_frame_histogram: Histogram<u64>,
pub mid_draw_events_dropped: u64,
}
#[cfg(feature = "input-latency-histogram")]
struct InputLatencyTracker {
first_input_at: Option<Instant>,
pending_input_count: u64,
latency_histogram: Histogram<u64>,
events_per_frame_histogram: Histogram<u64>,
mid_draw_events_dropped: u64,
}
#[cfg(feature = "input-latency-histogram")]
impl InputLatencyTracker {
fn new() -> Result<Self> {
Ok(Self {
first_input_at: None,
pending_input_count: 0,
latency_histogram: Histogram::new(3)
.map_err(|error| anyhow!("failed to create input latency histogram: {error}"))?,
events_per_frame_histogram: Histogram::new(3)
.map_err(|error| anyhow!("failed to create events per frame histogram: {error}"))?,
mid_draw_events_dropped: 0,
})
}
fn record_input(&mut self, dispatch_time: Instant) {
self.first_input_at.get_or_insert(dispatch_time);
self.pending_input_count += 1;
}
fn record_mid_draw_input(&mut self) {
self.mid_draw_events_dropped += 1;
}
fn record_frame_presented(&mut self) {
if let Some(first_input_at) = self.first_input_at.take() {
self.latency_histogram
.record(first_input_at.elapsed().as_nanos() as u64)
.ok();
}
if self.pending_input_count > 0 {
self.events_per_frame_histogram
.record(self.pending_input_count)
.ok();
self.pending_input_count = 0;
}
}
fn snapshot(&self) -> InputLatencySnapshot {
InputLatencySnapshot {
latency_histogram: self.latency_histogram.clone(),
events_per_frame_histogram: self.events_per_frame_histogram.clone(),
mid_draw_events_dropped: self.mid_draw_events_dropped,
}
}
}
pub struct Window {
pub(crate) handle: AnyWindowHandle,
pub(crate) invalidator: WindowInvalidator,
pub(crate) removed: bool,
pub(crate) platform_window: Box<dyn PlatformWindow>,
pub(crate) a11y: A11y,
display_id: Option<DisplayId>,
sprite_atlas: Arc<dyn PlatformAtlas>,
text_system: Arc<WindowTextSystem>,
rem_size: Pixels,
rem_size_override_stack: SmallVec<[Pixels; 8]>,
pub(crate) viewport_size: Size<Pixels>,
layout_engine: Option<TaffyLayoutEngine>,
pub(crate) root: Option<AnyView>,
pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
pub(crate) text_style_stack: SmallVec<[TextStyleRefinement; 4]>,
pub(crate) rendered_entity_stack: SmallVec<[EntityId; 16]>,
pub(crate) element_offset_stack: SmallVec<[Point<Pixels>; 16]>,
pub(crate) element_opacity: f32,
pub(crate) content_mask_stack: SmallVec<[ContentMask<Pixels>; 16]>,
pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
pub(crate) image_cache_stack: SmallVec<[AnyImageCache; 4]>,
pub(crate) rendered_frame: Frame,
pub(crate) next_frame: Frame,
next_hitbox_id: HitboxId,
pub(crate) next_tooltip_id: TooltipId,
pub(crate) tooltip_bounds: Option<TooltipBounds>,
pub(crate) next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
pub(crate) dirty_views: FxHashSet<EntityId>,
focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>,
focus_lost_path: SmallVec<[FocusId; 8]>,
default_prevented: bool,
mouse_position: Point<Pixels>,
mouse_hit_test: HitTest,
modifiers: Modifiers,
capslock: Capslock,
scale_factor: f32,
pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>,
appearance: WindowAppearance,
pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>,
active: Rc<Cell<bool>>,
visibility: WindowVisibility,
pub(crate) visibility_observers:
SubscriberSet<(), Box<dyn FnMut(WindowVisibility, &mut Window, &mut App) -> bool>>,
hovered: Rc<Cell<bool>>,
pub(crate) needs_present: Rc<Cell<bool>>,
pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
#[cfg(feature = "input-latency-histogram")]
input_latency_tracker: InputLatencyTracker,
pub(crate) last_input_was_keyboard: Cell<bool>,
pub(crate) refreshing: bool,
pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
pub(crate) focus: Option<FocusId>,
focus_enabled: bool,
pending_input: Option<PendingInput>,
pending_modifier: ModifierState,
pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>,
prompt: Option<RenderablePromptHandle>,
pub(crate) client_inset: Option<Pixels>,
captured_hitbox: Option<HitboxId>,
#[cfg(any(feature = "inspector", debug_assertions))]
inspector: Option<Entity<Inspector>>,
}
#[derive(Clone, Debug, Default)]
struct ModifierState {
modifiers: Modifiers,
saw_other_input: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum DrawPhase {
None,
Prepaint,
Paint,
Focus,
}
pub(crate) const PENDING_INPUT_TIMEOUT: Duration = Duration::from_secs(1);
pub struct PendingInputStatus<'a> {
keystrokes: &'a [Keystroke],
timeout: Option<PendingInputTimeoutStatus>,
}
impl<'a> PendingInputStatus<'a> {
pub fn keystrokes(&self) -> &'a [Keystroke] {
self.keystrokes
}
pub fn timeout(&self) -> Option<PendingInputTimeoutStatus> {
self.timeout
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PendingInputTimeoutStatus {
duration: Duration,
remaining: Duration,
started_at: Option<Instant>,
paused: bool,
}
impl PendingInputTimeoutStatus {
pub fn duration(&self) -> Duration {
self.duration
}
pub fn remaining(&self, cx: &App) -> Duration {
self.started_at
.map(|started_at| {
self.remaining
.saturating_sub(cx.background_executor().now() - started_at)
})
.unwrap_or(self.remaining)
}
pub fn is_paused(&self) -> bool {
self.paused
}
}
#[derive(Debug)]
struct PendingInputTimeout {
duration: Duration,
remaining: Duration,
state: PendingInputTimeoutState,
}
#[derive(Debug)]
enum PendingInputTimeoutState {
Running { started_at: Instant, task: Task<()> },
Paused { pause: PendingInputTimeoutPause },
}
struct PendingInputTimeoutPause {
owner_id: EntityId,
_release_subscription: Subscription,
}
impl std::fmt::Debug for PendingInputTimeoutPause {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PendingInputTimeoutPause")
.field("owner_id", &self.owner_id)
.finish_non_exhaustive()
}
}
impl PendingInputTimeout {
fn is_paused(&self) -> bool {
matches!(&self.state, PendingInputTimeoutState::Paused { .. })
}
fn pause(&mut self, pause: PendingInputTimeoutPause, now: Instant) -> bool {
match mem::replace(&mut self.state, PendingInputTimeoutState::Paused { pause }) {
PendingInputTimeoutState::Running { started_at, task } => {
self.remaining = self.remaining.saturating_sub(now - started_at);
drop(task);
true
}
previous_state @ PendingInputTimeoutState::Paused { .. } => {
self.state = previous_state;
false
}
}
}
fn pause_owner_id(&self) -> Option<EntityId> {
match &self.state {
PendingInputTimeoutState::Running { .. } => None,
PendingInputTimeoutState::Paused { pause } => Some(pause.owner_id),
}
}
fn resume(&mut self, owner_id: EntityId, started_at: Instant, task: Task<()>) -> bool {
match mem::replace(
&mut self.state,
PendingInputTimeoutState::Running { started_at, task },
) {
PendingInputTimeoutState::Paused { pause } if pause.owner_id == owner_id => true,
previous_state => {
self.state = previous_state;
false
}
}
}
fn reset_duration(&mut self, duration: Duration) {
self.duration = duration;
self.remaining = duration;
}
fn status(&self) -> PendingInputTimeoutStatus {
let (started_at, paused) = match &self.state {
PendingInputTimeoutState::Running { started_at, .. } => (Some(*started_at), false),
PendingInputTimeoutState::Paused { .. } => (None, true),
};
PendingInputTimeoutStatus {
duration: self.duration,
remaining: self.remaining,
started_at,
paused,
}
}
}
#[derive(Default, Debug)]
struct PendingInput {
keystrokes: SmallVec<[Keystroke; 1]>,
focus: Option<FocusId>,
timeout: Option<PendingInputTimeout>,
}
pub(crate) struct ElementStateBox {
pub(crate) inner: Box<dyn Any>,
#[cfg(debug_assertions)]
pub(crate) type_name: &'static str,
}
fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> Bounds<Pixels> {
const DEFAULT_WINDOW_OFFSET: Point<Pixels> = point(px(0.), px(35.));
cx.active_window()
.and_then(|w| w.update(cx, |_, window, _| window.bounds()).ok())
.map(|mut bounds| {
bounds.origin += DEFAULT_WINDOW_OFFSET;
bounds
})
.unwrap_or_else(|| {
let display = display_id
.map(|id| cx.find_display(id))
.unwrap_or_else(|| cx.primary_display());
display
.map(|display| display.default_bounds())
.unwrap_or_else(|| Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE))
})
}
fn border_only_quad_strips(
outer_bounds: Bounds<ScaledPixels>,
widths: Edges<ScaledPixels>,
radii: Corners<ScaledPixels>,
) -> Option<[Bounds<ScaledPixels>; 4]> {
let antialias_slack = point(ScaledPixels(1.0), ScaledPixels(1.0));
let top_left_inset = point(
widths.left,
widths.top.max(radii.top_left).max(radii.top_right),
) + antialias_slack;
let bottom_right_inset = point(
widths.right,
widths.bottom.max(radii.bottom_left).max(radii.bottom_right),
) + antialias_slack;
let inner_bounds = Bounds::from_corners(
outer_bounds.origin + top_left_inset,
outer_bounds.bottom_right() - bottom_right_inset,
);
if inner_bounds.is_empty() {
return None;
}
Some([
Bounds::from_corners(
outer_bounds.origin,
point(outer_bounds.right(), inner_bounds.top()),
),
Bounds::from_corners(
point(outer_bounds.left(), inner_bounds.bottom()),
outer_bounds.bottom_right(),
),
Bounds::from_corners(
point(outer_bounds.left(), inner_bounds.top()),
inner_bounds.bottom_left(),
),
Bounds::from_corners(
inner_bounds.top_right(),
point(outer_bounds.right(), inner_bounds.bottom()),
),
])
}
impl Window {
pub(crate) fn new(
handle: AnyWindowHandle,
options: WindowOptions,
cx: &mut App,
) -> Result<Self> {
let WindowOptions {
window_bounds,
titlebar,
focus,
show,
kind,
is_movable,
app_owns_titlebar_drag,
inactive_frame_interval,
is_resizable,
is_minimizable,
display_id,
window_background,
app_id,
window_min_size,
window_decorations,
#[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
tabbing_identifier,
mouse_passthrough,
icon,
} = options;
let bounds = window_bounds
.map(|bounds| bounds.get_bounds())
.unwrap_or_else(|| default_bounds(display_id, cx));
let mut platform_window = cx.platform.open_window(
handle,
WindowParams {
bounds,
titlebar,
kind,
is_movable,
app_owns_titlebar_drag,
is_resizable,
is_minimizable,
focus,
app_id: app_id.clone(),
show,
display_id,
window_min_size,
#[cfg(target_os = "macos")]
tabbing_identifier,
mouse_passthrough,
icon,
},
)?;
let tab_bar_visible = platform_window.tab_bar_visible();
SystemWindowTabController::init_visible(cx, tab_bar_visible);
if let Some(tabs) = platform_window.tabbed_windows() {
SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
}
let display_id = platform_window.display().map(|display| display.id());
let sprite_atlas = platform_window.sprite_atlas();
let mouse_position = platform_window.mouse_position();
let modifiers = platform_window.modifiers();
let capslock = platform_window.capslock();
let content_size = platform_window.content_size();
let scale_factor = platform_window.scale_factor();
let appearance = platform_window.appearance();
let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
let invalidator = WindowInvalidator::new();
let active = Rc::new(Cell::new(platform_window.is_active()));
let visibility = platform_window.visibility();
let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
let needs_present = Rc::new(Cell::new(false));
let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
platform_window
.request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
platform_window.set_background_appearance(window_background);
if let Some(ref window_open_state) = window_bounds {
match window_open_state {
WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
WindowBounds::Maximized(_) => platform_window.zoom(),
WindowBounds::Windowed(_) => {}
}
}
let accessibility_force_disabled =
cx.accessibility_force_disabled || !cfg!(feature = "accessibility");
let a11y_active_flag = Arc::new(AtomicBool::new(false));
#[cfg(not(target_family = "wasm"))]
if !accessibility_force_disabled {
let initial_tree = accesskit::TreeUpdate {
nodes: vec![(ROOT_NODE_ID, accesskit::Node::new(accesskit::Role::Window))],
tree: Some(accesskit::TreeInfo::new(ROOT_NODE_ID)),
tree_id: accesskit::TreeId::ROOT,
focus: ROOT_NODE_ID,
};
let (activation_sender, activation_receiver) = async_channel::unbounded::<()>();
let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>();
let (action_sender, action_receiver) =
async_channel::unbounded::<accesskit::ActionRequest>();
platform_window.a11y_init(crate::A11yCallbacks {
activation: {
let active_flag = a11y_active_flag.clone();
Box::new(move || {
log::info!("Accessibility activated");
active_flag.store(true, SeqCst);
activation_sender.send_blocking(()).log_err();
Some(initial_tree.clone())
})
},
action: Box::new(move |request| {
action_sender.send_blocking(request).log_err();
}),
deactivation: {
let active_flag = a11y_active_flag.clone();
Box::new(move || {
log::info!("Accessibility deactivated");
active_flag.store(false, SeqCst);
deactivation_sender.send_blocking(()).log_err();
})
},
});
let mut async_cx = cx.to_async();
cx.foreground_executor()
.spawn(async move {
while activation_receiver.recv().await.is_ok() {
handle
.update(&mut async_cx, |_, window, _| window.refresh())
.log_err();
}
})
.detach();
let mut async_cx = cx.to_async();
cx.foreground_executor()
.spawn(async move {
while deactivation_receiver.recv().await.is_ok() {
handle
.update(&mut async_cx, |_, window, _| window.refresh())
.log_err();
}
})
.detach();
let mut async_cx = cx.to_async();
cx.foreground_executor()
.spawn(async move {
while let Ok(request) = action_receiver.recv().await {
handle
.update(&mut async_cx, |_, window, cx| {
window.handle_a11y_action(request, cx);
})
.log_err();
}
})
.detach();
}
platform_window.on_close(Box::new({
let window_id = handle.window_id();
let cx = cx.to_async();
move || {
cx.spawn(async move |cx| {
cx.update(|cx| {
if cx.windows.contains_key(window_id) {
handle
.update(cx, |_, window, _| window.remove_window())
.log_err();
}
SystemWindowTabController::remove_tab(cx, window_id);
})
.log_err();
})
.detach();
}
}));
platform_window.on_request_frame(Box::new({
let mut cx = cx.to_async();
let invalidator = invalidator.clone();
let active = active.clone();
let needs_present = needs_present.clone();
let next_frame_callbacks = next_frame_callbacks.clone();
let input_rate_tracker = input_rate_tracker.clone();
let mut deferred_force_render = false;
let mut frame_pacer = FramePacer::default();
move |request_frame_options| {
if draw_in_progress() {
log::debug!("deferring re-entrant window draw request");
deferred_force_render |= request_frame_options.force_render;
return;
}
let force_render =
mem::take(&mut deferred_force_render) || request_frame_options.force_render;
let power_state = handle
.update(&mut cx, |_, _, cx| (cx.thermal_state(), cx.power_mode()))
.log_err();
let high_rate_input = input_rate_tracker.borrow().is_high_rate();
let has_next_frame_callbacks = !next_frame_callbacks.borrow().is_empty();
let has_frame_demand = invalidator.is_dirty()
|| force_render
|| has_next_frame_callbacks
|| request_frame_options.require_presentation
|| needs_present.get()
|| high_rate_input;
let should_throttle = !request_frame_options.require_presentation;
let inactive_without_high_rate_input =
should_throttle && !active.get() && !high_rate_input;
let (thermal_state, power_mode) =
power_state.unwrap_or((ThermalState::Nominal, crate::PowerMode::Unknown));
let min_frame_interval = minimum_frame_interval(
should_throttle,
inactive_without_high_rate_input,
inactive_frame_interval,
thermal_state,
power_mode,
);
let now = Instant::now();
if has_frame_demand && frame_pacer.should_defer(now, min_frame_interval) {
deferred_force_render |= force_render;
handle
.update(&mut cx, |_, window, _| {
window.platform_window.schedule_frame();
})
.log_err();
return;
}
let pending_next_frame_callbacks = next_frame_callbacks.take();
if !pending_next_frame_callbacks.is_empty() {
handle
.update(&mut cx, |_, window, cx| {
for callback in pending_next_frame_callbacks {
callback(window, cx);
}
})
.log_err();
}
let needs_present = request_frame_options.require_presentation
|| needs_present.get()
|| high_rate_input;
if invalidator.is_dirty() || force_render {
measure("frame duration", || {
handle
.update(&mut cx, |_, window, cx| {
if force_render {
window.refresh();
}
let arena_clear_needed = window.draw(cx);
window.present();
arena_clear_needed.clear();
})
.log_err();
})
} else if needs_present {
handle
.update(&mut cx, |_, window, _| window.present())
.log_err();
}
handle
.update(&mut cx, |_, window, _| {
if window.invalidator.is_dirty()
|| !window.next_frame_callbacks.borrow().is_empty()
{
window.platform_window.schedule_frame();
}
})
.log_err();
}
}));
platform_window.on_resize(Box::new({
let mut cx = cx.to_async();
let foreground_executor = cx.foreground_executor().clone();
move |_, _| {
if handle
.update(&mut cx, |_, window, cx| window.bounds_changed(cx))
.is_err()
{
let mut cx = cx.clone();
foreground_executor
.spawn(async move {
handle
.update(&mut cx, |_, window, cx| window.bounds_changed(cx))
.log_err();
})
.detach();
}
}
}));
platform_window.on_moved(Box::new({
let mut cx = cx.to_async();
let foreground_executor = cx.foreground_executor().clone();
move || {
if handle
.update(&mut cx, |_, window, cx| window.bounds_changed(cx))
.is_err()
{
let mut cx = cx.clone();
foreground_executor
.spawn(async move {
handle
.update(&mut cx, |_, window, cx| window.bounds_changed(cx))
.log_err();
})
.detach();
}
}
}));
platform_window.on_appearance_changed(Box::new({
let cx = cx.to_async();
let foreground_executor = cx.foreground_executor().clone();
move || {
let mut cx = cx.clone();
foreground_executor
.spawn(async move {
handle
.update(&mut cx, |_, window, cx| window.appearance_changed(cx))
.log_err();
})
.detach();
}
}));
platform_window.on_active_status_change(Box::new({
let mut cx = cx.to_async();
move |active| {
handle
.update(&mut cx, |_, window, cx| {
if !active {
window.platform_window.set_cursor_style(CursorStyle::Arrow);
cx.platform.set_cursor_style(CursorStyle::Arrow);
}
window.active.set(active);
window.modifiers = window.platform_window.modifiers();
window.capslock = window.platform_window.capslock();
window
.activation_observers
.clone()
.retain(&(), |callback| callback(window, cx));
window.bounds_changed(cx);
window.refresh();
SystemWindowTabController::update_last_active(cx, window.handle.id);
})
.log_err();
}
}));
platform_window.on_visibility_change(Box::new({
let mut cx = cx.to_async();
move |visibility| {
handle
.update(&mut cx, |_, window, cx| {
if window.visibility == visibility {
return;
}
window.visibility = visibility;
window
.visibility_observers
.clone()
.retain(&(), |callback| callback(visibility, window, cx));
})
.log_err();
}
}));
platform_window.on_hover_status_change(Box::new({
let mut cx = cx.to_async();
move |active| {
handle
.update(&mut cx, |_, window, _| {
window.hovered.set(active);
window.refresh();
})
.log_err();
}
}));
platform_window.on_input({
let mut cx = cx.to_async();
Box::new(move |event| {
handle
.update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
.log_err()
.unwrap_or(DispatchEventResult::default())
})
});
platform_window.on_hit_test_window_control({
let mut cx = cx.to_async();
Box::new(move || {
handle
.update(&mut cx, |_, window, _cx| {
for (area, hitbox) in &window.rendered_frame.window_control_hitboxes {
if window.mouse_hit_test.ids.contains(&hitbox.id) {
return Some(*area);
}
}
None
})
.log_err()
.unwrap_or(None)
})
});
platform_window.on_move_tab_to_new_window({
let mut cx = cx.to_async();
Box::new(move || {
handle
.update(&mut cx, |_, _window, cx| {
SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
})
.log_err();
})
});
platform_window.on_merge_all_windows({
let mut cx = cx.to_async();
Box::new(move || {
handle
.update(&mut cx, |_, _window, cx| {
SystemWindowTabController::merge_all_windows(cx, handle.window_id());
})
.log_err();
})
});
platform_window.on_select_next_tab({
let mut cx = cx.to_async();
Box::new(move || {
handle
.update(&mut cx, |_, _window, cx| {
SystemWindowTabController::select_next_tab(cx, handle.window_id());
})
.log_err();
})
});
platform_window.on_select_previous_tab({
let mut cx = cx.to_async();
Box::new(move || {
handle
.update(&mut cx, |_, _window, cx| {
SystemWindowTabController::select_previous_tab(cx, handle.window_id())
})
.log_err();
})
});
platform_window.on_toggle_tab_bar({
let mut cx = cx.to_async();
Box::new(move || {
handle
.update(&mut cx, |_, window, cx| {
let tab_bar_visible = window.platform_window.tab_bar_visible();
SystemWindowTabController::set_visible(cx, tab_bar_visible);
})
.log_err();
})
});
if let Some(app_id) = app_id {
platform_window.set_app_id(&app_id);
}
if show {
platform_window.map_window()?;
}
Ok(Window {
handle,
invalidator,
removed: false,
platform_window,
a11y: A11y::new(a11y_active_flag, accessibility_force_disabled),
display_id,
sprite_atlas,
text_system,
rem_size: px(16.),
rem_size_override_stack: SmallVec::new(),
viewport_size: content_size,
layout_engine: Some(TaffyLayoutEngine::new()),
root: None,
element_id_stack: SmallVec::default(),
text_style_stack: SmallVec::new(),
rendered_entity_stack: SmallVec::new(),
element_offset_stack: SmallVec::new(),
content_mask_stack: SmallVec::new(),
element_opacity: 1.0,
requested_autoscroll: None,
rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
next_frame_callbacks,
next_hitbox_id: HitboxId(0),
next_tooltip_id: TooltipId::default(),
tooltip_bounds: None,
dirty_views: FxHashSet::default(),
focus_listeners: SubscriberSet::new(),
focus_lost_listeners: SubscriberSet::new(),
focus_lost_path: SmallVec::new(),
default_prevented: true,
mouse_position,
mouse_hit_test: HitTest::default(),
modifiers,
capslock,
scale_factor,
bounds_observers: SubscriberSet::new(),
appearance,
appearance_observers: SubscriberSet::new(),
active,
visibility,
visibility_observers: SubscriberSet::new(),
hovered,
needs_present,
input_rate_tracker,
#[cfg(feature = "input-latency-histogram")]
input_latency_tracker: InputLatencyTracker::new()?,
last_input_was_keyboard: Cell::new(false),
refreshing: false,
activation_observers: SubscriberSet::new(),
focus: None,
focus_enabled: true,
pending_input: None,
pending_modifier: ModifierState::default(),
pending_input_observers: SubscriberSet::new(),
prompt: None,
client_inset: None,
image_cache_stack: SmallVec::new(),
captured_hitbox: None,
#[cfg(any(feature = "inspector", debug_assertions))]
inspector: None,
})
}
pub(crate) fn new_focus_listener(
&self,
value: AnyWindowFocusListener,
) -> (Subscription, impl FnOnce() + use<>) {
self.focus_listeners.insert((), value)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[allow(missing_docs)]
pub struct DispatchEventResult {
pub propagate: bool,
pub default_prevented: bool,
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
#[repr(C)]
pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
pub bounds: Bounds<P>,
}
impl ContentMask<Pixels> {
pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
ContentMask {
bounds: self.bounds.scale(factor),
}
}
pub fn intersect(&self, other: &Self) -> Self {
let bounds = self.bounds.intersect(&other.bounds);
ContentMask { bounds }
}
}
impl Window {
fn mark_view_dirty(&mut self, view_id: EntityId) {
for view_id in self
.rendered_frame
.dispatch_tree
.view_path(view_id)
.into_iter()
.rev()
{
if !self.dirty_views.insert(view_id) {
break;
}
}
}
pub fn visibility(&self) -> WindowVisibility {
self.visibility
}
pub fn is_visible(&self) -> bool {
self.visibility.is_visible()
}
pub fn observe_window_visibility(
&self,
mut callback: impl FnMut(WindowVisibility, &mut Window, &mut App) + 'static,
) -> Subscription {
let (subscription, activate) = self.visibility_observers.insert(
(),
Box::new(move |visibility, window, cx| {
callback(visibility, window, cx);
true
}),
);
activate();
subscription
}
pub fn observe_window_appearance(
&self,
mut callback: impl FnMut(&mut Window, &mut App) + 'static,
) -> Subscription {
let (subscription, activate) = self.appearance_observers.insert(
(),
Box::new(move |window, cx| {
callback(window, cx);
true
}),
);
activate();
subscription
}
pub fn replace_root<E>(
&mut self,
cx: &mut App,
build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
) -> Entity<E>
where
E: 'static + Render,
{
let view = cx.new(|cx| build_view(self, cx));
self.root = Some(view.clone().into());
self.refresh();
view
}
pub fn root<E>(&self) -> Option<Option<Entity<E>>>
where
E: 'static + Render,
{
self.root
.as_ref()
.map(|view| view.clone().downcast::<E>().ok())
}
pub fn window_handle(&self) -> AnyWindowHandle {
self.handle
}
pub fn refresh(&mut self) {
if self.invalidator.not_drawing() {
self.refreshing = true;
self.invalidator.set_dirty(true);
}
}
pub fn remove_window(&mut self) {
self.removed = true;
}
pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
self.focus
.and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
}
pub fn focus_lost_restore_target(&self, cx: &App) -> Option<FocusHandle> {
let (_leaf, ancestors) = self.focus_lost_path.split_last()?;
ancestors.iter().rev().find_map(|id| {
self.rendered_frame.dispatch_tree.focusable_node_id(*id)?;
FocusHandle::for_id(*id, &cx.focus_handles)
})
}
pub fn focus(&mut self, handle: &FocusHandle) {
if !self.focus_enabled || self.focus == Some(handle.id) {
return;
}
self.focus = Some(handle.id);
self.pending_input.take();
self.refresh();
}
pub fn blur(&mut self, cx: &mut App) {
self.clear_pending_keystrokes(cx);
if !self.focus_enabled {
return;
}
self.focus = None;
self.refresh();
}
pub fn disable_focus(&mut self, cx: &mut App) {
self.blur(cx);
self.focus_enabled = false;
}
pub fn focus_next(&mut self) {
if !self.focus_enabled {
return;
}
if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
self.focus(&handle)
}
}
pub fn focus_prev(&mut self) {
if !self.focus_enabled {
return;
}
if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
self.focus(&handle)
}
}
pub fn text_system(&self) -> &Arc<WindowTextSystem> {
&self.text_system
}
pub fn text_style(&self) -> TextStyle {
let mut style = TextStyle::default();
for refinement in &self.text_style_stack {
style.refine(refinement);
}
style
}
pub fn is_maximized(&self) -> bool {
self.platform_window.is_maximized()
}
pub fn request_decorations(&self, decorations: WindowDecorations) {
self.platform_window.request_decorations(decorations);
}
pub fn set_exclusive_zone(&self, zone: Pixels) {
self.platform_window.set_exclusive_zone(zone);
}
#[cfg(all(any(target_os = "linux", target_os = "freebsd"), feature = "wayland"))]
pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) {
self.platform_window.set_exclusive_edge(edge);
}
pub fn start_window_resize(&self, edge: ResizeEdge) {
self.platform_window.start_window_resize(edge);
}
pub fn window_bounds(&self) -> WindowBounds {
self.platform_window.window_bounds()
}
pub fn inner_window_bounds(&self) -> WindowBounds {
self.platform_window.inner_window_bounds()
}
pub fn native_window_state(&self) -> Option<Vec<u8>> {
self.platform_window.native_window_state()
}
pub fn restore_native_window_state(&self, state: &[u8]) {
self.platform_window.restore_native_window_state(state);
}
pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
let focus_id = self.focused(cx).map(|handle| handle.id);
let window = self.handle;
cx.defer(move |cx| {
window
.update(cx, |_, window, cx| {
let node_id = window.focus_node_id_in_rendered_frame(focus_id);
window.dispatch_action_on_node(node_id, action.as_ref(), cx);
})
.log_err();
})
}
pub(crate) fn dispatch_keystroke_observers(
&mut self,
keystroke: &Keystroke,
input_preference: InputPreference,
action: Option<&dyn Action>,
context_stack: Vec<KeyContext>,
cx: &mut App,
) {
cx.keystroke_observers.clone().retain(&(), move |callback| {
(callback)(
&KeystrokeEvent {
keystroke: keystroke.clone(),
input_preference,
action: action.map(|action| action.boxed_clone()),
context_stack: context_stack.clone(),
},
self,
cx,
)
});
}
pub(crate) fn dispatch_keystroke_interceptors(
&mut self,
keystroke: &Keystroke,
input_preference: InputPreference,
context_stack: Vec<KeyContext>,
cx: &mut App,
) {
cx.keystroke_interceptors
.clone()
.retain(&(), move |callback| {
(callback)(
&KeystrokeEvent {
keystroke: keystroke.clone(),
input_preference,
action: None,
context_stack: context_stack.clone(),
},
self,
cx,
)
});
}
pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
let handle = self.handle;
cx.defer(move |cx| {
handle.update(cx, |_, window, cx| f(window, cx)).ok();
});
}
pub fn observe<T: 'static>(
&mut self,
observed: &Entity<T>,
cx: &mut App,
mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
) -> Subscription {
let entity_id = observed.entity_id();
let observed = observed.downgrade();
let window_handle = self.handle;
cx.new_observer(
entity_id,
Box::new(move |cx| {
window_handle
.update(cx, |_, window, cx| {
if let Some(handle) = observed.upgrade() {
on_notify(handle, window, cx);
true
} else {
false
}
})
.unwrap_or(false)
}),
)
}
pub fn subscribe<Emitter, Evt>(
&mut self,
entity: &Entity<Emitter>,
cx: &mut App,
mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
) -> Subscription
where
Emitter: EventEmitter<Evt>,
Evt: 'static,
{
let entity_id = entity.entity_id();
let handle = entity.downgrade();
let window_handle = self.handle;
cx.new_subscription(
entity_id,
(
TypeId::of::<Evt>(),
Box::new(move |event, cx| {
window_handle
.update(cx, |_, window, cx| {
if let Some(entity) = handle.upgrade() {
let event = event.downcast_ref().expect("invalid event type");
on_event(entity, event, window, cx);
true
} else {
false
}
})
.unwrap_or(false)
}),
),
)
}
pub fn observe_release<T>(
&self,
entity: &Entity<T>,
cx: &mut App,
mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
) -> Subscription
where
T: 'static,
{
let entity_id = entity.entity_id();
let window_handle = self.handle;
let (subscription, activate) = cx.release_listeners.insert(
entity_id,
Box::new(move |entity, cx| {
let entity = entity.downcast_mut().expect("invalid entity type");
let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
}),
);
activate();
subscription
}
pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
AsyncWindowContext::new_context(cx.to_async(), self.handle)
}
pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
self.platform_window.schedule_frame();
}
pub fn request_animation_frame(&self) {
let entity = self.current_view();
self.on_next_frame(move |_, cx| cx.notify(entity));
}
#[track_caller]
pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
where
R: 'static,
AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
{
let handle = self.handle;
cx.spawn(async move |app| {
let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
f(&mut async_window_cx).await
})
}
fn bounds_changed(&mut self, cx: &mut App) {
self.scale_factor = self.platform_window.scale_factor();
self.viewport_size = self.platform_window.content_size();
self.display_id = self.platform_window.display().map(|display| display.id());
self.mouse_position = self.platform_window.mouse_position();
self.platform_window.a11y_update_window_bounds();
self.refresh();
self.bounds_observers
.clone()
.retain(&(), |callback| callback(self, cx));
}
pub fn bounds(&self) -> Bounds<Pixels> {
self.platform_window.bounds()
}
pub fn resize(&mut self, size: Size<Pixels>) {
self.platform_window.resize(size);
}
pub fn resize_anchored(&mut self, size: Size<Pixels>, anchor: ResizeAnchor) {
self.platform_window.resize_anchored(size, anchor);
}
pub fn is_fullscreen(&self) -> bool {
self.platform_window.is_fullscreen()
}
pub fn is_simple_fullscreen(&self) -> bool {
self.platform_window.is_simple_fullscreen()
}
pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
self.appearance = self.platform_window.appearance();
self.appearance_observers
.clone()
.retain(&(), |callback| callback(self, cx));
}
pub fn appearance(&self) -> WindowAppearance {
self.appearance
}
pub fn viewport_size(&self) -> Size<Pixels> {
self.viewport_size
}
pub fn is_window_active(&self) -> bool {
self.active.get()
}
pub fn is_window_hovered(&self) -> bool {
if cfg!(any(
target_os = "windows",
target_os = "linux",
target_os = "freebsd"
)) {
self.hovered.get()
} else {
self.is_window_active()
}
}
pub fn last_input_was_keyboard(&self) -> bool {
self.last_input_was_keyboard.get()
}
pub fn zoom_window(&self) {
self.platform_window.zoom();
}
pub fn show_window_menu(&self, position: Point<Pixels>) {
self.platform_window.show_window_menu(position)
}
pub fn start_window_move(&self) {
self.platform_window.start_window_move()
}
pub fn set_client_inset(&mut self, inset: Pixels) {
self.client_inset = Some(inset);
self.platform_window.set_client_inset(inset);
}
pub fn set_client_corner_radii(&mut self, radii: Corners<Pixels>) {
self.platform_window.set_client_corner_radii(radii);
}
pub fn client_inset(&self) -> Option<Pixels> {
self.client_inset
}
pub fn window_decorations(&self) -> Decorations {
self.platform_window.window_decorations()
}
pub fn window_controls(&self) -> WindowControls {
self.platform_window.window_controls()
}
pub fn set_window_title(&mut self, title: &str) {
self.platform_window.set_title(title);
}
pub fn set_app_id(&mut self, app_id: &str) {
self.platform_window.set_app_id(app_id);
}
pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
self.platform_window
.set_background_appearance(background_appearance);
}
pub fn set_window_edited(&mut self, edited: bool) {
self.platform_window.set_edited(edited);
}
pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
cx.platform
.displays()
.into_iter()
.find(|display| Some(display.id()) == self.display_id)
}
pub fn show_character_palette(&self) {
self.platform_window.show_character_palette();
}
pub fn scale_factor(&self) -> f32 {
self.scale_factor
}
pub fn rem_size(&self) -> Pixels {
self.rem_size_override_stack
.last()
.copied()
.unwrap_or(self.rem_size)
}
pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
self.rem_size = rem_size.into();
}
pub fn with_global_id<R>(
&mut self,
element_id: ElementId,
f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
) -> R {
self.element_id_stack.push(element_id);
let global_id = GlobalElementId(self.element_id_stack.clone());
let result = f(&global_id, self);
self.element_id_stack.pop();
result
}
pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
where
F: FnOnce(&mut Self) -> R,
{
self.invalidator.debug_assert_paint_or_prepaint();
if let Some(rem_size) = rem_size {
self.rem_size_override_stack.push(rem_size.into());
let result = f(self);
self.rem_size_override_stack.pop();
result
} else {
f(self)
}
}
pub fn line_height(&self) -> Pixels {
self.text_style().line_height_in_pixels(self.rem_size())
}
#[inline]
pub fn pixel_snap(&self, value: Pixels) -> Pixels {
px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
}
#[inline]
pub fn pixel_snap_f64(&self, value: f64) -> f64 {
let scale_factor = f64::from(self.scale_factor());
round_half_toward_zero_f64(value * scale_factor) / scale_factor
}
#[inline]
pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
bounds.map(|c| self.pixel_snap(c))
}
#[inline]
pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
position.map(|c| self.pixel_snap(c))
}
#[inline]
fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
let scale_factor = self.scale_factor();
let left = round_to_device_pixel(bounds.left().0, scale_factor);
let top = round_to_device_pixel(bounds.top().0, scale_factor);
let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
Bounds::from_corners(
point(ScaledPixels(left), ScaledPixels(top)),
point(ScaledPixels(right), ScaledPixels(bottom)),
)
}
#[inline]
fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
}
#[inline]
fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
edges.map(|e| self.snap_stroke(*e))
}
#[inline]
fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
let scale_factor = self.scale_factor();
let left = floor_to_device_pixel(bounds.left().0, scale_factor);
let top = floor_to_device_pixel(bounds.top().0, scale_factor);
let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
Bounds::from_corners(
point(ScaledPixels(left), ScaledPixels(top)),
point(ScaledPixels(right), ScaledPixels(bottom)),
)
}
#[inline]
fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
ContentMask {
bounds: self.cover_bounds(self.content_mask().bounds),
}
}
pub fn prevent_default(&mut self) {
self.default_prevented = true;
}
pub fn default_prevented(&self) -> bool {
self.default_prevented
}
pub fn is_action_available(&self, action: &dyn Action, cx: &mut App) -> bool {
let node_id =
self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
self.rendered_frame
.dispatch_tree
.is_action_available(action, node_id)
}
pub fn mouse_position(&self) -> Point<Pixels> {
self.mouse_position
}
pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
self.captured_hitbox = Some(hitbox_id);
}
pub fn release_pointer(&mut self) {
self.captured_hitbox = None;
}
pub fn captured_hitbox(&self) -> Option<HitboxId> {
self.captured_hitbox
}
pub fn modifiers(&self) -> Modifiers {
self.modifiers
}
pub fn capslock(&self) -> Capslock {
self.capslock
}
#[profiling::function]
pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
let arena_scope = ElementArenaScope::enter();
self.invalidate_entities();
cx.entities.clear_accessed();
debug_assert!(self.rendered_entity_stack.is_empty());
self.invalidator.set_dirty(false);
self.requested_autoscroll = None;
if let Some(input_handler) = self.platform_window.take_input_handler() {
if let Some(slot) = self
.rendered_frame
.input_handlers
.iter_mut()
.rev()
.find(|handler| handler.is_none())
{
*slot = Some(input_handler);
} else {
self.rendered_frame.input_handlers.push(Some(input_handler));
}
}
self.draw_roots(cx);
self.dirty_views.clear();
self.next_frame.window_active = self.active.get();
if let Some(input_handler) = self
.next_frame
.input_handlers
.iter_mut()
.rev()
.find_map(|handler| handler.take())
{
self.platform_window.set_input_handler(input_handler);
}
self.layout_engine.as_mut().unwrap().clear();
self.text_system().finish_frame();
self.next_frame.finish(&mut self.rendered_frame);
self.invalidator.set_phase(DrawPhase::Focus);
let previous_focus_path = self.rendered_frame.focus_path();
let previous_window_active = self.rendered_frame.window_active;
mem::swap(&mut self.rendered_frame, &mut self.next_frame);
self.next_frame.clear();
let current_focus_path = self.rendered_frame.focus_path();
let current_window_active = self.rendered_frame.window_active;
if previous_focus_path != current_focus_path
|| previous_window_active != current_window_active
{
if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
self.focus_lost_path = previous_focus_path.clone();
self.focus_lost_listeners
.clone()
.retain(&(), |listener| listener(self, cx));
self.focus_lost_path = SmallVec::new();
}
let event = WindowFocusEvent {
previous_focus_path: if previous_window_active {
previous_focus_path
} else {
Default::default()
},
current_focus_path: if current_window_active {
current_focus_path
} else {
Default::default()
},
};
self.focus_listeners
.clone()
.retain(&(), |listener| listener(&event, self, cx));
}
debug_assert!(self.rendered_entity_stack.is_empty());
self.record_entities_accessed(cx);
self.reset_cursor_style(cx);
self.refreshing = false;
self.invalidator.set_phase(DrawPhase::None);
self.needs_present.set(true);
drop(arena_scope);
ArenaClearNeeded
}
#[cfg(any(test, feature = "test-support"))]
pub fn visual_render_artifact(&self) -> crate::VisualRenderArtifact {
crate::VisualRenderArtifact::from_scene(&self.rendered_frame.scene)
}
#[cfg(any(test, feature = "test-support"))]
pub fn present_for_visual_test(&mut self) {
self.present();
}
#[cfg(any(test, feature = "test-support"))]
pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
self.platform_window
.render_to_image(&self.rendered_frame.scene)
}
#[cfg(any(test, feature = "test-support"))]
pub fn painted_quads(&self) -> Vec<Quad> {
self.rendered_frame.scene.quads.clone()
}
fn record_entities_accessed(&mut self, cx: &mut App) {
let mut entities_ref = cx.entities.accessed_entities.borrow_mut();
let mut entities = mem::take(entities_ref.deref_mut());
drop(entities_ref);
let handle = self.handle;
cx.record_entities_accessed(
handle,
self.invalidator.clone(),
&entities,
);
let mut entities_ref = cx.entities.accessed_entities.borrow_mut();
mem::swap(&mut entities, entities_ref.deref_mut());
}
fn invalidate_entities(&mut self) {
let mut views = self.invalidator.take_views();
for entity in views.drain() {
self.mark_view_dirty(entity);
}
self.invalidator.replace_views(views);
}
#[profiling::function]
fn present(&mut self) {
self.platform_window.draw(&self.rendered_frame.scene);
#[cfg(feature = "input-latency-histogram")]
self.input_latency_tracker.record_frame_presented();
self.needs_present.set(false);
profiling::finish_frame!();
}
#[cfg(feature = "input-latency-histogram")]
pub fn input_latency_snapshot(&self) -> InputLatencySnapshot {
self.input_latency_tracker.snapshot()
}
fn draw_roots(&mut self, cx: &mut App) {
self.invalidator.set_phase(DrawPhase::Prepaint);
self.tooltip_bounds.take();
self.a11y.sync_active_flag();
if self.a11y.is_active() {
self.a11y.begin_frame();
}
let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
let root_size = {
#[cfg(any(feature = "inspector", debug_assertions))]
{
if self.inspector.is_some() {
let mut size = self.viewport_size;
size.width = (size.width - _inspector_width).max(px(0.0));
size
} else {
self.viewport_size
}
}
#[cfg(not(any(feature = "inspector", debug_assertions)))]
{
self.viewport_size
}
};
let scale_factor = self.scale_factor();
let mut root_element = self.root.as_ref().unwrap().clone().into_any();
let root_layout_id = root_element.request_layout(self, cx);
self.layout_engine
.as_mut()
.unwrap()
.stretch_auto_size_to_fill(root_layout_id, root_size, scale_factor);
root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
#[cfg(any(feature = "inspector", debug_assertions))]
let inspector_element = self.prepaint_inspector(_inspector_width, cx);
self.prepaint_deferred_draws(cx);
let mut prompt_element = None;
let mut active_drag_element = None;
let mut tooltip_element = None;
if let Some(prompt) = self.prompt.take() {
let mut element = prompt.view.any_view().into_any();
let prompt_layout_id = element.request_layout(self, cx);
self.layout_engine
.as_mut()
.unwrap()
.stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor);
element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
prompt_element = Some(element);
self.prompt = Some(prompt);
} else if let Some(active_drag) = cx.active_drag.take() {
let mut element = active_drag.view.clone().into_any();
let offset = self.mouse_position() - active_drag.cursor_offset;
element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
active_drag_element = Some(element);
cx.active_drag = Some(active_drag);
} else {
tooltip_element = self.prepaint_tooltip(cx);
}
self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
self.invalidator.set_phase(DrawPhase::Paint);
root_element.paint(self, cx);
#[cfg(any(feature = "inspector", debug_assertions))]
self.paint_inspector(inspector_element, cx);
let mut sorted_deferred_draws =
(0..self.next_frame.deferred_draws.len()).collect::<SmallVec<[_; 8]>>();
sorted_deferred_draws.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
self.paint_deferred_draws(&sorted_deferred_draws, cx);
if let Some(mut prompt_element) = prompt_element {
prompt_element.paint(self, cx);
} else if let Some(mut drag_element) = active_drag_element {
drag_element.paint(self, cx);
} else if let Some(mut tooltip_element) = tooltip_element {
tooltip_element.paint(self, cx);
}
#[cfg(any(feature = "inspector", debug_assertions))]
self.paint_inspector_hitbox(cx);
let a11y_active_start_of_frame = self.a11y.is_active();
self.a11y.sync_active_flag();
let a11y_active_end_of_frame = self.a11y.is_active();
if a11y_active_start_of_frame {
let tree_update = self.a11y.end_frame();
if a11y_active_end_of_frame {
log::debug!(
"Sending a11y tree update: {} nodes",
tree_update.nodes.len()
);
self.platform_window.a11y_tree_update(tree_update);
}
}
}
fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
let Some(Some(tooltip_request)) = self
.next_frame
.tooltip_requests
.get(tooltip_request_index)
.cloned()
else {
log::error!("Unexpectedly absent TooltipRequest");
continue;
};
let mut element = tooltip_request.tooltip.view.clone().into_any();
let mouse_position = tooltip_request.tooltip.mouse_position;
let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
let mut tooltip_bounds =
Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
let window_bounds = Bounds {
origin: Point::default(),
size: self.viewport_size(),
};
if tooltip_bounds.right() > window_bounds.right() {
let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
if new_x >= Pixels::ZERO {
tooltip_bounds.origin.x = new_x;
} else {
tooltip_bounds.origin.x = cmp::max(
Pixels::ZERO,
tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
);
}
}
if tooltip_bounds.bottom() > window_bounds.bottom() {
let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
if new_y >= Pixels::ZERO {
tooltip_bounds.origin.y = new_y;
} else {
tooltip_bounds.origin.y = cmp::max(
Pixels::ZERO,
tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
);
}
}
let is_visible =
(tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
if !is_visible {
continue;
}
self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
element.prepaint(window, cx)
});
self.tooltip_bounds = Some(TooltipBounds {
id: tooltip_request.id,
bounds: tooltip_bounds,
});
return Some(element);
}
None
}
fn prepaint_deferred_draws(&mut self, cx: &mut App) {
assert_eq!(self.element_id_stack.len(), 0);
let mut round_start = 0;
let mut depth = 0;
loop {
let round_end = self.next_frame.deferred_draws.len();
if round_start == round_end {
break;
}
assert!(depth < 10, "Exceeded maximum (10) deferred depth");
depth += 1;
let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
traversal_order.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
for deferred_draw_ix in traversal_order {
let (element, parent_node, current_view, absolute_offset, prepaint_range) = {
let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix];
self.element_id_stack
.clone_from(&deferred_draw.element_id_stack);
self.text_style_stack
.clone_from(&deferred_draw.text_style_stack);
(
deferred_draw.element.take(),
deferred_draw.parent_node,
deferred_draw.current_view,
deferred_draw.absolute_offset,
deferred_draw.prepaint_range.clone(),
)
};
self.next_frame.dispatch_tree.set_active_node(parent_node);
let prepaint_start = self.prepaint_index();
if let Some(mut element) = element {
self.with_rendered_view(current_view, |window| {
window.with_absolute_element_offset(absolute_offset, |window| {
element.prepaint(window, cx)
});
});
self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element);
} else {
self.reuse_prepaint(prepaint_range);
}
let prepaint_end = self.prepaint_index();
self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
prepaint_start..prepaint_end;
}
self.element_id_stack.clear();
self.text_style_stack.clear();
round_start = round_end;
}
}
fn paint_deferred_draws(&mut self, deferred_draw_indices: &[usize], cx: &mut App) {
assert_eq!(self.element_id_stack.len(), 0);
let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
for deferred_draw_ix in deferred_draw_indices {
let mut deferred_draw = &mut deferred_draws[*deferred_draw_ix];
self.element_id_stack
.clone_from(&deferred_draw.element_id_stack);
self.next_frame
.dispatch_tree
.set_active_node(deferred_draw.parent_node);
let paint_start = self.paint_index();
if let Some(element) = deferred_draw.element.as_mut() {
self.with_rendered_view(deferred_draw.current_view, |window| {
element.paint(window, cx);
})
} else {
self.reuse_paint(deferred_draw.paint_range.clone());
}
let paint_end = self.paint_index();
deferred_draw.paint_range = paint_start..paint_end;
}
self.next_frame.deferred_draws = deferred_draws;
self.element_id_stack.clear();
}
pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
PrepaintStateIndex {
hitboxes_index: self.next_frame.hitboxes.len(),
tooltips_index: self.next_frame.tooltip_requests.len(),
deferred_draws_index: self.next_frame.deferred_draws.len(),
dispatch_tree_index: self.next_frame.dispatch_tree.len(),
accessed_element_states_index: self.next_frame.accessed_element_states.len(),
line_layout_index: self.text_system.layout_index(),
}
}
pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
self.next_frame.hitboxes.extend(
self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
.iter()
.cloned(),
);
self.next_frame.tooltip_requests.extend(
self.rendered_frame.tooltip_requests
[range.start.tooltips_index..range.end.tooltips_index]
.iter_mut()
.map(|request| request.take()),
);
self.next_frame.accessed_element_states.extend(
self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
..range.end.accessed_element_states_index]
.iter()
.map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
);
self.text_system
.reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
range.start.dispatch_tree_index..range.end.dispatch_tree_index,
&mut self.rendered_frame.dispatch_tree,
self.focus,
);
if reused_subtree.contains_focus() {
self.next_frame.focus = self.focus;
}
self.next_frame.deferred_draws.extend(
self.rendered_frame.deferred_draws
[range.start.deferred_draws_index..range.end.deferred_draws_index]
.iter()
.map(|deferred_draw| DeferredDraw {
current_view: deferred_draw.current_view,
parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
element_id_stack: deferred_draw.element_id_stack.clone(),
text_style_stack: deferred_draw.text_style_stack.clone(),
priority: deferred_draw.priority,
element: None,
absolute_offset: deferred_draw.absolute_offset,
prepaint_range: deferred_draw.prepaint_range.clone(),
paint_range: deferred_draw.paint_range.clone(),
}),
);
}
pub(crate) fn paint_index(&self) -> PaintIndex {
PaintIndex {
scene_index: self.next_frame.scene.len(),
#[cfg(any(test, feature = "test-support"))]
debug_bounds_index: self.next_frame.debug_bounds_records.len(),
mouse_listeners_index: self.next_frame.mouse_listeners.len(),
input_handlers_index: self.next_frame.input_handlers.len(),
cursor_styles_index: self.next_frame.cursor_styles.len(),
accessed_element_states_index: self.next_frame.accessed_element_states.len(),
tab_handle_index: self.next_frame.tab_stops.paint_index(),
line_layout_index: self.text_system.layout_index(),
}
}
pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
#[cfg(any(test, feature = "test-support"))]
for (selector, bounds) in &self.rendered_frame.debug_bounds_records
[range.start.debug_bounds_index..range.end.debug_bounds_index]
{
self.next_frame
.record_debug_bounds(selector.clone(), *bounds);
}
self.next_frame.cursor_styles.extend(
self.rendered_frame.cursor_styles
[range.start.cursor_styles_index..range.end.cursor_styles_index]
.iter()
.cloned(),
);
self.next_frame.input_handlers.extend(
self.rendered_frame.input_handlers
[range.start.input_handlers_index..range.end.input_handlers_index]
.iter_mut()
.map(|handler| handler.take()),
);
self.next_frame.mouse_listeners.extend(
self.rendered_frame.mouse_listeners
[range.start.mouse_listeners_index..range.end.mouse_listeners_index]
.iter_mut()
.map(|listener| listener.take()),
);
self.next_frame.accessed_element_states.extend(
self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
..range.end.accessed_element_states_index]
.iter()
.map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
);
self.next_frame.tab_stops.replay(
&self.rendered_frame.tab_stops.insertion_history
[range.start.tab_handle_index..range.end.tab_handle_index],
);
self.text_system
.reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
self.next_frame.scene.replay(
range.start.scene_index..range.end.scene_index,
&self.rendered_frame.scene,
);
}
pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
where
F: FnOnce(&mut Self) -> R,
{
self.invalidator.debug_assert_paint_or_prepaint();
if let Some(style) = style {
self.text_style_stack.push(style);
let result = f(self);
self.text_style_stack.pop();
result
} else {
f(self)
}
}
pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
self.invalidator.debug_assert_paint();
self.next_frame.cursor_styles.push(CursorStyleRequest {
hitbox_id: Some(hitbox.id),
style,
});
}
pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
self.invalidator.debug_assert_paint();
self.next_frame.cursor_styles.push(CursorStyleRequest {
hitbox_id: None,
style,
})
}
pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
self.invalidator.debug_assert_prepaint();
let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
self.next_frame
.tooltip_requests
.push(Some(TooltipRequest { id, tooltip }));
id
}
pub fn with_content_mask<R>(
&mut self,
mask: Option<ContentMask<Pixels>>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
self.invalidator.debug_assert_paint_or_prepaint();
if let Some(mask) = mask {
let mask = mask.intersect(&self.content_mask());
self.content_mask_stack.push(mask);
let result = f(self);
self.content_mask_stack.pop();
result
} else {
f(self)
}
}
pub fn with_element_offset<R>(
&mut self,
offset: Point<Pixels>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
self.invalidator.debug_assert_prepaint();
if offset.is_zero() {
return f(self);
};
let abs_offset = self.element_offset() + offset;
self.with_absolute_element_offset(abs_offset, f)
}
pub fn with_absolute_element_offset<R>(
&mut self,
offset: Point<Pixels>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
self.invalidator.debug_assert_prepaint();
self.element_offset_stack.push(offset);
let result = f(self);
self.element_offset_stack.pop();
result
}
pub(crate) fn with_element_opacity<R>(
&mut self,
opacity: Option<f32>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
self.invalidator.debug_assert_paint_or_prepaint();
let Some(opacity) = opacity else {
return f(self);
};
let previous_opacity = self.element_opacity;
self.element_opacity = previous_opacity * opacity;
let result = f(self);
self.element_opacity = previous_opacity;
result
}
pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
self.invalidator.debug_assert_prepaint();
let index = self.prepaint_index();
let result = f(self);
if result.is_err() {
self.next_frame.hitboxes.truncate(index.hitboxes_index);
self.next_frame
.tooltip_requests
.truncate(index.tooltips_index);
self.next_frame
.deferred_draws
.truncate(index.deferred_draws_index);
self.next_frame
.dispatch_tree
.truncate(index.dispatch_tree_index);
self.next_frame
.accessed_element_states
.truncate(index.accessed_element_states_index);
self.text_system.truncate_layouts(index.line_layout_index);
}
result
}
pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
self.invalidator.debug_assert_prepaint();
self.requested_autoscroll = Some(bounds);
}
pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
self.invalidator.debug_assert_prepaint();
self.requested_autoscroll.take()
}
pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
cx.asset_entry::<A>(source).use_by(self.current_view())
}
pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
cx.fetch_asset::<A>(source)
}
pub fn element_offset(&self) -> Point<Pixels> {
self.invalidator.debug_assert_prepaint();
self.element_offset_stack
.last()
.copied()
.unwrap_or_default()
}
#[inline]
pub(crate) fn element_opacity(&self) -> f32 {
self.invalidator.debug_assert_paint_or_prepaint();
self.element_opacity
}
pub fn content_mask(&self) -> ContentMask<Pixels> {
self.invalidator.debug_assert_paint_or_prepaint();
self.content_mask_stack
.last()
.cloned()
.unwrap_or_else(|| ContentMask {
bounds: Bounds {
origin: Point::default(),
size: self.viewport_size,
},
})
}
pub fn with_element_namespace<R>(
&mut self,
element_id: impl Into<ElementId>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
self.element_id_stack.push(element_id.into());
let result = f(self);
self.element_id_stack.pop();
result
}
pub fn use_keyed_state<S: 'static>(
&mut self,
key: impl Into<ElementId>,
cx: &mut App,
init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
) -> Entity<S> {
let current_view = self.current_view();
self.with_global_id(key.into(), |global_id, window| {
window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
if let Some(state) = state {
(state.clone(), state)
} else {
let new_state = cx.new(|cx| init(window, cx));
cx.observe(&new_state, move |_, cx| {
cx.notify(current_view);
})
.detach();
(new_state.clone(), new_state)
}
})
})
}
pub fn with_id<R>(&mut self, id: impl Into<ElementId>, f: impl FnOnce(&mut Self) -> R) -> R {
self.with_global_id(id.into(), |_, window| f(window))
}
#[track_caller]
pub fn use_state<S: 'static>(
&mut self,
cx: &mut App,
init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
) -> Entity<S> {
self.use_keyed_state(
ElementId::CodeLocation(*core::panic::Location::caller()),
cx,
init,
)
}
pub fn with_element_state<S, R>(
&mut self,
global_id: &GlobalElementId,
f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
) -> R
where
S: 'static,
{
self.invalidator.debug_assert_paint_or_prepaint();
let key = (GlobalElementId(global_id.0.clone()), TypeId::of::<S>());
self.next_frame
.accessed_element_states
.push((GlobalElementId(key.0.clone()), TypeId::of::<S>()));
if let Some(any) = self
.next_frame
.element_states
.remove(&key)
.or_else(|| self.rendered_frame.element_states.remove(&key))
{
let ElementStateBox {
inner,
#[cfg(debug_assertions)]
type_name,
} = any;
let mut state_box = inner
.downcast::<Option<S>>()
.map_err(|_| {
#[cfg(debug_assertions)]
{
anyhow::anyhow!(
"invalid element state type for id, requested {:?}, actual: {:?}",
std::any::type_name::<S>(),
type_name
)
}
#[cfg(not(debug_assertions))]
{
anyhow::anyhow!(
"invalid element state type for id, requested {:?}",
std::any::type_name::<S>(),
)
}
})
.unwrap();
let state = state_box.take().expect(
"reentrant call to with_element_state for the same state type and element id",
);
let (result, state) = f(Some(state), self);
state_box.replace(state);
self.next_frame.element_states.insert(
key,
ElementStateBox {
inner: state_box,
#[cfg(debug_assertions)]
type_name,
},
);
result
} else {
let (result, state) = f(None, self);
self.next_frame.element_states.insert(
key,
ElementStateBox {
inner: Box::new(Some(state)),
#[cfg(debug_assertions)]
type_name: std::any::type_name::<S>(),
},
);
result
}
}
pub fn with_optional_element_state<S, R>(
&mut self,
global_id: Option<&GlobalElementId>,
f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
) -> R
where
S: 'static,
{
self.invalidator.debug_assert_paint_or_prepaint();
if let Some(global_id) = global_id {
self.with_element_state(global_id, |state, cx| {
let (result, state) = f(Some(state), cx);
let state =
state.expect("you must return some state when you pass some element id");
(result, state)
})
} else {
let (result, state) = f(None, self);
debug_assert!(
state.is_none(),
"you must not return an element state when passing None for the global id"
);
result
}
}
#[inline]
pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
if let Some(index) = index {
self.next_frame.tab_stops.begin_group(index);
let result = f(self);
self.next_frame.tab_stops.end_group();
result
} else {
f(self)
}
}
pub fn defer_draw(
&mut self,
element: AnyElement,
absolute_offset: Point<Pixels>,
priority: usize,
) {
self.invalidator.debug_assert_prepaint();
let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
self.next_frame.deferred_draws.push(DeferredDraw {
current_view: self.current_view(),
parent_node,
element_id_stack: self.element_id_stack.clone(),
text_style_stack: self.text_style_stack.clone(),
priority,
element: Some(element),
absolute_offset,
prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
paint_range: PaintIndex::default()..PaintIndex::default(),
});
}
pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
self.invalidator.debug_assert_paint();
let content_mask = self.content_mask();
let clipped_bounds = bounds.intersect(&content_mask.bounds);
if !clipped_bounds.is_empty() {
self.next_frame
.scene
.push_layer(self.cover_bounds(clipped_bounds));
}
let result = f(self);
if !clipped_bounds.is_empty() {
self.next_frame.scene.pop_layer();
}
result
}
pub fn paint_shadows(
&mut self,
bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
shadows: &[BoxShadow],
) {
self.invalidator.debug_assert_paint();
let scale_factor = self.scale_factor();
let content_mask = self.snapped_content_mask();
let opacity = self.element_opacity();
for shadow in shadows {
let shadow_bounds = if shadow.inset {
bounds.contract(shadow.spread_radius)
} else {
(bounds + shadow.offset).dilate(shadow.spread_radius)
};
self.next_frame.scene.insert_primitive(Shadow {
order: 0,
blur_radius: shadow.blur_radius.scale(scale_factor),
bounds: if shadow.inset {
self.snap_bounds(shadow_bounds)
} else {
self.cover_bounds(shadow_bounds)
},
content_mask: if shadow.inset {
ContentMask {
bounds: self.snap_bounds(bounds),
}
} else {
content_mask
},
corner_radii: corner_radii.scale(scale_factor),
color: shadow.color.opacity(opacity),
inset: if shadow.inset { 1 } else { 0 },
_pad_end: 0,
});
}
}
pub fn paint_quad(&mut self, quad: PaintQuad) {
self.invalidator.debug_assert_paint();
let opacity = self.element_opacity();
let snapped_bounds = self.snap_bounds(quad.bounds);
let snapped_border_widths = self.snap_border_widths(quad.border_widths);
let quad = Quad {
order: 0,
bounds: snapped_bounds,
content_mask: self.snapped_content_mask(),
background: quad.background.opacity(opacity),
border_color: quad.border_color.opacity(opacity),
corner_radii: quad.corner_radii.scale(self.scale_factor()),
border_widths: snapped_border_widths,
border_style: quad.border_style,
continuous_corners: if quad.continuous_corners { 1 } else { 0 },
_pad_before_transform: 0,
transform: quad.transform,
blend_mode: quad.blend_mode as u32,
_pad_end: 0,
};
if !quad.background.is_transparent() {
self.next_frame.scene.insert_primitive(quad);
return;
}
let Some(strips) =
border_only_quad_strips(quad.bounds, quad.border_widths, quad.corner_radii)
else {
self.next_frame.scene.insert_primitive(quad);
return;
};
for strip in strips {
let mask_bounds = quad.content_mask.bounds.intersect(&strip);
if !mask_bounds.is_empty() {
self.next_frame.scene.insert_primitive(Quad {
content_mask: ContentMask {
bounds: mask_bounds,
},
..quad
});
}
}
}
pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
self.invalidator.debug_assert_paint();
let scale_factor = self.scale_factor();
let content_mask = self.content_mask();
let opacity = self.element_opacity();
path.content_mask = content_mask;
let color: Background = color.into();
path.color = color.opacity(opacity);
self.next_frame
.scene
.insert_primitive(path.scale(scale_factor));
}
pub fn paint_underline(
&mut self,
origin: Point<Pixels>,
width: Pixels,
style: &UnderlineStyle,
) {
self.invalidator.debug_assert_paint();
let scale_factor = self.scale_factor();
let thickness = self.snap_stroke(style.thickness);
let height = if style.wavy {
ScaledPixels(thickness.0 * 3.)
} else {
thickness
};
let bounds = Bounds {
origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
size: size(self.snap_stroke(width), height),
};
let element_opacity = self.element_opacity();
self.next_frame.scene.insert_primitive(Underline {
order: 0,
pad: 0,
bounds,
content_mask: self.snapped_content_mask(),
color: style.color.unwrap_or_default().opacity(element_opacity),
thickness,
wavy: style.wavy.into(),
});
}
pub fn paint_strikethrough(
&mut self,
origin: Point<Pixels>,
width: Pixels,
style: &StrikethroughStyle,
) {
self.invalidator.debug_assert_paint();
let scale_factor = self.scale_factor();
let height = style.thickness;
let bounds = Bounds {
origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
size: size(self.snap_stroke(width), self.snap_stroke(height)),
};
let opacity = self.element_opacity();
self.next_frame.scene.insert_primitive(Underline {
order: 0,
pad: 0,
bounds,
content_mask: self.snapped_content_mask(),
thickness: self.snap_stroke(style.thickness),
color: style.color.unwrap_or_default().opacity(opacity),
wavy: false.into(),
});
}
pub fn paint_glyph(
&mut self,
origin: Point<Pixels>,
font_id: FontId,
glyph_id: GlyphId,
font_size: Pixels,
color: Hsla,
) -> Result<()> {
self.invalidator.debug_assert_paint();
let element_opacity = self.element_opacity();
let scale_factor = self.scale_factor();
let glyph_origin = origin.scale(scale_factor);
let quantized_origin = Point::new(
round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
/ SUBPIXEL_VARIANTS_X as f32,
round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
/ SUBPIXEL_VARIANTS_Y as f32,
);
let subpixel_variant = Point::new(
(quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
(quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
);
let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
let dilation = self.text_system().glyph_dilation_for_color(color);
let params = RenderGlyphParams {
font_id,
glyph_id,
font_size,
subpixel_variant,
scale_factor,
is_emoji: false,
dilation,
};
let raster_bounds = self.text_system().raster_bounds(¶ms)?;
if !raster_bounds.is_zero() {
let tile = self
.sprite_atlas
.get_or_insert_with(¶ms.clone().into(), &mut || {
let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
Ok(Some((size, Cow::Owned(bytes))))
})?
.expect("Callback above only errors or returns Some");
let bounds = Bounds {
origin: integer_origin + raster_bounds.origin.map(Into::into),
size: tile.bounds.size.map(Into::into),
};
let content_mask = self.snapped_content_mask();
self.next_frame.scene.insert_primitive(MonochromeSprite {
order: 0,
pad: 0,
bounds,
content_mask,
color: color.opacity(element_opacity),
tile,
transformation: TransformationMatrix::unit(),
});
}
Ok(())
}
pub fn paint_emoji(
&mut self,
origin: Point<Pixels>,
font_id: FontId,
glyph_id: GlyphId,
font_size: Pixels,
) -> Result<()> {
self.invalidator.debug_assert_paint();
let scale_factor = self.scale_factor();
let glyph_origin = origin.scale(scale_factor);
let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
let params = RenderGlyphParams {
font_id,
glyph_id,
font_size,
subpixel_variant: Default::default(),
scale_factor,
is_emoji: true,
dilation: 0, };
let raster_bounds = self.text_system().raster_bounds(¶ms)?;
if !raster_bounds.is_zero() {
let tile = self
.sprite_atlas
.get_or_insert_with(¶ms.clone().into(), &mut || {
let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
Ok(Some((size, Cow::Owned(bytes))))
})?
.expect("Callback above only errors or returns Some");
let bounds = Bounds {
origin: integer_origin + raster_bounds.origin.map(Into::into),
size: tile.bounds.size.map(Into::into),
};
let content_mask = self.snapped_content_mask();
let opacity = self.element_opacity();
self.next_frame.scene.insert_primitive(PolychromeSprite {
order: 0,
pad: 0,
grayscale: false.into(),
bounds,
corner_radii: Default::default(),
content_mask,
tile,
opacity,
});
}
Ok(())
}
pub fn paint_svg(
&mut self,
bounds: Bounds<Pixels>,
path: SharedString,
transformation: TransformationMatrix,
color: Hsla,
cx: &App,
) -> Result<()> {
self.paint_svg_from(bounds, path, None, transformation, color, cx)
}
pub(crate) fn paint_svg_from(
&mut self,
bounds: Bounds<Pixels>,
path: SharedString,
data: Option<&[u8]>,
transformation: TransformationMatrix,
color: Hsla,
cx: &App,
) -> Result<()> {
self.invalidator.debug_assert_paint();
let element_opacity = self.element_opacity();
let bounds = self.snap_bounds(bounds);
let params = RenderSvgParams {
path,
size: bounds.size.map(|pixels| {
DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
}),
};
let Some(tile) =
self.sprite_atlas
.get_or_insert_with(¶ms.clone().into(), &mut || {
let Some((size, bytes)) = cx.svg_renderer.render(¶ms, data)? else {
return Ok(None);
};
Ok(Some((size, Cow::Owned(bytes))))
})?
else {
return Ok(());
};
let content_mask = self.snapped_content_mask();
let svg_bounds = Bounds {
origin: bounds.center()
- Point::new(
ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
),
size: tile
.bounds
.size
.map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
};
let final_bounds = svg_bounds
.map_origin(|origin| ScaledPixels(round_half_toward_zero(origin.0)))
.map_size(|size| size.ceil());
self.next_frame.scene.insert_primitive(MonochromeSprite {
order: 0,
pad: 0,
bounds: final_bounds,
content_mask,
color: color.opacity(element_opacity),
tile,
transformation,
});
Ok(())
}
pub fn paint_image(
&mut self,
bounds: Bounds<Pixels>,
image_bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
data: Arc<RenderImage>,
frame_index: usize,
grayscale: bool,
) -> Result<()> {
self.invalidator.debug_assert_paint();
let visible_bounds = bounds.intersect(&image_bounds);
if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
return Ok(());
}
if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
return Ok(());
}
let params = RenderImageParams {
image_id: data.id,
frame_index,
};
let Some(bytes) = data.as_bytes(frame_index) else {
return Ok(());
};
let image_size = data.size(frame_index);
let tile = self
.sprite_atlas
.get_or_insert_with(¶ms.into(), &mut || {
Ok(Some((image_size, Cow::Borrowed(bytes))))
})?
.expect("Callback above only returns Some");
let visible_bounds_snapped = self.snap_bounds(visible_bounds);
let sub_tile = if visible_bounds == image_bounds {
tile
} else {
let x_offset_ratio =
(visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
let y_offset_ratio =
(visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
let width_ratio = visible_bounds.size.width / image_bounds.size.width;
let height_ratio = visible_bounds.size.height / image_bounds.size.height;
let tile_origin_x = tile.bounds.origin.x.0;
let tile_origin_y = tile.bounds.origin.y.0;
let tile_width = tile.bounds.size.width.0;
let tile_height = tile.bounds.size.height.0;
let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
let sub_width = (width_ratio * tile_width as f32).round() as i32;
let sub_height = (height_ratio * tile_height as f32).round() as i32;
let max_x = tile_origin_x + tile_width;
let max_y = tile_origin_y + tile_height;
let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
AtlasTile {
bounds: Bounds {
origin: point(
DevicePixels(clamped_origin_x),
DevicePixels(clamped_origin_y),
),
size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
},
..tile
}
};
let content_mask = self.snapped_content_mask();
let corner_radii = corner_radii
.clamp_radii_for_quad_size(visible_bounds.size)
.scale(self.scale_factor());
let opacity = self.element_opacity();
self.next_frame.scene.insert_primitive(PolychromeSprite {
order: 0,
pad: 0,
grayscale: grayscale.into(),
bounds: visible_bounds_snapped,
content_mask,
corner_radii,
tile: sub_tile,
opacity,
});
Ok(())
}
#[cfg(target_os = "macos")]
pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
use crate::PaintSurface;
self.invalidator.debug_assert_paint();
let bounds = self.snap_bounds(bounds);
let content_mask = self.snapped_content_mask();
self.next_frame.scene.insert_primitive(PaintSurface {
order: 0,
bounds,
content_mask,
image_buffer,
});
}
pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
for frame_index in 0..data.frame_count() {
let params = RenderImageParams {
image_id: data.id,
frame_index,
};
self.sprite_atlas.remove(¶ms.clone().into());
}
Ok(())
}
#[must_use]
pub fn request_layout(
&mut self,
style: Style,
children: impl IntoIterator<Item = LayoutId>,
cx: &mut App,
) -> LayoutId {
self.invalidator.debug_assert_prepaint();
cx.layout_id_buffer.clear();
cx.layout_id_buffer.extend(children);
let rem_size = self.rem_size();
let scale_factor = self.scale_factor();
self.layout_engine.as_mut().unwrap().request_layout(
style,
rem_size,
scale_factor,
&cx.layout_id_buffer,
)
}
pub fn request_measured_layout<
F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
+ 'static,
>(
&mut self,
style: Style,
measure: F,
) -> LayoutId {
self.invalidator.debug_assert_prepaint();
let rem_size = self.rem_size();
let scale_factor = self.scale_factor();
self.layout_engine
.as_mut()
.unwrap()
.request_measured_layout(style, rem_size, scale_factor, measure)
}
pub fn compute_layout(
&mut self,
layout_id: LayoutId,
available_space: Size<AvailableSpace>,
cx: &mut App,
) {
self.invalidator.debug_assert_prepaint();
let mut layout_engine = self.layout_engine.take().unwrap();
layout_engine.compute_layout(layout_id, available_space, self, cx);
self.layout_engine = Some(layout_engine);
}
pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
self.invalidator.debug_assert_prepaint();
let scale_factor = self.scale_factor();
let mut bounds = self
.layout_engine
.as_mut()
.unwrap()
.layout_bounds(layout_id, scale_factor)
.map(Into::into);
bounds.origin += self.pixel_snap_point(self.element_offset());
bounds
}
pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
self.invalidator.debug_assert_prepaint();
let content_mask = self.content_mask();
let mut id = self.next_hitbox_id;
self.next_hitbox_id = self.next_hitbox_id.next();
let hitbox = Hitbox {
id,
bounds,
content_mask,
behavior,
};
self.next_frame.hitboxes.push(hitbox.clone());
hitbox
}
pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
self.invalidator.debug_assert_paint();
self.next_frame.window_control_hitboxes.push((area, hitbox));
}
pub fn set_key_context(&mut self, context: KeyContext) {
self.invalidator.debug_assert_paint();
self.next_frame.dispatch_tree.set_key_context(context);
}
pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
self.invalidator.debug_assert_prepaint();
if focus_handle.is_focused(self) {
self.next_frame.focus = Some(focus_handle.id);
}
self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
}
pub fn set_view_id(&mut self, view_id: EntityId) {
self.invalidator.debug_assert_prepaint();
self.next_frame.dispatch_tree.set_view_id(view_id);
}
pub fn current_view(&self) -> EntityId {
self.invalidator.debug_assert_paint_or_prepaint();
self.rendered_entity_stack.last().copied().unwrap()
}
pub(crate) fn with_rendered_view<R>(
&mut self,
id: EntityId,
f: impl FnOnce(&mut Self) -> R,
) -> R {
self.rendered_entity_stack.push(id);
let result = f(self);
self.rendered_entity_stack.pop();
result
}
pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
where
F: FnOnce(&mut Self) -> R,
{
if let Some(image_cache) = image_cache {
self.image_cache_stack.push(image_cache);
let result = f(self);
self.image_cache_stack.pop();
result
} else {
f(self)
}
}
pub fn handle_input(
&mut self,
focus_handle: &FocusHandle,
input_handler: impl InputHandler,
cx: &App,
) {
self.invalidator.debug_assert_paint();
if focus_handle.is_focused(self) {
let cx = self.to_async(cx);
self.next_frame
.input_handlers
.push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
}
}
pub fn on_mouse_event<Event: MouseEvent>(
&mut self,
mut handler: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
) {
self.invalidator.debug_assert_paint();
self.next_frame.mouse_listeners.push(Some(Box::new(
move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
if let Some(event) = event.downcast_ref() {
handler(event, phase, window, cx)
}
},
)));
}
pub fn on_key_event<Event: KeyEvent>(
&mut self,
listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
) {
self.invalidator.debug_assert_paint();
self.next_frame.dispatch_tree.on_key_event(Rc::new(
move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
if let Some(event) = event.downcast_ref::<Event>() {
listener(event, phase, window, cx)
}
},
));
}
pub fn on_modifiers_changed(
&mut self,
listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
) {
self.invalidator.debug_assert_paint();
self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
listener(event, window, cx)
},
));
}
pub fn on_focus_in(
&mut self,
handle: &FocusHandle,
cx: &mut App,
mut listener: impl FnMut(&mut Window, &mut App) + 'static,
) -> Subscription {
let focus_id = handle.id;
let (subscription, activate) =
self.new_focus_listener(Box::new(move |event, window, cx| {
if event.is_focus_in(focus_id) {
listener(window, cx);
}
true
}));
cx.defer(move |_| activate());
subscription
}
pub fn on_focus_out(
&mut self,
handle: &FocusHandle,
cx: &mut App,
mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
) -> Subscription {
let focus_id = handle.id;
let (subscription, activate) =
self.new_focus_listener(Box::new(move |event, window, cx| {
if let Some(blurred_id) = event.previous_focus_path.last().copied()
&& event.is_focus_out(focus_id)
{
let event = FocusOutEvent {
blurred: WeakFocusHandle {
id: blurred_id,
handles: Arc::downgrade(&cx.focus_handles),
},
};
listener(event, window, cx)
}
true
}));
cx.defer(move |_| activate());
subscription
}
fn reset_cursor_style(&self, cx: &mut App) {
if self.is_window_hovered() {
let style = self
.rendered_frame
.cursor_style(self)
.unwrap_or(CursorStyle::Arrow);
self.platform_window.set_cursor_style(style);
cx.platform.set_cursor_style(style);
}
}
pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
let keystroke = keystroke.with_simulated_ime();
let result = self.dispatch_event(
PlatformInput::KeyDown(KeyDownEvent {
keystroke: keystroke.clone(),
is_held: false,
prefer_character_input: false,
}),
cx,
);
if !result.propagate {
return true;
}
if let Some(input) = keystroke.key_char
&& let Some(mut input_handler) = self.platform_window.take_input_handler()
{
input_handler.dispatch_input(&input, self, cx);
self.platform_window.set_input_handler(input_handler);
return true;
}
false
}
pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
self.highest_precedence_binding_for_action(action)
.map(|binding| {
binding
.keystrokes()
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(" ")
})
.unwrap_or_else(|| action.name().to_string())
}
#[profiling::function]
pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
#[cfg(feature = "input-latency-histogram")]
let dispatch_time = Instant::now();
let update_count_before = self.invalidator.update_count();
cx.propagate_event = true;
self.default_prevented = false;
let event = match event {
PlatformInput::MouseMove(mouse_move) => {
self.mouse_position = mouse_move.position;
self.modifiers = mouse_move.modifiers;
PlatformInput::MouseMove(mouse_move)
}
PlatformInput::MouseDown(mouse_down) => {
self.mouse_position = mouse_down.position;
self.modifiers = mouse_down.modifiers;
PlatformInput::MouseDown(mouse_down)
}
PlatformInput::MouseUp(mouse_up) => {
self.mouse_position = mouse_up.position;
self.modifiers = mouse_up.modifiers;
PlatformInput::MouseUp(mouse_up)
}
PlatformInput::MouseExited(mouse_exited) => {
self.modifiers = mouse_exited.modifiers;
PlatformInput::MouseExited(mouse_exited)
}
PlatformInput::ModifiersChanged(modifiers_changed) => {
self.modifiers = modifiers_changed.modifiers;
self.capslock = modifiers_changed.capslock;
PlatformInput::ModifiersChanged(modifiers_changed)
}
PlatformInput::ScrollWheel(scroll_wheel) => {
self.mouse_position = scroll_wheel.position;
self.modifiers = scroll_wheel.modifiers;
PlatformInput::ScrollWheel(scroll_wheel)
}
PlatformInput::Pinch(pinch) => {
self.mouse_position = pinch.position;
self.modifiers = pinch.modifiers;
PlatformInput::Pinch(pinch)
}
PlatformInput::FileDrop(file_drop) => match file_drop {
FileDropEvent::Entered { position, paths } => {
self.mouse_position = position;
if cx.active_drag.is_none() {
cx.active_drag = Some(AnyDrag {
value: Arc::new(paths.clone()),
view: cx.new(|_| paths).into(),
cursor_offset: position,
cursor_style: None,
});
}
PlatformInput::MouseMove(MouseMoveEvent {
position,
pressed_button: Some(MouseButton::Left),
modifiers: Modifiers::default(),
})
}
FileDropEvent::Pending { position } => {
self.mouse_position = position;
PlatformInput::MouseMove(MouseMoveEvent {
position,
pressed_button: Some(MouseButton::Left),
modifiers: Modifiers::default(),
})
}
FileDropEvent::Submit { position } => {
cx.activate(true);
self.mouse_position = position;
PlatformInput::MouseUp(MouseUpEvent {
button: MouseButton::Left,
position,
modifiers: Modifiers::default(),
click_count: 1,
})
}
FileDropEvent::Exited => {
cx.active_drag.take();
PlatformInput::FileDrop(FileDropEvent::Exited)
}
},
PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
};
if let Some(any_mouse_event) = event.mouse_event() {
self.dispatch_mouse_event(any_mouse_event, cx);
} else if let Some(any_key_event) = event.keyboard_event() {
self.dispatch_key_event(any_key_event, cx);
}
if self.invalidator.update_count() > update_count_before {
self.input_rate_tracker.borrow_mut().record_input();
#[cfg(feature = "input-latency-histogram")]
if self.invalidator.not_drawing() {
self.input_latency_tracker.record_input(dispatch_time);
} else {
self.input_latency_tracker.record_mid_draw_input();
}
}
DispatchEventResult {
propagate: cx.propagate_event,
default_prevented: self.default_prevented,
}
}
fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
self.last_input_was_keyboard.set(false);
let hit_test = self.rendered_frame.hit_test(self.mouse_position());
if hit_test != self.mouse_hit_test {
self.mouse_hit_test = hit_test;
self.reset_cursor_style(cx);
}
#[cfg(any(feature = "inspector", debug_assertions))]
if self.is_inspector_picking(cx) {
self.handle_inspector_mouse_event(event, cx);
return;
}
let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
for listener in &mut mouse_listeners {
let listener = listener.as_mut().unwrap();
listener(event, DispatchPhase::Capture, self, cx);
if !cx.propagate_event {
break;
}
}
if cx.propagate_event {
for listener in mouse_listeners.iter_mut().rev() {
let listener = listener.as_mut().unwrap();
listener(event, DispatchPhase::Bubble, self, cx);
if !cx.propagate_event {
break;
}
}
}
self.rendered_frame.mouse_listeners = mouse_listeners;
if cx.has_active_drag() {
if event.is::<MouseMoveEvent>() {
self.refresh();
} else if event.is::<MouseUpEvent>() {
cx.active_drag = None;
self.refresh();
}
}
if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
self.captured_hitbox = None;
}
}
fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
self.last_input_was_keyboard.set(true);
if self.invalidator.is_dirty() {
self.draw(cx).clear();
}
let node_id = self.focus_node_id_in_rendered_frame(self.focus);
let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
let mut keystroke: Option<Keystroke> = None;
if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
if event.modifiers.number_of_modifiers() == 0
&& self.pending_modifier.modifiers.number_of_modifiers() == 1
&& !self.pending_modifier.saw_other_input
{
let key = match self.pending_modifier.modifiers {
modifiers if modifiers.shift => Some("shift"),
modifiers if modifiers.control => Some("control"),
modifiers if modifiers.alt => Some("alt"),
modifiers if modifiers.platform => Some("platform"),
modifiers if modifiers.function => Some("function"),
_ => None,
};
if let Some(key) = key {
keystroke = Some(Keystroke {
key: key.to_string(),
key_char: None,
modifiers: Modifiers::default(),
});
}
}
if self.pending_modifier.modifiers.number_of_modifiers() == 0
&& event.modifiers.number_of_modifiers() == 1
{
self.pending_modifier.saw_other_input = false
} else if event.modifiers.number_of_modifiers() > 1 {
self.pending_modifier.saw_other_input = true
}
self.pending_modifier.modifiers = event.modifiers
} else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
self.pending_modifier.saw_other_input = true;
keystroke = Some(key_down_event.keystroke.clone());
}
let Some(keystroke) = keystroke else {
self.finish_dispatch_key_event(
event,
None,
InputPreference::KeyBindings,
dispatch_path,
self.context_stack(),
cx,
);
return;
};
let input_preference = self.input_preference(event, cx);
cx.propagate_event = true;
self.dispatch_keystroke_interceptors(
&keystroke,
input_preference,
self.context_stack(),
cx,
);
if !cx.propagate_event {
self.finish_dispatch_key_event(
event,
Some(&keystroke),
input_preference,
dispatch_path,
self.context_stack(),
cx,
);
return;
}
let mut currently_pending = self.pending_input.take().unwrap_or_default();
if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
currently_pending = PendingInput::default();
}
let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
currently_pending.keystrokes,
keystroke.clone(),
&dispatch_path,
);
if !match_result.to_replay.is_empty() {
self.replay_pending_input(match_result.to_replay, cx);
cx.propagate_event = true;
}
if !match_result.pending.is_empty() {
let previous_timeout = currently_pending.timeout.take();
currently_pending.keystrokes = match_result.pending;
currently_pending.focus = self.focus;
currently_pending.timeout = match previous_timeout {
Some(mut timeout) if timeout.is_paused() => {
timeout.reset_duration(PENDING_INPUT_TIMEOUT);
Some(timeout)
}
previous_timeout => {
drop(previous_timeout);
Some(self.new_pending_input_timeout(PENDING_INPUT_TIMEOUT, cx))
}
};
self.pending_input = Some(currently_pending);
self.pending_input_changed(cx);
cx.propagate_event = false;
return;
}
let input_preference = self.input_preference(event, cx);
if input_preference == InputPreference::KeyBindings {
for binding in match_result.bindings {
self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
if !cx.propagate_event {
self.dispatch_keystroke_observers(
&keystroke,
input_preference,
Some(binding.action.as_ref()),
match_result.context_stack,
cx,
);
self.pending_input_changed(cx);
return;
}
}
}
self.finish_dispatch_key_event(
event,
Some(&keystroke),
input_preference,
dispatch_path,
match_result.context_stack,
cx,
);
self.pending_input_changed(cx);
}
fn input_preference(&mut self, event: &dyn Any, cx: &mut App) -> InputPreference {
let prefer_character_input = event
.downcast_ref::<KeyDownEvent>()
.is_some_and(|key_down_event| key_down_event.prefer_character_input);
if !prefer_character_input {
return InputPreference::KeyBindings;
}
let Some(mut input_handler) = self.platform_window.take_input_handler() else {
return InputPreference::KeyBindings;
};
let accepts_text_input = input_handler.accepts_text_input(self, cx);
self.platform_window.set_input_handler(input_handler);
if accepts_text_input {
InputPreference::CharacterInput
} else {
InputPreference::KeyBindings
}
}
fn new_pending_input_timeout(&self, duration: Duration, cx: &App) -> PendingInputTimeout {
let (started_at, task) = self.start_pending_input_timeout(duration, cx);
PendingInputTimeout {
duration,
remaining: duration,
state: PendingInputTimeoutState::Running { started_at, task },
}
}
fn start_pending_input_timeout(&self, remaining: Duration, cx: &App) -> (Instant, Task<()>) {
let started_at = cx.background_executor().now();
let task = self.spawn(cx, async move |cx| {
cx.background_executor.timer(remaining).await;
cx.update(move |window, cx| {
let Some(currently_pending) = window
.pending_input
.take()
.filter(|pending| pending.focus == window.focus)
else {
return;
};
let node_id = window.focus_node_id_in_rendered_frame(window.focus);
let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
let to_replay = window
.rendered_frame
.dispatch_tree
.flush_dispatch(currently_pending.keystrokes, &dispatch_path);
window.pending_input_changed(cx);
window.replay_pending_input(to_replay, cx)
})
.log_err();
});
(started_at, task)
}
fn finish_dispatch_key_event(
&mut self,
event: &dyn Any,
recognized_keystroke: Option<&Keystroke>,
input_preference: InputPreference,
dispatch_path: SmallVec<[DispatchNodeId; 32]>,
context_stack: Vec<KeyContext>,
cx: &mut App,
) {
self.dispatch_key_down_up_event(event, &dispatch_path, cx);
if !cx.propagate_event {
return;
}
self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
if !cx.propagate_event {
return;
}
if let Some(keystroke) = recognized_keystroke {
self.dispatch_keystroke_observers(keystroke, input_preference, None, context_stack, cx);
}
}
fn pending_input_changed(&mut self, cx: &mut App) {
self.pending_input_observers
.clone()
.retain(&(), |callback| callback(self, cx));
}
fn dispatch_key_down_up_event(
&mut self,
event: &dyn Any,
dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
cx: &mut App,
) {
for node_id in dispatch_path {
let node = self.rendered_frame.dispatch_tree.node(*node_id);
for key_listener in node.key_listeners.clone() {
key_listener(event, DispatchPhase::Capture, self, cx);
if !cx.propagate_event {
return;
}
}
}
for node_id in dispatch_path.iter().rev() {
let node = self.rendered_frame.dispatch_tree.node(*node_id);
for key_listener in node.key_listeners.clone() {
key_listener(event, DispatchPhase::Bubble, self, cx);
if !cx.propagate_event {
return;
}
}
}
}
fn dispatch_modifiers_changed_event(
&mut self,
event: &dyn Any,
dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
cx: &mut App,
) {
let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
return;
};
for node_id in dispatch_path.iter().rev() {
let node = self.rendered_frame.dispatch_tree.node(*node_id);
for listener in node.modifiers_changed_listeners.clone() {
listener(event, self, cx);
if !cx.propagate_event {
return;
}
}
}
}
pub fn has_pending_keystrokes(&self) -> bool {
self.pending_input().is_some()
}
#[cfg(test)]
pub(crate) fn pending_input_is_none(&self) -> bool {
self.pending_input.is_none()
}
fn defer_pending_input_changed(&self, cx: &mut App) {
self.defer(cx, |window, cx| {
window.pending_input_changed(cx);
});
}
pub(crate) fn clear_pending_keystrokes(&mut self, cx: &mut App) {
if self.pending_input.take().is_some() {
self.defer_pending_input_changed(cx);
}
}
pub fn pending_input(&self) -> Option<PendingInputStatus<'_>> {
self.pending_input
.as_ref()
.filter(|pending_input| pending_input.focus == self.focus)
.map(|pending_input| PendingInputStatus {
keystrokes: pending_input.keystrokes.as_slice(),
timeout: pending_input
.timeout
.as_ref()
.map(PendingInputTimeout::status),
})
}
pub fn set_pending_input_timeout_paused<T: 'static>(
&mut self,
owner: &Entity<T>,
paused: bool,
cx: &mut App,
) -> bool {
let owner_id = owner.entity_id();
if !paused {
return self.resume_pending_input_timeout(owner_id, cx);
}
let timeout = self
.pending_input
.as_ref()
.filter(|pending_input| pending_input.focus == self.focus)
.and_then(|pending_input| pending_input.timeout.as_ref());
let Some(timeout) = timeout else {
return false;
};
if timeout.is_paused() {
return false;
}
let release_subscription = self.observe_release(owner, cx, move |_, window, cx| {
window.resume_pending_input_timeout(owner_id, cx);
});
let now = cx.background_executor().now();
let changed = self
.pending_input
.as_mut()
.filter(|pending_input| pending_input.focus == self.focus)
.and_then(|pending_input| pending_input.timeout.as_mut())
.is_some_and(|timeout| {
timeout.pause(
PendingInputTimeoutPause {
owner_id,
_release_subscription: release_subscription,
},
now,
)
});
if changed {
self.defer_pending_input_changed(cx);
}
changed
}
fn resume_pending_input_timeout(&mut self, owner_id: EntityId, cx: &mut App) -> bool {
let Some(remaining) = self
.pending_input
.as_ref()
.filter(|pending_input| pending_input.focus == self.focus)
.and_then(|pending_input| pending_input.timeout.as_ref())
.filter(|timeout| timeout.pause_owner_id() == Some(owner_id))
.map(|timeout| timeout.remaining)
else {
return false;
};
let (started_at, task) = self.start_pending_input_timeout(remaining, cx);
let changed = self
.pending_input
.as_mut()
.filter(|pending_input| pending_input.focus == self.focus)
.and_then(|pending_input| pending_input.timeout.as_mut())
.is_some_and(|timeout| timeout.resume(owner_id, started_at, task));
if changed {
self.defer_pending_input_changed(cx);
}
changed
}
pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
self.pending_input()
.map(|pending_input| pending_input.keystrokes())
}
fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
let node_id = self.focus_node_id_in_rendered_frame(self.focus);
let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
'replay: for replay in replays {
let event = KeyDownEvent {
keystroke: replay.keystroke.clone(),
is_held: false,
prefer_character_input: true,
};
cx.propagate_event = true;
for binding in replay.bindings {
self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
if !cx.propagate_event {
self.dispatch_keystroke_observers(
&replay.keystroke,
InputPreference::KeyBindings,
Some(binding.action.as_ref()),
Vec::default(),
cx,
);
continue 'replay;
}
}
self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
if !cx.propagate_event {
continue 'replay;
}
if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
&& let Some(mut input_handler) = self.platform_window.take_input_handler()
{
input_handler.dispatch_input(&input, self, cx);
self.platform_window.set_input_handler(input_handler)
}
}
}
fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
focus_id
.and_then(|focus_id| {
self.rendered_frame
.dispatch_tree
.focusable_node_id(focus_id)
})
.unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
}
fn dispatch_action_on_node(
&mut self,
node_id: DispatchNodeId,
action: &dyn Action,
cx: &mut App,
) {
let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
cx.propagate_event = true;
if let Some(mut global_listeners) = cx
.global_action_listeners
.remove(&action.as_any().type_id())
{
for listener in &global_listeners {
listener(action.as_any(), DispatchPhase::Capture, cx);
if !cx.propagate_event {
break;
}
}
global_listeners.extend(
cx.global_action_listeners
.remove(&action.as_any().type_id())
.unwrap_or_default(),
);
cx.global_action_listeners
.insert(action.as_any().type_id(), global_listeners);
}
if !cx.propagate_event {
return;
}
for node_id in &dispatch_path {
let node = self.rendered_frame.dispatch_tree.node(*node_id);
for DispatchActionListener {
action_type,
listener,
} in node.action_listeners.clone()
{
let any_action = action.as_any();
if action_type == any_action.type_id() {
listener(any_action, DispatchPhase::Capture, self, cx);
if !cx.propagate_event {
return;
}
}
}
}
for node_id in dispatch_path.iter().rev() {
let node = self.rendered_frame.dispatch_tree.node(*node_id);
for DispatchActionListener {
action_type,
listener,
} in node.action_listeners.clone()
{
let any_action = action.as_any();
if action_type == any_action.type_id() {
cx.propagate_event = false; listener(any_action, DispatchPhase::Bubble, self, cx);
if !cx.propagate_event {
return;
}
}
}
}
if let Some(mut global_listeners) = cx
.global_action_listeners
.remove(&action.as_any().type_id())
{
for listener in global_listeners.iter().rev() {
cx.propagate_event = false;
listener(action.as_any(), DispatchPhase::Bubble, cx);
if !cx.propagate_event {
break;
}
}
global_listeners.extend(
cx.global_action_listeners
.remove(&action.as_any().type_id())
.unwrap_or_default(),
);
cx.global_action_listeners
.insert(action.as_any().type_id(), global_listeners);
}
}
pub fn observe_global<G: Global>(
&mut self,
cx: &mut App,
f: impl Fn(&mut Window, &mut App) + 'static,
) -> Subscription {
let window_handle = self.handle;
let (subscription, activate) = cx.global_observers.insert(
TypeId::of::<G>(),
Box::new(move |cx| {
window_handle
.update(cx, |_, window, cx| f(window, cx))
.is_ok()
}),
);
cx.defer(move |_| activate());
subscription
}
pub fn activate_window(&self) {
self.platform_window.activate();
}
pub fn request_attention(&self) {
self.platform_window.request_attention();
}
pub fn minimize_window(&self) {
self.platform_window.minimize();
}
pub fn show_window(&self) {
self.platform_window.show();
}
pub fn hide_window(&self) {
self.platform_window.hide();
}
pub fn is_window_visible(&self) -> bool {
self.platform_window.is_visible()
}
pub fn set_mouse_passthrough(&self, passthrough: bool) {
self.platform_window.set_mouse_passthrough(passthrough);
}
pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
self.platform_window.set_input_region(region);
}
pub fn toggle_fullscreen(&self) {
self.platform_window.toggle_fullscreen();
}
pub fn toggle_simple_fullscreen(&self) {
self.platform_window.toggle_simple_fullscreen();
}
pub fn set_progress_bar(&self, state: ProgressBarState) {
self.platform_window.set_progress_bar(state);
}
pub fn window_state(&self) -> WindowState {
let bounds = self.platform_window.window_bounds();
let display_id = self.platform_window.display().map(|d| d.id());
let fullscreen = self.platform_window.is_fullscreen();
WindowState {
bounds,
display_id,
fullscreen,
}
}
pub fn restore_window_state(&self, state: &WindowState) {
let is_fullscreen = self.platform_window.is_fullscreen();
if state.fullscreen != is_fullscreen {
self.platform_window.toggle_fullscreen();
}
}
pub fn invalidate_character_coordinates(&self) {
self.on_next_frame(|window, cx| {
if let Some(mut input_handler) = window.platform_window.take_input_handler() {
if let Some(bounds) = input_handler.selected_bounds(window, cx) {
window.platform_window.update_ime_position(bounds);
}
window.platform_window.set_input_handler(input_handler);
}
});
}
pub fn prompt<T>(
&mut self,
level: PromptLevel,
message: &str,
detail: Option<&str>,
answers: &[T],
cx: &mut App,
) -> oneshot::Receiver<usize>
where
T: Clone + Into<PromptButton>,
{
let prompt_builder = cx.prompt_builder.take();
let Some(prompt_builder) = prompt_builder else {
unreachable!("Re-entrant window prompting is not supported by GPUI");
};
let answers = answers
.iter()
.map(|answer| answer.clone().into())
.collect::<Vec<_>>();
let receiver = match &prompt_builder {
PromptBuilder::Default => self
.platform_window
.prompt(level, message, detail, &answers)
.unwrap_or_else(|| {
self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
}),
PromptBuilder::Custom(_) => {
self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
}
};
cx.prompt_builder = Some(prompt_builder);
receiver
}
fn build_custom_prompt(
&mut self,
prompt_builder: &PromptBuilder,
level: PromptLevel,
message: &str,
detail: Option<&str>,
answers: &[PromptButton],
cx: &mut App,
) -> oneshot::Receiver<usize> {
let (sender, receiver) = oneshot::channel();
let handle = PromptHandle::new(sender);
let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
self.prompt = Some(handle);
receiver
}
pub fn has_active_prompt(&self) -> bool {
self.prompt.is_some()
}
pub fn context_stack(&self) -> Vec<KeyContext> {
let node_id = self.focus_node_id_in_rendered_frame(self.focus);
let dispatch_tree = &self.rendered_frame.dispatch_tree;
dispatch_tree
.dispatch_path(node_id)
.iter()
.filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
.collect()
}
pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
let node_id = self.focus_node_id_in_rendered_frame(self.focus);
let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
for action_type in cx.global_action_listeners.keys() {
if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
let action = cx.actions.build_action_type(action_type).ok();
if let Some(action) = action {
actions.insert(ix, action);
}
}
}
actions
}
pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
self.rendered_frame
.dispatch_tree
.bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
}
pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
self.rendered_frame
.dispatch_tree
.highest_precedence_binding_for_action(
action,
&self.rendered_frame.dispatch_tree.context_stack,
)
}
pub fn bindings_for_action_in_context(
&self,
action: &dyn Action,
context: KeyContext,
) -> Vec<KeyBinding> {
let dispatch_tree = &self.rendered_frame.dispatch_tree;
dispatch_tree.bindings_for_action(action, &[context])
}
pub fn highest_precedence_binding_for_action_in_context(
&self,
action: &dyn Action,
context: KeyContext,
) -> Option<KeyBinding> {
let dispatch_tree = &self.rendered_frame.dispatch_tree;
dispatch_tree.highest_precedence_binding_for_action(action, &[context])
}
pub fn bindings_for_action_in(
&self,
action: &dyn Action,
focus_handle: &FocusHandle,
) -> Vec<KeyBinding> {
let dispatch_tree = &self.rendered_frame.dispatch_tree;
let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
return vec![];
};
dispatch_tree.bindings_for_action(action, &context_stack)
}
pub fn highest_precedence_binding_for_action_in(
&self,
action: &dyn Action,
focus_handle: &FocusHandle,
) -> Option<KeyBinding> {
let dispatch_tree = &self.rendered_frame.dispatch_tree;
let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
}
fn context_stack_for_focus_handle(
&self,
focus_handle: &FocusHandle,
) -> Option<Vec<KeyContext>> {
let dispatch_tree = &self.rendered_frame.dispatch_tree;
let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
let context_stack: Vec<_> = dispatch_tree
.dispatch_path(node_id)
.into_iter()
.filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
.collect();
Some(context_stack)
}
pub fn listener_for<V: Render, E>(
&self,
view: &Entity<V>,
f: impl Fn(&mut V, &E, &mut Window, &mut Context<V>) + 'static,
) -> impl Fn(&E, &mut Window, &mut App) + 'static {
let view = view.downgrade();
move |e: &E, window: &mut Window, cx: &mut App| {
view.update(cx, |view, cx| f(view, e, window, cx)).ok();
}
}
pub fn handler_for<V: Render, Callback: Fn(&mut V, &mut Window, &mut Context<V>) + 'static>(
&self,
view: &Entity<V>,
f: Callback,
) -> impl Fn(&mut Window, &mut App) + use<V, Callback> {
let view = view.downgrade();
move |window: &mut Window, cx: &mut App| {
view.update(cx, |view, cx| f(view, window, cx)).ok();
}
}
pub fn on_window_should_close(
&self,
cx: &App,
f: impl Fn(&mut Window, &mut App) -> bool + 'static,
) {
let mut cx = self.to_async(cx);
self.platform_window.on_should_close(Box::new(move || {
cx.update(|window, cx| f(window, cx)).unwrap_or(true)
}))
}
pub fn on_action(
&mut self,
action_type: TypeId,
listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
) {
self.next_frame
.dispatch_tree
.on_action(action_type, Rc::new(listener));
}
pub fn on_action_when(
&mut self,
condition: bool,
action_type: TypeId,
listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
) {
if condition {
self.next_frame
.dispatch_tree
.on_action(action_type, Rc::new(listener));
}
}
pub fn gpu_specs(&self) -> Option<GpuSpecs> {
self.platform_window.gpu_specs()
}
pub fn titlebar_double_click(&self) {
self.platform_window.titlebar_double_click();
}
pub fn window_title(&self) -> String {
self.platform_window.get_title()
}
pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
self.platform_window.tabbed_windows()
}
pub fn tab_bar_visible(&self) -> bool {
self.platform_window.tab_bar_visible()
}
pub fn merge_all_windows(&self) {
self.platform_window.merge_all_windows()
}
pub fn move_tab_to_new_window(&self) {
self.platform_window.move_tab_to_new_window()
}
pub fn toggle_window_tab_overview(&self) {
self.platform_window.toggle_window_tab_overview()
}
pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
self.platform_window
.set_tabbing_identifier(tabbing_identifier)
}
pub fn play_system_bell(&self) {
self.platform_window.play_system_bell()
}
pub fn is_a11y_enabled(&self) -> bool {
self.a11y.is_enabled()
}
pub fn debug_a11y_tree_json(&self) -> Option<String> {
self.a11y.debug_tree_json()
}
pub fn on_a11y_action(
&mut self,
node_id: accesskit::NodeId,
action: accesskit::Action,
listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
) {
self.a11y
.action_listeners
.entry(node_id)
.or_default()
.push((action, Box::new(listener)));
}
#[cfg(not(target_family = "wasm"))]
pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
let action_data = request.data.as_ref();
let mut matched = false;
for (action, listener) in &mut listeners {
if *action == request.action {
listener(action_data, self, cx);
matched = true;
}
}
self.a11y
.action_listeners
.insert(request.target_node, listeners);
if matched {
return;
}
}
match request.action {
accesskit::Action::Click => {
if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
let center = bounds.center();
self.dispatch_event(
PlatformInput::MouseDown(crate::MouseDownEvent {
button: MouseButton::Left,
position: center,
modifiers: Modifiers::default(),
click_count: 1,
first_mouse: false,
}),
cx,
);
self.dispatch_event(
PlatformInput::MouseUp(MouseUpEvent {
button: MouseButton::Left,
position: center,
modifiers: Modifiers::default(),
click_count: 1,
}),
cx,
);
}
}
accesskit::Action::Focus => {
if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
&& let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
{
self.focus(&handle);
}
}
accesskit::Action::Blur => self.blur(cx),
_ => {
log::debug!(
"Unhandled a11y action: {:?} on {:?}",
request.action,
request.target_node
);
}
}
}
#[cfg(any(feature = "inspector", debug_assertions))]
pub fn toggle_inspector(&mut self, cx: &mut App) {
self.inspector = match self.inspector {
None => Some(cx.new(|_| Inspector::new())),
Some(_) => None,
};
self.refresh();
}
pub fn is_inspector_picking(&self, _cx: &App) -> bool {
#[cfg(any(feature = "inspector", debug_assertions))]
{
if let Some(inspector) = &self.inspector {
return inspector.read(_cx).is_picking();
}
}
false
}
#[cfg(any(feature = "inspector", debug_assertions))]
pub fn with_inspector_state<T: 'static, R>(
&mut self,
_inspector_id: Option<&crate::InspectorElementId>,
cx: &mut App,
f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
) -> R {
if let Some(inspector_id) = _inspector_id
&& let Some(inspector) = &self.inspector
{
let inspector = inspector.clone();
let active_element_id = inspector.read(cx).active_element_id();
if Some(inspector_id) == active_element_id {
return inspector.update(cx, |inspector, _cx| {
inspector.with_active_element_state(self, f)
});
}
}
f(&mut None, self)
}
#[cfg(any(feature = "inspector", debug_assertions))]
pub(crate) fn build_inspector_element_id(
&mut self,
path: crate::InspectorElementPath,
) -> crate::InspectorElementId {
self.invalidator.debug_assert_paint_or_prepaint();
let path = Rc::new(path);
let next_instance_id = self
.next_frame
.next_inspector_instance_ids
.entry(path.clone())
.or_insert(0);
let instance_id = *next_instance_id;
*next_instance_id += 1;
crate::InspectorElementId { path, instance_id }
}
#[cfg(any(feature = "inspector", debug_assertions))]
fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
if let Some(inspector) = self.inspector.take() {
let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
inspector_element.prepaint_as_root(
point(self.viewport_size.width - inspector_width, px(0.0)),
size(inspector_width, self.viewport_size.height).into(),
self,
cx,
);
self.inspector = Some(inspector);
Some(inspector_element)
} else {
None
}
}
#[cfg(any(feature = "inspector", debug_assertions))]
fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
if let Some(mut inspector_element) = inspector_element {
inspector_element.paint(self, cx);
};
}
#[cfg(any(feature = "inspector", debug_assertions))]
pub fn insert_inspector_hitbox(
&mut self,
hitbox_id: HitboxId,
inspector_id: Option<&crate::InspectorElementId>,
cx: &App,
) {
self.invalidator.debug_assert_paint_or_prepaint();
if !self.is_inspector_picking(cx) {
return;
}
if let Some(inspector_id) = inspector_id {
self.next_frame
.inspector_hitboxes
.insert(hitbox_id, inspector_id.clone());
}
}
#[cfg(any(feature = "inspector", debug_assertions))]
fn paint_inspector_hitbox(&mut self, cx: &App) {
if let Some(inspector) = self.inspector.as_ref() {
let inspector = inspector.read(cx);
if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
&& let Some(hitbox) = self
.next_frame
.hitboxes
.iter()
.find(|hitbox| hitbox.id == hitbox_id)
{
self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
}
}
}
#[cfg(any(feature = "inspector", debug_assertions))]
fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
let Some(inspector) = self.inspector.clone() else {
return;
};
if event.downcast_ref::<MouseMoveEvent>().is_some() {
inspector.update(cx, |inspector, _cx| {
if let Some((_, inspector_id)) =
self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
{
inspector.hover(inspector_id, self);
}
});
} else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
inspector.update(cx, |inspector, _cx| {
if let Some((_, inspector_id)) =
self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
{
inspector.select(inspector_id, self);
}
});
} else if let Some(event) = event.downcast_ref::<crate::ScrollEvent>() {
const SCROLL_LINES: f32 = 3.0;
const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
let delta_y = event
.delta
.pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
.y;
if let Some(inspector) = self.inspector.clone() {
inspector.update(cx, |inspector, _cx| {
if let Some(depth) = inspector.pick_depth.as_mut() {
*depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
if *depth < 0.0 {
*depth = 0.0;
} else if *depth > max_depth {
*depth = max_depth;
}
if let Some((_, inspector_id)) =
self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
{
inspector.set_active_element_id(inspector_id, self);
}
}
});
}
}
}
#[cfg(any(feature = "inspector", debug_assertions))]
fn hovered_inspector_hitbox(
&self,
inspector: &Inspector,
frame: &Frame,
) -> Option<(HitboxId, crate::InspectorElementId)> {
if let Some(pick_depth) = inspector.pick_depth {
let depth = (pick_depth as i64).try_into().unwrap_or(0);
let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
let skip_count = (depth as usize).min(max_skipped);
for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
return Some((*hitbox_id, inspector_id.clone()));
}
}
}
None
}
#[cfg(any(test, feature = "test-support"))]
pub fn set_modifiers(&mut self, modifiers: Modifiers) {
self.modifiers = modifiers;
}
}
slotmap::new_key_type! {
pub struct WindowId;
}
impl WindowId {
pub fn as_u64(&self) -> u64 {
self.0.as_ffi()
}
}
impl From<u64> for WindowId {
fn from(value: u64) -> Self {
WindowId(slotmap::KeyData::from_ffi(value))
}
}
#[derive(Deref, DerefMut)]
pub struct WindowHandle<V> {
#[deref]
#[deref_mut]
pub(crate) any_handle: AnyWindowHandle,
state_type: PhantomData<V>,
}
impl<V> Debug for WindowHandle<V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WindowHandle")
.field("any_handle", &self.any_handle.id.as_u64())
.finish()
}
}
impl<V: 'static + Render> WindowHandle<V> {
pub fn new(id: WindowId) -> Self {
WindowHandle {
any_handle: AnyWindowHandle {
id,
state_type: TypeId::of::<V>(),
},
state_type: PhantomData,
}
}
#[cfg(any(test, feature = "test-support"))]
pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
where
C: AppContext,
{
crate::Flatten::flatten(cx.update_window(self.any_handle, |root_view, _, _| {
root_view
.downcast::<V>()
.map_err(|_| anyhow!("the type of the window's root view has changed"))
}))
}
pub fn update<C, R>(
&self,
cx: &mut C,
update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
) -> Result<R>
where
C: AppContext,
{
cx.update_window(self.any_handle, |root_view, window, cx| {
let view = root_view
.downcast::<V>()
.map_err(|_| anyhow!("the type of the window's root view has changed"))?;
Ok(view.update(cx, |view, cx| update(view, window, cx)))
})?
}
pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
let x = cx
.windows
.get(self.id)
.and_then(|window| {
window
.as_ref()
.and_then(|window| window.root.clone())
.map(|root_view| root_view.downcast::<V>())
})
.context("window not found")?
.map_err(|_| anyhow!("the type of the window's root view has changed"))?;
Ok(x.read(cx))
}
pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
where
C: AppContext,
{
cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
}
pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
where
C: AppContext,
{
cx.read_window(self, |root_view, _cx| root_view)
}
pub fn is_active(&self, cx: &mut App) -> Option<bool> {
cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
.ok()
}
}
impl<V> Copy for WindowHandle<V> {}
impl<V> Clone for WindowHandle<V> {
fn clone(&self) -> Self {
*self
}
}
impl<V> PartialEq for WindowHandle<V> {
fn eq(&self, other: &Self) -> bool {
self.any_handle == other.any_handle
}
}
impl<V> Eq for WindowHandle<V> {}
impl<V> Hash for WindowHandle<V> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.any_handle.hash(state);
}
}
impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
fn from(val: WindowHandle<V>) -> Self {
val.any_handle
}
}
unsafe impl<V> Send for WindowHandle<V> {}
unsafe impl<V> Sync for WindowHandle<V> {}
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct AnyWindowHandle {
pub(crate) id: WindowId,
state_type: TypeId,
}
impl AnyWindowHandle {
pub fn window_id(&self) -> WindowId {
self.id
}
#[cfg(any(test, feature = "test-support"))]
pub fn for_test(id: WindowId) -> Self {
Self {
id,
state_type: TypeId::of::<()>(),
}
}
pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
if TypeId::of::<T>() == self.state_type {
Some(WindowHandle {
any_handle: *self,
state_type: PhantomData,
})
} else {
None
}
}
pub fn update<C, R>(
self,
cx: &mut C,
update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
) -> Result<R>
where
C: AppContext,
{
cx.update_window(self, update)
}
pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
where
C: AppContext,
T: 'static,
{
let view = self
.downcast::<T>()
.context("the type of the window's root view has changed")?;
cx.read_window(&view, read)
}
}
impl HasWindowHandle for Window {
fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
self.platform_window.window_handle()
}
}
impl HasDisplayHandle for Window {
fn display_handle(
&self,
) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
self.platform_window.display_handle()
}
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum ElementId {
View(EntityId),
Integer(u64),
Name(SharedString),
Uuid(Uuid),
FocusHandle(FocusId),
NamedInteger(SharedString, u64),
Path(Arc<std::path::Path>),
CodeLocation(core::panic::Location<'static>),
NamedChild(Box<ElementId>, SharedString),
OpaqueId([u8; 20]),
}
impl ElementId {
pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
Self::NamedInteger(name.into(), integer as u64)
}
}
impl Display for ElementId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
ElementId::Integer(ix) => write!(f, "{}", ix)?,
ElementId::Name(name) => write!(f, "{}", name)?,
ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
ElementId::Path(path) => write!(f, "{}", path.display())?,
ElementId::CodeLocation(location) => write!(f, "{}", location)?,
ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
}
Ok(())
}
}
impl TryInto<SharedString> for ElementId {
type Error = anyhow::Error;
fn try_into(self) -> anyhow::Result<SharedString> {
if let ElementId::Name(name) = self {
Ok(name)
} else {
anyhow::bail!("element id is not string")
}
}
}
impl From<u64> for ElementId {
fn from(id: u64) -> Self {
ElementId::Integer(id)
}
}
impl From<usize> for ElementId {
fn from(id: usize) -> Self {
ElementId::Integer(id as u64)
}
}
impl From<i32> for ElementId {
fn from(id: i32) -> Self {
Self::Integer(id as u64)
}
}
impl From<SharedString> for ElementId {
fn from(name: SharedString) -> Self {
ElementId::Name(name)
}
}
impl From<String> for ElementId {
fn from(name: String) -> Self {
ElementId::Name(name.into())
}
}
impl From<Arc<str>> for ElementId {
fn from(name: Arc<str>) -> Self {
ElementId::Name(name.into())
}
}
impl From<Arc<std::path::Path>> for ElementId {
fn from(path: Arc<std::path::Path>) -> Self {
ElementId::Path(path)
}
}
impl From<&'static str> for ElementId {
fn from(name: &'static str) -> Self {
ElementId::Name(SharedString::new_static(name))
}
}
impl<'a> From<&'a FocusHandle> for ElementId {
fn from(handle: &'a FocusHandle) -> Self {
ElementId::FocusHandle(handle.id)
}
}
impl From<(&'static str, EntityId)> for ElementId {
fn from((name, id): (&'static str, EntityId)) -> Self {
ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
}
}
impl From<(&'static str, usize)> for ElementId {
fn from((name, id): (&'static str, usize)) -> Self {
ElementId::NamedInteger(SharedString::new_static(name), id as u64)
}
}
impl From<(SharedString, usize)> for ElementId {
fn from((name, id): (SharedString, usize)) -> Self {
ElementId::NamedInteger(name, id as u64)
}
}
impl From<(&'static str, u64)> for ElementId {
fn from((name, id): (&'static str, u64)) -> Self {
ElementId::NamedInteger(SharedString::new_static(name), id)
}
}
impl From<Uuid> for ElementId {
fn from(value: Uuid) -> Self {
Self::Uuid(value)
}
}
impl From<(&'static str, u32)> for ElementId {
fn from((name, id): (&'static str, u32)) -> Self {
ElementId::NamedInteger(SharedString::new_static(name), id.into())
}
}
impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
fn from((id, name): (ElementId, T)) -> Self {
ElementId::NamedChild(Box::new(id), name.into())
}
}
impl From<&'static core::panic::Location<'static>> for ElementId {
fn from(location: &'static core::panic::Location<'static>) -> Self {
ElementId::CodeLocation(*location)
}
}
impl From<[u8; 20]> for ElementId {
fn from(opaque_id: [u8; 20]) -> Self {
ElementId::OpaqueId(opaque_id)
}
}
#[derive(Clone)]
pub struct PaintQuad {
pub bounds: Bounds<Pixels>,
pub corner_radii: Corners<Pixels>,
pub background: Background,
pub border_widths: Edges<Pixels>,
pub border_color: Hsla,
pub border_style: BorderStyle,
pub continuous_corners: bool,
pub transform: TransformationMatrix,
pub blend_mode: BlendMode,
}
impl PaintQuad {
pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
PaintQuad {
corner_radii: corner_radii.into(),
..self
}
}
pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
PaintQuad {
border_widths: border_widths.into(),
..self
}
}
pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
PaintQuad {
border_color: border_color.into(),
..self
}
}
pub fn background(self, background: impl Into<Background>) -> Self {
PaintQuad {
background: background.into(),
..self
}
}
}
pub fn quad(
bounds: Bounds<Pixels>,
corner_radii: impl Into<Corners<Pixels>>,
background: impl Into<Background>,
border_widths: impl Into<Edges<Pixels>>,
border_color: impl Into<Hsla>,
border_style: BorderStyle,
) -> PaintQuad {
PaintQuad {
bounds,
corner_radii: corner_radii.into(),
background: background.into(),
border_widths: border_widths.into(),
border_color: border_color.into(),
border_style,
continuous_corners: false,
transform: TransformationMatrix::unit(),
blend_mode: BlendMode::Normal,
}
}
pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
PaintQuad {
bounds: bounds.into(),
corner_radii: (0.).into(),
background: background.into(),
border_widths: (0.).into(),
border_color: transparent_black(),
border_style: BorderStyle::default(),
continuous_corners: false,
transform: TransformationMatrix::unit(),
blend_mode: BlendMode::Normal,
}
}
pub fn outline(
bounds: impl Into<Bounds<Pixels>>,
border_color: impl Into<Hsla>,
border_style: BorderStyle,
) -> PaintQuad {
PaintQuad {
bounds: bounds.into(),
corner_radii: (0.).into(),
background: transparent_black().into(),
border_widths: (1.).into(),
border_color: border_color.into(),
border_style,
continuous_corners: false,
transform: TransformationMatrix::unit(),
blend_mode: BlendMode::Normal,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
ContentMask, Context, Entity, ExternalPaths, HitboxBehavior, InputEvent as _,
MouseMoveEvent, QuitMode, Render, StyleRefinement, TestAppContext, ThermalState,
WindowOptions, bounds, canvas, div, hsla, point, px, size,
};
use std::{
cell::{Cell, RefCell},
path::PathBuf,
rc::Rc,
};
#[test]
fn high_rate_input_avoids_inactive_window_throttling() {
let default_inactive = Some(super::THIRTY_FPS_INTERVAL);
assert_eq!(
minimum_frame_interval(
true,
true,
default_inactive,
ThermalState::Nominal,
crate::PowerMode::Unknown,
),
default_inactive
);
assert_eq!(
minimum_frame_interval(
true,
false,
default_inactive,
ThermalState::Nominal,
crate::PowerMode::Unknown,
),
None
);
assert_eq!(
minimum_frame_interval(
true,
false,
default_inactive,
ThermalState::Serious,
crate::PowerMode::Unknown,
),
Some(super::SIXTY_FPS_INTERVAL),
"thermal pressure still caps high-rate input"
);
}
#[test]
fn inactive_frame_interval_is_configurable() {
let custom = Some(Duration::from_millis(16));
assert_eq!(
minimum_frame_interval(
true,
true,
custom,
ThermalState::Nominal,
crate::PowerMode::Unknown,
),
custom
);
assert_eq!(
minimum_frame_interval(
true,
true,
None,
ThermalState::Nominal,
crate::PowerMode::Unknown,
),
None,
"None disables inactive-window throttling"
);
}
#[test]
fn frame_throttle_tracks_display_refreshes() {
let start = super::Instant::now();
for (elapsed, interval) in [
(Duration::from_micros(16_666), super::SIXTY_FPS_INTERVAL),
(Duration::from_micros(33_332), super::THIRTY_FPS_INTERVAL),
] {
let mut pacer = super::FramePacer::default();
assert!(!pacer.should_defer(start, Some(interval)));
assert!(pacer.should_defer(start + elapsed / 2, Some(interval)));
assert!(!pacer.should_defer(start + elapsed, Some(interval)));
}
}
#[test]
fn frame_throttle_preserves_cadence_without_catching_up_after_stalls() {
let start = super::Instant::now();
let interval = super::THIRTY_FPS_INTERVAL;
let mut pacer = super::FramePacer::default();
assert!(!pacer.should_defer(start, Some(interval)));
let delayed_frame = start + interval + Duration::from_millis(5);
assert!(!pacer.should_defer(delayed_frame, Some(interval)));
assert!(pacer.should_defer(start + interval + interval / 2, Some(interval)));
assert!(!pacer.should_defer(start + interval * 2, Some(interval)));
let after_stall = start + interval * 4 - Duration::from_millis(1);
assert!(!pacer.should_defer(after_stall, Some(interval)));
assert!(pacer.should_defer(after_stall + interval / 2, Some(interval)));
assert!(!pacer.should_defer(after_stall + interval, Some(interval)));
let mandatory_frame = after_stall + interval + Duration::from_millis(2);
assert!(!pacer.should_defer(mandatory_frame, None));
assert!(pacer.should_defer(mandatory_frame + interval / 2, Some(interval)));
}
#[test]
fn power_modes_preserve_frame_limits() {
for (power_mode, active_interval, thermal_interval) in [
(
crate::PowerMode::LowPower,
Some(super::THIRTY_FPS_INTERVAL),
super::THIRTY_FPS_INTERVAL,
),
(crate::PowerMode::Unknown, None, super::SIXTY_FPS_INTERVAL),
(crate::PowerMode::Balanced, None, super::SIXTY_FPS_INTERVAL),
(crate::PowerMode::HighPower, None, super::SIXTY_FPS_INTERVAL),
] {
assert_eq!(
super::minimum_frame_interval(true, false, None, ThermalState::Nominal, power_mode),
active_interval,
);
assert_eq!(
super::minimum_frame_interval(true, false, None, ThermalState::Serious, power_mode),
Some(thermal_interval),
);
let inactive_interval = Duration::from_millis(100);
assert_eq!(
super::minimum_frame_interval(
true,
true,
Some(inactive_interval),
ThermalState::Nominal,
power_mode,
),
Some(inactive_interval),
);
}
}
#[test]
fn thermal_and_low_power_caps_raise_short_inactive_intervals() {
let short = Some(Duration::from_millis(10));
let long = Some(Duration::from_millis(100));
assert_eq!(
super::minimum_frame_interval(
true,
true,
short,
ThermalState::Serious,
crate::PowerMode::Unknown,
),
Some(super::SIXTY_FPS_INTERVAL),
);
assert_eq!(
super::minimum_frame_interval(
true,
true,
None,
ThermalState::Critical,
crate::PowerMode::Unknown,
),
Some(super::SIXTY_FPS_INTERVAL),
"a missing inactive interval does not disable the thermal cap"
);
assert_eq!(
super::minimum_frame_interval(
true,
true,
short,
ThermalState::Nominal,
crate::PowerMode::LowPower,
),
Some(super::THIRTY_FPS_INTERVAL),
);
assert_eq!(
super::minimum_frame_interval(
true,
true,
short,
ThermalState::Serious,
crate::PowerMode::LowPower,
),
Some(super::THIRTY_FPS_INTERVAL),
"low power is the longer of the two caps"
);
assert_eq!(
super::minimum_frame_interval(
true,
true,
long,
ThermalState::Critical,
crate::PowerMode::LowPower,
),
long,
);
assert_eq!(
super::minimum_frame_interval(
true,
false,
None,
ThermalState::Nominal,
crate::PowerMode::Unknown,
),
None,
"unknown power mode does not enable the low-power cap"
);
}
#[test]
fn hovered_at_ignores_pointer_capture() {
let mut cx = TestAppContext::single();
let window = cx.add_window(|_, _| EmptyView);
let window: AnyWindowHandle = window.into();
cx.update_window(window, |_, window, _| {
let bounds = bounds(point(px(0.), px(0.)), size(px(10.), px(10.)));
let hitbox = Hitbox {
id: HitboxId(1),
bounds,
content_mask: ContentMask { bounds },
behavior: HitboxBehavior::Normal,
};
window.rendered_frame.hitboxes.push(hitbox.clone());
window.capture_pointer(hitbox.id);
assert!(hitbox.is_hovered(window));
assert!(hitbox.is_hovered_at(point(px(5.), px(5.)), window));
assert!(!hitbox.is_hovered_at(point(px(20.), px(20.)), window));
})
.unwrap();
}
#[test]
fn hovered_at_respects_content_masks_and_occlusion() {
let mut cx = TestAppContext::single();
let window = cx.add_window(|_, _| EmptyView);
let window: AnyWindowHandle = window.into();
cx.update_window(window, |_, window, _| {
let target_bounds = bounds(point(px(0.), px(0.)), size(px(20.), px(20.)));
let target = Hitbox {
id: HitboxId(1),
bounds: target_bounds,
content_mask: ContentMask {
bounds: bounds(point(px(0.), px(0.)), size(px(10.), px(20.))),
},
behavior: HitboxBehavior::Normal,
};
let blocker = Hitbox {
id: HitboxId(2),
bounds: target_bounds,
content_mask: ContentMask {
bounds: target_bounds,
},
behavior: HitboxBehavior::BlockMouse,
};
window.rendered_frame.hitboxes.push(target.clone());
assert!(target.is_hovered_at(point(px(5.), px(5.)), window));
assert!(!target.is_hovered_at(point(px(15.), px(5.)), window));
window.rendered_frame.hitboxes.push(blocker.clone());
assert!(!target.is_hovered_at(point(px(5.), px(5.)), window));
assert!(blocker.is_hovered_at(point(px(15.), px(5.)), window));
})
.unwrap();
}
#[test]
fn hovered_at_ignores_keyboard_input_modality() {
let mut cx = TestAppContext::single();
let window = cx.add_window(|_, _| EmptyView);
let window: AnyWindowHandle = window.into();
cx.update_window(window, |_, window, _| {
let bounds = bounds(point(px(0.), px(0.)), size(px(10.), px(10.)));
let hitbox = Hitbox {
id: HitboxId(1),
bounds,
content_mask: ContentMask { bounds },
behavior: HitboxBehavior::Normal,
};
window.rendered_frame.hitboxes.push(hitbox.clone());
window.last_input_was_keyboard.set(true);
assert!(!hitbox.is_hovered(window));
assert!(hitbox.is_hovered_at(point(px(5.), px(5.)), window));
})
.unwrap();
}
#[test]
fn draw_in_progress_tracks_element_arena_scope() {
assert!(!draw_in_progress());
let scope = ElementArenaScope::enter();
assert!(draw_in_progress());
let nested = ElementArenaScope::enter();
assert!(draw_in_progress());
drop(nested);
assert!(draw_in_progress(), "outer draw is still in progress");
drop(scope);
assert!(!draw_in_progress());
}
struct EmptyView;
impl Render for EmptyView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
}
}
struct FileDropExitView(Rc<Cell<usize>>);
impl Render for FileDropExitView {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().size_full().on_file_drop_exit({
let observed_file_drop_exit = self.0.clone();
move |_, _, _| observed_file_drop_exit.set(observed_file_drop_exit.get() + 1)
})
}
}
#[test]
fn file_drop_exit_is_window_local() {
let mut cx = TestAppContext::single();
let first_destination_exit_count = Rc::new(Cell::new(0));
let first_destination: AnyWindowHandle = cx
.add_window({
let first_destination_exit_count = first_destination_exit_count.clone();
move |_, _| FileDropExitView(first_destination_exit_count)
})
.into();
let second_destination_exit_count = Rc::new(Cell::new(0));
let second_destination: AnyWindowHandle = cx
.add_window({
let second_destination_exit_count = second_destination_exit_count.clone();
move |_, _| FileDropExitView(second_destination_exit_count)
})
.into();
let reentry_position = point(px(30.), px(30.));
let external_paths =
|| ExternalPaths([PathBuf::from("/tmp/dropped.txt")].into_iter().collect());
let update_result = cx.update_window(first_destination, |_, window, cx| {
window.draw(cx).clear();
window.dispatch_event(
FileDropEvent::Entered {
position: reentry_position,
paths: external_paths(),
}
.to_platform_input(),
cx,
);
window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
assert!(cx.active_drag.is_none());
assert_eq!(first_destination_exit_count.get(), 1);
assert_eq!(second_destination_exit_count.get(), 0);
});
assert!(
update_result.is_ok(),
"failed to handle drag in first destination window: {update_result:?}"
);
let update_result = cx.update_window(second_destination, |_, window, cx| {
window.draw(cx).clear();
window.dispatch_event(
PlatformInput::KeyDown(KeyDownEvent {
keystroke: Keystroke::parse("down").expect("valid keystroke"),
is_held: false,
prefer_character_input: false,
}),
cx,
);
window.dispatch_event(
FileDropEvent::Entered {
position: reentry_position,
paths: external_paths(),
}
.to_platform_input(),
cx,
);
assert!(
cx.active_drag
.as_ref()
.is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
);
assert_eq!(first_destination_exit_count.get(), 1);
assert_eq!(second_destination_exit_count.get(), 0);
window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
assert!(cx.active_drag.is_none());
assert_eq!(first_destination_exit_count.get(), 1);
assert_eq!(second_destination_exit_count.get(), 1);
});
assert!(
update_result.is_ok(),
"failed to handle drag in second destination window: {update_result:?}"
);
}
#[test]
fn open_window_propagates_platform_map_error() {
let cx = TestAppContext::single();
cx.test_platform()
.fail_next_window_map("test window mapping failed");
let result =
cx.update(|cx| cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView)));
let error = match result {
Ok(_) => panic!("window mapping unexpectedly succeeded"),
Err(error) => error,
};
assert_eq!(error.to_string(), "test window mapping failed");
assert!(cx.read(|cx| cx.windows().is_empty()));
}
struct OpensWindowOnPaint {
opened: Rc<Cell<bool>>,
}
impl Render for OpensWindowOnPaint {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let opened = self.opened.clone();
div()
.size_full()
.child(canvas(
|_, _, _| {},
move |_, _, _window, cx| {
if !opened.replace(true) {
cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
.unwrap();
}
},
))
.child(div().child("after"))
}
}
#[test]
fn opening_a_window_during_draw_keeps_outer_elements_alive() {
let mut cx = TestAppContext::single();
let opened = Rc::new(Cell::new(false));
let window = cx.add_window({
let opened = opened.clone();
move |_, _| OpensWindowOnPaint { opened }
});
assert!(opened.get());
assert_eq!(cx.windows().len(), 2);
cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear())
.unwrap();
}
struct FocusLostRestoreView {
parent: FocusHandle,
child: FocusHandle,
show_child: bool,
observed_restore: Option<FocusHandle>,
_subscription: Subscription,
}
impl FocusLostRestoreView {
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
Self {
parent: cx.focus_handle(),
child: cx.focus_handle(),
show_child: true,
observed_restore: None,
_subscription: cx.on_focus_lost(window, |this, window, cx| {
this.observed_restore = window.focus_lost_restore_target(cx);
}),
}
}
}
impl Render for FocusLostRestoreView {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.id("parent")
.track_focus(&self.parent)
.when(self.show_child, |parent| {
parent.child(div().id("child").track_focus(&self.child))
})
}
}
#[test]
fn focus_lost_restore_target_is_nearest_surviving_ancestor() {
let mut cx = TestAppContext::single();
let window = cx.add_window(FocusLostRestoreView::new);
window
.update(&mut cx, |view, window, _| {
window.focus(&view.child);
})
.unwrap();
cx.update_window(window.into(), |_, window, cx| {
window.draw(cx).clear();
assert!(
window.focus_lost_restore_target(cx).is_none(),
"restore target is only set while focus-lost listeners run"
);
})
.unwrap();
window
.update(&mut cx, |view, window, _| {
assert!(view.child.is_focused(window));
view.show_child = false;
})
.unwrap();
cx.update_window(window.into(), |_, window, cx| {
window.draw(cx).clear();
assert!(
window.focus_lost_restore_target(cx).is_none(),
"restore target must be cleared after focus-lost listeners return"
);
})
.unwrap();
window
.update(&mut cx, |view, _, _| {
assert_eq!(
view.observed_restore.as_ref(),
Some(&view.parent),
"restore target should be the parent that remained in the tree"
);
})
.unwrap();
}
#[gpui::test]
fn test_native_close_defers_app_access(cx: &mut TestAppContext) {
let window = cx.add_window(|_, _| EmptyView);
let platform_window = cx.test_window(window.into());
{
let app = cx.app.borrow_mut();
platform_window.simulate_close();
assert!(app.windows.contains_key(window.window_id()));
}
cx.run_until_parked();
assert!(!cx.app.borrow().windows.contains_key(window.window_id()));
}
#[gpui::test]
fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
let window = cx.add_window(|_, _| EmptyView);
window
.update(cx, |_, window, _| {
assert!(matches!(
window.window_handle(),
Err(HandleError::NotSupported)
));
assert!(matches!(
window.display_handle(),
Err(HandleError::NotSupported)
));
})
.unwrap();
}
#[gpui::test]
fn test_window_visibility(cx: &mut TestAppContext) {
let window = cx.add_window(|_, _| EmptyView);
let observed = Rc::new(RefCell::new(Vec::new()));
let _subscription = window
.update(cx, {
let observed = observed.clone();
move |_, window, _| {
assert_eq!(window.visibility(), WindowVisibility::Visible);
assert!(window.is_visible());
window.observe_window_visibility(move |visibility, window, _| {
assert_eq!(window.visibility(), visibility);
observed.borrow_mut().push(visibility);
})
}
})
.unwrap();
let test_window = cx.test_window(window.into());
window
.update(cx, |_, window, _| {
window.invalidator.set_dirty(false);
window.needs_present.set(false);
})
.unwrap();
let frame_wake_count = test_window.frame_wake_count();
test_window.simulate_visibility_change(WindowVisibility::Hidden);
assert_eq!(*observed.borrow(), [WindowVisibility::Hidden]);
window
.update(cx, |_, window, _| assert!(!window.is_visible()))
.unwrap();
test_window.simulate_visibility_change(WindowVisibility::Hidden);
assert_eq!(observed.borrow().len(), 1);
test_window.simulate_visibility_change(WindowVisibility::Visible);
assert_eq!(
*observed.borrow(),
[WindowVisibility::Hidden, WindowVisibility::Visible]
);
window
.update(cx, |_, window, _| assert!(window.is_visible()))
.unwrap();
assert_eq!(test_window.frame_wake_count(), frame_wake_count);
}
#[gpui::test]
fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
let window = cx.add_window(|_, _| EmptyView);
let observed_appearance = Rc::new(Cell::new(None));
let _subscription = window
.update(cx, {
let observed_appearance = observed_appearance.clone();
move |_, window, _| {
window.observe_window_appearance(move |window, _| {
observed_appearance.set(Some(window.appearance()));
})
}
})
.unwrap();
let test_window = cx.test_window(window.into());
cx.update(|_| {
test_window.simulate_appearance_change(WindowAppearance::Dark);
assert_eq!(observed_appearance.get(), None);
});
cx.run_until_parked();
assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
}
#[test]
fn test_scale_factor_change_preserves_bounds_and_survives_resize() {
let mut cx = TestAppContext::single();
let window = cx.add_window(|_, _| EmptyView);
let handle: AnyWindowHandle = window.into();
let window_state = |cx: &mut TestAppContext| {
cx.update_window(handle, |_, window, _| {
(
window.scale_factor(),
window.bounds(),
window.viewport_size(),
)
})
.unwrap()
};
let (scale_factor, mut expected_bounds, _) = window_state(&mut cx);
assert_eq!(scale_factor, 2.0);
for (scale_factor, resized_size) in [
(1.0, size(px(800.), px(600.))),
(1.25, size(px(640.), px(480.))),
(2.0, size(px(1024.), px(768.))),
] {
cx.simulate_window_scale_factor_change(handle, scale_factor);
assert_eq!(
window_state(&mut cx),
(scale_factor, expected_bounds, expected_bounds.size)
);
cx.simulate_window_resize(handle, resized_size);
expected_bounds.size = resized_size;
assert_eq!(
window_state(&mut cx),
(scale_factor, expected_bounds, resized_size)
);
}
}
struct RootView {
explicit_size: bool,
child_bounds: Rc<Cell<Bounds<Pixels>>>,
}
impl Render for RootView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let child_bounds = self.child_bounds.clone();
let mut root = div().flex().flex_col().child(
canvas(
move |bounds, _, _| child_bounds.set(bounds),
|_, _, _, _| {},
)
.size_full(),
);
if self.explicit_size {
root = root.w(px(300.)).h(px(200.));
}
root
}
}
#[test]
fn auto_sized_window_root_fills_the_window() {
let mut cx = TestAppContext::single();
let child_bounds = Rc::new(Cell::new(Bounds::default()));
let window = cx.add_window({
let child_bounds = child_bounds.clone();
move |_, _| RootView {
explicit_size: false,
child_bounds,
}
});
let viewport_size = cx
.update_window(window.into(), |_, window, cx| {
window.draw(cx).clear();
window.viewport_size()
})
.unwrap();
assert_eq!(child_bounds.get().size, viewport_size);
}
#[test]
fn explicitly_sized_window_root_keeps_its_size() {
let mut cx = TestAppContext::single();
let child_bounds = Rc::new(Cell::new(Bounds::default()));
let window = cx.add_window({
let child_bounds = child_bounds.clone();
move |_, _| RootView {
explicit_size: true,
child_bounds,
}
});
cx.update_window(window.into(), |_, window, cx| {
window.draw(cx).clear();
})
.unwrap();
assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
}
fn scaled(value: f32) -> ScaledPixels {
ScaledPixels(value)
}
#[test]
fn border_only_quad_strips_cover_asymmetric_borders_and_corners() {
let bounds = Bounds::new(
point(scaled(0.), scaled(0.)),
size(scaled(100.), scaled(80.)),
);
let widths = Edges {
top: scaled(6.),
right: scaled(4.),
bottom: scaled(8.),
left: scaled(2.),
};
let radii = Corners {
top_left: scaled(10.),
top_right: scaled(12.),
bottom_right: scaled(16.),
bottom_left: scaled(14.),
};
let strips = border_only_quad_strips(bounds, widths, radii).unwrap();
assert_eq!(
strips,
[
Bounds::from_corners(
point(scaled(0.), scaled(0.)),
point(scaled(100.), scaled(13.)),
),
Bounds::from_corners(
point(scaled(0.), scaled(63.)),
point(scaled(100.), scaled(80.)),
),
Bounds::from_corners(
point(scaled(0.), scaled(13.)),
point(scaled(3.), scaled(63.)),
),
Bounds::from_corners(
point(scaled(95.), scaled(13.)),
point(scaled(100.), scaled(63.)),
),
]
);
}
#[test]
fn border_only_quad_keeps_one_primitive_when_interior_is_too_small() {
let bounds = Bounds::new(
point(scaled(0.), scaled(0.)),
size(scaled(10.), scaled(10.)),
);
let widths = Edges {
top: scaled(5.),
right: scaled(5.),
bottom: scaled(5.),
left: scaled(5.),
};
assert!(border_only_quad_strips(bounds, widths, Corners::default()).is_none());
}
struct BorderOnlyQuadView;
impl Render for BorderOnlyQuadView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
canvas(
|_, _, _| {},
|bounds, _, window, _| {
window.paint_quad(outline(bounds, hsla(0., 0., 1., 1.), BorderStyle::Solid));
},
)
.size(px(100.))
}
}
#[test]
fn border_only_quad_emits_four_clipped_primitives() {
let mut cx = TestAppContext::single();
let window = cx.add_window(|_, _| BorderOnlyQuadView);
let primitive_count = cx
.update_window(window.into(), |_, window, cx| {
window.draw(cx).clear();
window.rendered_frame.scene.quads.len()
})
.unwrap();
assert_eq!(primitive_count, 4);
}
#[test]
fn resource_profile_gpu_budget_reaches_the_platform() {
let cx = TestAppContext::single();
let budget = cx.test_platform().gpu_resource_budget.lock().clone();
assert_eq!(budget.instance_buffer_initial_size, 2 * 1024 * 1024);
assert_eq!(budget.instance_buffer_max_size, 256 * 1024 * 1024);
}
#[test]
fn window_attention_is_forwarded_to_the_platform_window() {
let mut cx = TestAppContext::single();
let window = cx.add_window(|_, _| BorderOnlyQuadView);
let window = AnyWindowHandle::from(window);
cx.update_window(window, |_, window, _| window.request_attention())
.unwrap();
assert_eq!(cx.test_window(window).0.lock().attention_requests, 1);
}
#[test]
fn quit_mode_explicit_keeps_app_alive_after_last_window_closed() {
let mut cx = TestAppContext::single();
cx.update(|cx| cx.set_quit_mode(QuitMode::Explicit));
assert_eq!(
*cx.test_platform().last_quit_mode.lock(),
Some(QuitMode::Explicit)
);
let window = cx.add_window(|_, _| BorderOnlyQuadView);
let window = AnyWindowHandle::from(window);
cx.update_window(window, |_, window, _| window.remove_window())
.unwrap();
assert!(!*cx.test_platform().did_quit.lock());
}
#[test]
fn quit_mode_last_window_closed_quits_after_last_window_closed() {
let mut cx = TestAppContext::single();
cx.update(|cx| cx.set_quit_mode(QuitMode::LastWindowClosed));
let window = cx.add_window(|_, _| BorderOnlyQuadView);
let window = AnyWindowHandle::from(window);
cx.update_window(window, |_, window, _| window.remove_window())
.unwrap();
assert!(*cx.test_platform().did_quit.lock());
}
#[test]
fn quit_mode_runtime_change_applies_to_the_next_window_close() {
let mut cx = TestAppContext::single();
cx.update(|cx| cx.set_quit_mode(QuitMode::Explicit));
let window = AnyWindowHandle::from(cx.add_window(|_, _| BorderOnlyQuadView));
cx.update(|cx| cx.set_quit_mode(QuitMode::LastWindowClosed));
assert_eq!(
*cx.test_platform().last_quit_mode.lock(),
Some(QuitMode::LastWindowClosed)
);
cx.update_window(window, |_, window, _| window.remove_window())
.unwrap();
assert!(*cx.test_platform().did_quit.lock());
}
#[test]
fn quit_mode_last_window_closed_waits_for_every_window() {
let mut cx = TestAppContext::single();
cx.update(|cx| cx.set_quit_mode(QuitMode::LastWindowClosed));
let first = AnyWindowHandle::from(cx.add_window(|_, _| BorderOnlyQuadView));
let second = AnyWindowHandle::from(cx.add_window(|_, _| BorderOnlyQuadView));
cx.update_window(first, |_, window, _| window.remove_window())
.unwrap();
assert!(!*cx.test_platform().did_quit.lock());
cx.update_window(second, |_, window, _| window.remove_window())
.unwrap();
assert!(*cx.test_platform().did_quit.lock());
}
#[test]
fn quit_mode_default_follows_platform_convention() {
let mut cx = TestAppContext::single();
let window = cx.add_window(|_, _| BorderOnlyQuadView);
let window = AnyWindowHandle::from(window);
cx.update_window(window, |_, window, _| window.remove_window())
.unwrap();
let expected = cfg!(not(target_os = "macos"));
assert_eq!(*cx.test_platform().did_quit.lock(), expected);
}
#[gpui::test]
fn cached_view_follows_inherited_opacity(cx: &mut TestAppContext) {
struct Child {
renders: usize,
}
impl Render for Child {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
self.renders += 1;
div().size_full().bg(crate::rgb(0xff0000))
}
}
struct Root {
opacity: f32,
width: Pixels,
child: Entity<Child>,
}
impl Render for Root {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.w(self.width)
.h(px(200.))
.opacity(self.opacity)
.hover(|style| style.opacity(1.))
.child(
AnyView::from(self.child.clone())
.cached(StyleRefinement::default().size(px(100.))),
)
}
}
fn update_and_draw(
window: WindowHandle<Root>,
child: &Entity<Child>,
cx: &mut TestAppContext,
update: impl FnOnce(&mut Root, &mut Window, &mut Context<Root>),
) -> (f32, usize) {
window
.update(cx, |root, window, cx| {
update(root, window, cx);
cx.notify();
})
.expect("update root");
for _ in 0..3 {
let (alpha, renders, requested_frames) = cx
.update_window(window.into(), |_, window, cx| {
window.draw(cx).clear();
let quads = &window.rendered_frame.scene.quads;
assert_eq!(quads.len(), 1);
let alpha = quads.first().expect("child quad").background.solid.a;
(
alpha,
child.read(cx).renders,
simulate_next_frame(window, cx),
)
})
.expect("draw window");
if requested_frames == 0 {
return (alpha, renders);
}
}
panic!("cached child kept requesting frames");
}
fn simulate_next_frame(window: &mut Window, cx: &mut App) -> usize {
let callbacks = window.next_frame_callbacks.take();
let count = callbacks.len();
for callback in callbacks {
callback(window, cx);
}
count
}
fn simulate_mouse_move(window: &mut Window, position: Point<Pixels>, cx: &mut App) {
let _ = window.dispatch_event(
MouseMoveEvent {
position,
modifiers: window.modifiers(),
pressed_button: None,
}
.to_platform_input(),
cx,
);
}
let child = cx.new(|_| Child { renders: 0 });
let window = cx.add_window(|_, _| Root {
opacity: 1.,
width: px(200.),
child: child.clone(),
});
let outside = point(px(500.), px(500.));
let inside = point(px(50.), px(50.));
let beside = point(px(250.), px(50.));
let move_outside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
simulate_mouse_move(window, outside, cx)
};
assert_eq!(update_and_draw(window, &child, cx, move_outside), (1., 1));
assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (1., 1));
let fade = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.opacity = 0.5;
assert_eq!(update_and_draw(window, &child, cx, fade), (0.5, 2));
assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (0.5, 2));
let move_inside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
simulate_mouse_move(window, inside, cx)
};
assert_eq!(update_and_draw(window, &child, cx, move_inside).0, 1.);
let move_beside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
simulate_mouse_move(window, beside, cx)
};
assert_eq!(update_and_draw(window, &child, cx, move_beside).0, 0.5);
let widen = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.width = px(300.);
assert_eq!(update_and_draw(window, &child, cx, widen).0, 1.);
}
}