Skip to main content

ViewportState

Struct ViewportState 

pub struct ViewportState { /* private fields */ }
Expand description

The pure zoom/pan state kernel. Owns the zoom factor and the scroll offsets, derives the content↔screen transform, and reduces input events (wheel, drag, arrow keys) into new state. Render-agnostic and cheap to clone — a host stores one of these and drives it from its own event + draw paths. See the module docs for the two usage shapes.

Implementations§

§

impl ViewportState

pub fn new() -> ViewportState

A fresh viewport at 100 % zoom, no scroll, default bounds + padding, content centred horizontally and top-aligned vertically (the common document feel). Set the content size with Self::set_content_size and the rect with Self::set_rect before drawing.

pub fn with_zoom_bounds(self, min: f64, max: f64) -> ViewportState

Override the inclusive zoom bounds. min is clamped > 0 and max is raised to at least min.

pub fn with_padding(self, pad: f64) -> ViewportState

Override the screen-px padding reserved around the content. A pinned value stays put across layouts; without it the padding is the theme’s spacing.s6 (24 px at the default density).

pub fn with_alignment( self, align_x: SmallContentAlign, align_y: SmallContentAlign, ) -> ViewportState

Override how content is aligned along each axis when it is smaller than the viewport on that axis.

pub fn set_rect(&mut self, rect: Rect)

Set the on-screen viewport rect. Re-clamps the scroll so the content stays reachable after a resize. Call once per layout pass.

pub fn set_content_size(&mut self, width: f64, height: f64)

Declare the content’s intrinsic size (content units). Re-clamps the scroll. Call whenever the document size changes (page added, image swapped, …).

pub fn rect(&self) -> Rect

pub fn zoom(&self) -> f64

Current uniform zoom (content units → screen px).

pub fn scroll_x(&self) -> f64

Current scroll offset (screen px) along x.

pub fn scroll_y(&self) -> f64

Current scroll offset (screen px) along y.

pub fn zoom_bounds(&self) -> (f64, f64)

Inclusive zoom bounds (min, max).

pub fn content_size(&self) -> (f64, f64)

Declared content size (width, height) in content units.

pub fn scaled_content_width(&self) -> f64

Total screen width the content occupies at the current zoom, plus both side pads.

pub fn scaled_content_height(&self) -> f64

Total screen height the content occupies at the current zoom, plus both pads.

pub fn max_scroll_x(&self) -> f64

Maximum horizontal scroll (screen px). Zero when the content fits.

pub fn max_scroll_y(&self) -> f64

Maximum vertical scroll (screen px). Zero when the content fits.

pub fn overflows_x(&self) -> bool

Whether the content overflows the viewport horizontally (scrollbar + horizontal pan become live).

pub fn overflows_y(&self) -> bool

Whether the content overflows the viewport vertically.

pub fn clamp_scroll(&mut self)

Clamp both scroll offsets into their valid ranges. Idempotent; called internally after every mutation.

pub fn content_origin(&self) -> Point

Screen-space top-left of the content (content (0,0) mapped to screen). Useful for hosts that want the origin directly.

pub fn content_to_screen(&self) -> Affine

The affine that maps content space → screen space: scale by zoom then translate to the content origin. A host draws its content under transform * content_to_screen() and everything zooms/pans correctly. Pure function of the current state.

pub fn content_point_to_screen(&self, p: Point) -> Point

Map a single content-space point to screen space.

pub fn screen_to_content(&self, p: Point) -> Point

Map a screen-space point back into content space — the inverse of Self::content_to_screen. Use this to hit-test a pointer event against content. Robust even at extreme zooms (zoom is always >= min_zoom > 0).

pub fn content_contains_screen(&self, p: Point) -> bool

Whether a screen point lands within the content’s drawn area (its scaled rect). Hosts can use it to decide whether a click hits the document or empty viewport margin.

pub fn zoom_at(&mut self, factor: f64, focal: Point)

Zoom by factor (e.g. 1.1 to zoom in 10 %) holding the content point currently under focal (a screen point) stationary, so a Ctrl+wheel zoom tracks the cursor and the content under it doesn’t drift. Clamped to the zoom bounds; a no-op at the bound.

pub fn zoom_by(&mut self, factor: f64)

Zoom by factor holding the viewport centre fixed — the +/- buttons and Ctrl+Plus / Ctrl+Minus path.

pub fn set_zoom(&mut self, zoom: f64)

Set the zoom to an absolute value, holding the viewport centre fixed.

pub fn fit_zoom(&self) -> f64

The zoom that fits the whole content inside the viewport (both axes visible), honouring padding. Clamped to the zoom bounds. Returns 1.0 if the viewport or content is degenerate.

pub fn fit_width_zoom(&self) -> f64

The zoom that fits the content’s width to the viewport.

pub fn reset_to_fit(&mut self)

Reset to fit-the-whole-content zoom, scrolled to the top-left. The Ctrl+0 path.

pub fn zoom_to_rect(&mut self, area: Rect)

