Skip to main content

Engine

Struct Engine 

Source
pub struct Engine<S = ()> { /* private fields */ }
Expand description

The run loop: owns the window’s widget tree, routes input to Widgets, calls the application’s callbacks, and draws.

S is the application state type. Engine::run takes ownership of a value of S, passes it to every callback, and returns it when the Engine stops. Applications that prefer their own loop use Engine::event_loop and Engine::next_event instead of callbacks.

Implementations§

Source§

impl<S> Engine<S>

Source

pub fn new(size: Size, frame_rate: u32) -> Self

Creates an Engine for a window of the given size.

A white RootWidget is created as Widget 0 and fills the window.

§Arguments
  • size - The size of the window in pixels.
  • frame_rate - The maximum number of frames drawn per second (for example 30 or 60). 0 is treated as 1.
§Returns

A new Engine with no Widgets other than the root, and no callbacks.

Source

pub fn shutdown(&mut self)

Stops the Engine.

The run loop exits after the current batch of events; in the event-loop style, Engine::next_event returns None.

Source

pub fn set_event_mask(&mut self, mask: EventMask)

Sets the run loop’s event mask.

Events whose class is not in the mask are dropped before routing and callbacks, and the backend is told the mask so it can stop delivering the rest. Close requests are always delivered. The change applies from the next event and emits EngineEvent::EventMaskChanged with MaskScope::RunLoop.

With EventMask::TIMER left out and nothing to repaint, the loop blocks waiting for input instead of polling, so an idle application uses almost no CPU.

§Arguments
  • mask - The classes of events to handle. The default is EventMask::ALL.
§Examples
use pushrod::engine::Engine;
use pushrod::event::EventMask;
use pushrod::geometry::size;

let mut engine: Engine = Engine::new(size(320, 200), 60);

// No hover effects: stop pointer motion at the source.
engine.set_event_mask(EventMask::ALL & !EventMask::POINTER_MOTION & !EventMask::HOVER);

assert!(!engine.event_mask().contains(EventMask::HOVER));
Source

pub fn event_mask(&self) -> EventMask

Returns the run loop’s event mask.

§Returns

The mask set with Engine::set_event_mask; EventMask::ALL by default.

Source