Zoom so area (content units) fills the viewport, honouring padding, and centre it as far as the scroll range allows: the “zoom to selection” path. A degenerate area keeps the zoom and only centres.

pub fn pan_by(&mut self, dx: f64, dy: f64)

Pan by a screen-space delta (positive dx/dy reveal content to the right / below). Clamped so the content stays reachable.

pub fn set_scroll(&mut self, scroll_x: f64, scroll_y: f64)

Set the scroll offsets directly (screen px), clamped.

pub fn begin_pan(&mut self, start: Point)

Begin a drag-to-pan at start (screen point). Captures the current scroll so motion maps 1:1.

pub fn update_pan(&mut self, cursor: Point) -> bool

Continue a drag-to-pan: move so the content tracks the cursor. Past PAN_SLOP the drag is flagged as a real pan. Returns true while a pan is in progress. No-op when no pan is active.

pub fn end_pan(&mut self) -> bool

End a drag-to-pan. Returns true if the gesture actually moved the content (so the host can treat a no-move release as a click).

pub fn is_panning(&self) -> bool

Whether a drag-to-pan is currently in progress.

pub fn on_wheel( &mut self, delta: &MouseScrollDelta, modifiers: &ModifiersState, cursor: Point, scale_factor: f64, ) -> bool

Reduce a mouse-wheel event into zoom/pan, mirroring the PDF reader’s mapping:

  • Ctrl/Cmd + wheel → zoom centred on cursor (focal).
  • Shift + wheel (or a horizontal wheel) → horizontal pan.
  • otherwise → vertical pan (with any horizontal wheel component).

cursor is the current pointer position in screen space. Returns true if the viewport consumed the event (it always does when it can scroll/zoom in the requested direction).

pub fn on_key(&mut self, key: &Key, modifiers: &ModifiersState) -> bool

Reduce an arrow-key press into a pan / zoom action. Returns true if the key was consumed. Mapping:

A host that wants the arrow keys to also page-step when the content doesn’t overflow can check Self::overflows_x / Self::overflows_y before delegating here.

pub fn frame_dt(&mut self) -> f64

Record a frame tick and return the clamped seconds since the last call. The viewport has no easing of its own, but exposing the clamped delta lets a host layer smooth-scroll / kinetic motion on top without re-deriving the clock. The first call returns 0.0.

pub fn h_scrollbar_thumb(&self) -> Option<Rect>

The horizontal scrollbar thumb rect (screen space), or None when the content fits horizontally. A host can paint it itself, or rely on DocumentViewport to do so.

pub fn v_scrollbar_thumb(&self) -> Option<Rect>

The vertical scrollbar thumb rect (screen space), or None when the content fits vertically.

pub fn press_scrollbar(&mut self, cursor: Point) -> bool

Hit-test a left-press against either scrollbar. A press on a thumb begins a direct thumb drag; a press on the track pages the view toward the click. Returns true when the press landed on a bar, so the caller suppresses drag-to-pan / child routing beneath it.

pub fn drag_scrollbar(&mut self, cursor: Point) -> bool

Continue an active scrollbar thumb drag, mapping the cursor to a new scroll offset. Returns true while a bar is being dragged.

pub fn scrollbar_dragging(&self) -> bool

Whether a scrollbar thumb drag is in progress.

pub fn release_scrollbar(&mut self) -> bool

End any active scrollbar drag. Returns true when one was in progress.

pub fn update_scrollbar_hover(&mut self, cursor: Point) -> bool

Recompute thumb hover from the cursor; returns true when a hover edge changed (so the caller can schedule a redraw).

pub fn draw_scrollbars( &self, scene: &mut Scene, transform: Affine, theme: &Theme, )

Paint the scrollbars (when present) into scene. Reads the scrollbar/thumb color from the theme so it matches OS chrome. Both DocumentViewport and a canvas-root host call this after drawing content. The thumb brightens while hovered or dragged.

Trait Implementations§

§

impl Clone for ViewportState

§

fn clone(&self) -> ViewportState

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for ViewportState

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Default for ViewportState

§

fn default() -> ViewportState

Returns the “default value” for a type. Read more

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
§

impl<T> Downcast<T> for T

§

fn downcast(&self) -> &T

§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync> ⓘ

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> NoneValue for T
where T: Default,

§

type NoneType = T

§

fn null_value() -> T

The none-equivalent value.
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
§

impl<T, S> SimdFrom<T, S> for T
where S: Simd,

§

fn simd_from(_simd: S, value: T) -> T

§

impl<F, T, S> SimdInto<T, S> for F
where T: SimdFrom<F, S>, S: Simd,

§

fn simd_into(self, simd: S) -> T

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.
§

impl<T> Upcast<T> for T

§

fn upcast(&self) -> Option<&T>

§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<T> ErasedDestructor for T
where T: 'static,

§

impl<T> Fruit for T
where T: Send + Downcast,

§

impl<T> MaybeSendSync for T
where T: Send + Sync + ?Sized,

§

impl<T> WasmNotSend for T
where T: Send,

§

impl<T> WasmNotSendSync for T

§

impl<T> WasmNotSync for T
where T: Sync,