pub fn on_timer<F>( &mut self, interval: Duration, repeat: bool, callback: F, ) -> TimerId
where F: FnMut(&mut S, &mut Ui<'_>) + 'static,

Starts a timer.

The callback runs from the run loop (or Engine::next_event_with) once interval has passed, within one frame of it. A repeating timer runs again every interval; if the application falls behind it runs once and keeps its rhythm instead of catching up in a burst. Each firing emits EngineEvent::TimerFired. The callback receives the application state and a Ui; call Ui::cancel_timer to stop a timer, even from its own callback.

§Arguments
  • interval - The time until the timer fires, and between firings if it repeats.
  • repeat - true to fire every interval; false to fire once.
  • callback - Runs each time the timer fires.
§Returns

The timer’s TimerId, for cancelling it.

§Examples
use pushrod::engine::Engine;
use pushrod::geometry::size;
use std::time::Duration;

let mut engine: Engine<u32> = Engine::new(size(320, 200), 60);

// Counts seconds; the application reads the count from its state.
let clock = engine.on_timer(Duration::from_secs(1), true, |seconds, _ui| *seconds += 1);

assert!(engine.cancel_timer(clock));
Source

pub fn cancel_timer(&mut self, id: TimerId) -> bool

Cancels a timer started with Engine::on_timer. Emits EngineEvent::TimerCancelled when a waiting timer was stopped.

§Arguments
  • id - The timer to cancel.
§Returns

true if the timer was still scheduled.

Source

pub fn on_idle<F>(&mut self, callback: F)
where F: FnMut(&mut S, &mut Ui<'_>) + 'static,

Registers a callback that runs when the loop is idle: once per loop iteration in which no events were waiting. Use it for work that should yield to input, such as deferred layout or incremental loading. While any idle callback is registered the loop polls once per frame instead of blocking, so keep the callback short. Each run emits EngineEvent::IdleRan.

§Arguments
  • callback - Receives the application state and a Ui.
§Examples
use pushrod::engine::Engine;
use pushrod::geometry::size;

let mut engine: Engine<Vec<u32>> = Engine::new(size(320, 200), 60);

// Loads one item per idle iteration.
engine.on_idle(|loaded, _ui| loaded.push(loaded.len() as u32));
Source

pub fn advance(&mut self, now: Instant, state: &mut S)

Advances the engine’s clock to now: runs the timers that are due, then delivers one Event::Tick to the Widgets that requested animation, and delivers everything they cause to the callbacks. Engine::run calls this once per frame; call it directly to test an application’s timers headless, with times of your own choosing.

§Arguments
  • now - The current time.
  • state - The application state passed to the callbacks.
Source

pub fn run_idle(&mut self, state: &mut S)

Runs the idle callbacks and delivers the events they cause. Engine::run calls this when a frame had no events to process; call it directly to test idle callbacks headless.

§Arguments
  • state - The application state passed to the callbacks.
Source

pub fn is_running(&self) -> bool

Returns whether the Engine is running.

§Returns

true until the window is closed or shutdown is called.

Source

pub fn add_widget<W: Widget>(&mut self, widget: W) -> WidgetId

Adds a Widget to the window, as a child of the root Widget.

§Arguments
  • widget - The Widget to add. Its origin is relative to the window.
§Returns

The ID assigned to the Widget; use it to register callbacks and to reach the Widget later.

Source

pub fn add_child_widget<W: Widget>( &mut self, parent: WidgetId, widget: W, ) -> WidgetId

Adds a Widget as a child of another Widget.

Children move with their parent, are hidden with it, and are drawn on top of it.

§Arguments
  • parent - The ID of the parent Widget.
  • widget - The Widget to add. Its origin is relative to the parent.
§Returns

The ID assigned to the Widget.

§Panics

Panics if parent does not exist.

Source

pub fn try_add_child_widget<W: Widget>( &mut self, parent: WidgetId, widget: W, ) -> Result<WidgetId>

Adds a Widget as a child of another, reporting an unknown parent as an error instead of panicking. Behaves like add_child_widget otherwise.

§Arguments
  • parent - The ID of the parent Widget.
  • widget - The Widget to add. Its origin is relative to the parent.
§Returns

The ID assigned to the Widget.

§Errors

Returns Error::UnknownWidget if parent does not exist.

Source

pub fn widgets(&mut self) -> &mut WidgetCache

Returns the window’s widget tree.

§Returns

The WidgetCache holding every Widget in the window.

Source

pub fn on_click<F>(&mut self, id: WidgetId, callback: F) -> CallbackId
where F: FnMut(&mut S, &mut Ui<'_>) + 'static,

Registers a callback that runs when a Widget is clicked.

Several callbacks may be registered for the same Widget; they run in the order registered, before any on_event callbacks. Callbacks run with Engine::run, Engine::dispatch and Engine::next_event_with. Every on_* method below works the same way: it fires only for its Widget and event kind, in registration order, after the Widget has updated itself.

§Arguments
  • id - The ID of the Widget.
  • callback - Called with the application state and a Ui handle.
§Returns

The CallbackId of the registered callback.

§Examples
use pushrod::engine::Engine;
use pushrod::geometry::size;

let mut engine: Engine<u32> = Engine::new(size(320, 200), 30);

engine.on_click(0, |clicks, _ui| *clicks += 1);
Source

pub fn on_press<F>(&mut self, id: WidgetId, callback: F) -> CallbackId
where F: FnMut(&mut S, &mut Ui<'_>) + 'static,

Registers a callback that runs when a mouse button goes down on the Widget.

§Arguments
  • id - The ID of the Widget.
  • callback - Called with the application state and a Ui handle.
§Returns

The CallbackId of the registered callback.

Source

pub fn on_release<F>(&mut self, id: WidgetId, callback: F) -> CallbackId
where F: FnMut(&mut S, &mut Ui<'_>) + 'static,

Registers a callback that runs when a mouse button goes up, inside or outside the Widget (it is sent to the Widget that captured the press).

§Arguments
  • id - The ID of the Widget.
  • callback - Called with the application state and a Ui handle.
§Returns

The CallbackId of the registered callback.

Source

pub fn on_activate<F>(&mut self, id: WidgetId, callback: F) -> CallbackId
where F: FnMut(&mut S, &mut Ui<'_>) + 'static,

Registers a callback that runs when a Widget is activated.

§Arguments
  • id - The ID of the Widget.
  • callback - Called with the application state and a Ui handle.
§Returns

The CallbackId of the registered callback.

Source

pub fn on_value_change<F>(&mut self, id: WidgetId, callback: F) -> CallbackId
where F: FnMut(&mut S, &mut Ui<'_>) + 'static,

Registers a callback that runs when a Widget’s value changes.

§Arguments
  • id - The ID of the Widget.
  • callback - Called with the application state and a Ui handle.
§Returns

The CallbackId of the registered callback.

Source

pub fn on_selection_change<F>( &mut self, id: WidgetId, callback: F, ) -> CallbackId
where F: FnMut(&mut S, &mut Ui<'_>) + 'static,

Registers a callback that runs when a Widget’s selection changes.

§Arguments
  • id - The ID of the Widget.
  • callback - Called with the application state and a Ui handle.
§Returns

The CallbackId of the registered callback.

Source

pub fn on_text_change<F>(&mut self, id: WidgetId, callback: F) -> CallbackId
where F: FnMut(&mut S, &mut Ui<'_>) + 'static,

Registers a callback that runs when a Widget’s text changes.

§Arguments
  • id - The ID of the Widget.
  • callback - Called with the application state and a Ui handle.
§Returns

The CallbackId of the registered callback.

Source

pub fn on_editing_finished<F>( &mut self, id: WidgetId, callback: F, ) -> CallbackId
where F: FnMut(&mut S, &mut Ui<'_>) + 'static,

Registers a callback that runs when editing in a Widget finishes.

§Arguments
  • id - The ID of the Widget.
  • callback - Called with the application state and a Ui handle.
§Returns

The CallbackId of the registered callback.

Source

pub fn on_toggle<F>(&mut self, id: WidgetId, callback: F) -> CallbackId
where F: FnMut(&mut S, &mut Ui<'_>, bool) + 'static,

Registers a callback that runs when a Widget is toggled.

§Arguments
  • id - The ID of the Widget.
  • callback - Called with the application state, a Ui handle, and the new checked state.
§Returns

The CallbackId of the registered callback.

Source

pub fn on_viewport_change<F>(&mut self, id: WidgetId, callback: F) -> CallbackId
where F: FnMut(&mut S, &mut Ui<'_>, Point) + 'static,

Registers a callback that runs when a scrolling Widget’s visible area moves.

§Arguments
  • id - The ID of the Widget.
  • callback - Called with the application state, a Ui handle, and the new scroll offset.
§Returns

The CallbackId of the registered callback.

Source

pub fn on_key_press<F>(&mut self, id: WidgetId, callback: F) -> CallbackId
where F: FnMut(&mut S, &mut Ui<'_>, Key, Modifiers) + 'static,

Registers a callback that runs when a key goes down (or repeats) while the Widget has the keyboard.

§Arguments
  • id - The ID of the Widget.
  • callback - Called with the application state, a Ui handle, the key, and the modifiers held.
§Returns

The CallbackId of the registered callback.

Source

pub fn on_focus_change<F>(&mut self, id: WidgetId, callback: F) -> CallbackId
where F: FnMut(&mut S, &mut Ui<'_>, bool) + 'static,

Registers a callback that runs when a Widget gains or loses keyboard focus.

§Arguments
  • id - The ID of the Widget.
  • callback - Called with the application state, a Ui handle, and true if focus was gained.
§Returns

The CallbackId of the registered callback.

Source

pub fn on_hover<F>(&mut self, id: WidgetId, callback: F) -> CallbackId
where F: FnMut(&mut S, &mut Ui<'_>, bool) + 'static,

Registers a callback that runs when the pointer enters or leaves a Widget.

§Arguments
  • id - The ID of the Widget.
  • callback - Called with the application state, a Ui handle, and true if the pointer is inside.
§Returns

The CallbackId of the registered callback.

Source

pub fn on_event<F>(&mut self, callback: F)
where F: FnMut(&mut S, &mut Ui<'_>, &Event) + 'static,

Registers a callback that receives every event the Widgets generate.

These callbacks run after the Widget-specific callbacks for the same event, in the order registered.

§Arguments
  • callback - Called with the application state, a Ui handle, and the event.
Source

pub fn on_engine_event<F>(&mut self, callback: F)
where F: FnMut(&mut S, &mut Ui<'_>, &EngineEvent) + 'static,

Registers a callback that receives every EngineEvent.

Engine events are emitted after an internal action completes (an event mask change, a Widget added, …). They run before on_event callbacks. Engine events never trigger further internal actions by themselves.

§Arguments
  • callback - Called with the application state, a Ui handle, and the engine event.
§Examples
use pushrod::engine::Engine;
use pushrod::event::EngineEvent;
use pushrod::geometry::size;

let mut engine: Engine<Vec<String>> = Engine::new(size(320, 200), 30);

engine.on_engine_event(|log, _ui, event| log.push(format!("{:?}", event)));
Source

pub fn on_engine_event_filtered<F>( &mut self, kinds: &[EngineEventKind], callback: F, )
where F: FnMut(&mut S, &mut Ui<'_>, &EngineEvent) + 'static,

Registers a callback that receives only the listed kinds of EngineEvent.

§Arguments
  • kinds - The kinds of engine event to receive.
  • callback - Called with the application state, a Ui handle, and the engine event.
Source

pub fn on_custom<T, F>(&mut self, callback: F)
where T: Any, F: FnMut(&mut S, &mut Ui<'_>, Option<WidgetId>, &T) + 'static,

Registers a callback for custom events whose payload is a T.

Custom events are delivered to the targeted Widgets first, then to these callbacks, then to on_event. Events carrying any other payload type are ignored by this callback.

§Arguments
  • callback - Called with the application state, a Ui handle, the posting Widget (None if the application or another thread posted), and the payload.
§Examples
use pushrod::engine::Engine;
use pushrod::geometry::size;

struct DocumentSaved;

let mut engine: Engine<u32> = Engine::new(size(320, 200), 30);

engine.on_custom::<DocumentSaved, _>(|saves, _ui, _source, _payload| *saves += 1);
Source

pub fn sender(&self) -> Sender

Returns a handle other threads use to post custom events to this Engine.

§Returns

A Sender; every call returns a handle to the same queue.

Source

pub fn set_background(&mut self, color: Color)

Sets the window’s background color.

This is the color of the RootWidget (ID 0), which fills the window behind every other Widget.

§Arguments
  • color - The new background color.
Source

pub fn get_size(&self) -> Size

Returns the size of the window.

§Returns

The window size given to Engine::new.

Source

pub fn dispatch(&mut self, event: InputEvent, state: &mut S)

Processes one raw input event, as the run loop does.

The event is routed to the Widgets, and every event they generate is delivered to the registered callbacks, in order. Useful for testing an application without opening a window.

§Arguments
  • event - The input event, as a backend would deliver it.
  • state - The application state passed to the callbacks.
Source

pub fn run(&mut self, backend: &mut dyn Backend, state: S) -> S

Runs the application on a backend until the window is closed or a callback calls shutdown.

Each frame, the loop processes waiting input events (routing them to Widgets and calling callbacks), repaints changed Widgets, presents the frame if anything changed, then sleeps for the rest of the frame time. Applications normally start this through a backend crate, such as pushrod_sdl2::run, which builds the window and calls this method.

§Arguments
  • backend - The backend that owns the window.
  • state - The application state, passed to every callback.
§Returns

The application state, after the last callback has run.

§Examples
use pushrod::backend::headless::HeadlessBackend;
use pushrod::engine::Engine;
use pushrod::geometry::size;

let mut engine: Engine<u32> = Engine::new(size(100, 100), 30);
let mut backend = HeadlessBackend::new(size(100, 100));

// With nothing scripted, the headless window closes at once.
assert_eq!(engine.run(&mut backend, 7), 7);
Source

pub fn event_loop(&mut self, backend: Box<dyn Backend>) -> EventLoop

Starts an application-driven event loop, as an alternative to Engine::run and callbacks.

Call Engine::next_event repeatedly to receive the events generated by the Widgets. Applications normally start this through a backend crate, such as pushrod_sdl2::event_loop.

§Arguments
  • backend - The backend that owns the window; the loop keeps it.
§Returns

The EventLoop to pass to Engine::next_event.

§Examples
use pushrod::backend::headless::HeadlessBackend;
use pushrod::engine::Engine;
use pushrod::event::Event;
use pushrod::geometry::size;

let mut engine: Engine = Engine::new(size(400, 200), 60);
let mut events = engine.event_loop(Box::new(HeadlessBackend::new(size(400, 200))));

while let Some(event) = engine.next_event(&mut events) {
    if let Event::Clicked { id, .. } = event {
        println!("widget {} clicked", id);
    }
}
Source

pub fn next_event(&mut self, events: &mut EventLoop) -> Option<Event>

Returns the next event generated by the Widgets, waiting for input as needed.

While waiting, the screen is kept up to date: invalidated Widgets are repainted and the frame is presented, so changes made to Widgets between calls appear immediately. When nothing happens, the call blocks without using the CPU. Callbacks registered with on_click and on_event are not called by this method; use Engine::next_event_with to run them too.

§Arguments
§Returns

The next event, or None once the window has been closed or shutdown has been called.

Source

pub fn next_event_with( &mut self, events: &mut EventLoop, state: &mut S, ) -> Option<Event>

Returns the next event, after running the registered callbacks for it.

This is Engine::next_event plus the callback style: the on_click, on_engine_event and on_event callbacks run for the event, with the application state, and then the event is returned. Use it to mix styles, for example callbacks for most Widgets and a loop for the main window’s logic. Every event is delivered to both, in the same order as Engine::run delivers it. Events emitted by a callback’s own actions are returned by later calls.

§Arguments
  • events - The loop state returned by Engine::event_loop.
  • state - The application state passed to the callbacks.
§Returns

The next event, or None once the window has been closed or shutdown has been called.

§Examples
let mut engine: Engine<u32> = Engine::new(size(400, 200), 60);
let mut events = engine.event_loop(Box::new(HeadlessBackend::new(size(400, 200))));
let mut clicks = 0;

engine.on_click(0, |clicks, _ui| *clicks += 1);

// The callback has already run when the event is returned.
while let Some(event) = engine.next_event_with(&mut events, &mut clicks) {
    println!("{:?}, {} clicks so far", event, clicks);
}

Auto Trait Implementations§

§

impl<S = ()> !RefUnwindSafe for Engine<S>

§

impl<S = ()> !Send for Engine<S>

§

impl<S = ()> !Sync for Engine<S>

§

impl<S = ()> !UnwindSafe for Engine<S>

§

impl<S> Freeze for Engine<S>

§

impl<S> Unpin for Engine<S>

§

impl<S> UnsafeUnpin for Engine<S>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.