common

package
v1.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 24, 2026 License: BSD-3-Clause Imports: 29 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	TapMoveDecay        = 0.92                   // scroll continue decay per frame
	TapMoveEndThreshold = 2.0                    // offset threshold to stop decay
	TapMoveThreshold    = 4.0                    // movement before drag begins
	TapSecondaryDelay   = 300 * time.Millisecond // long-press for secondary tap
	TapDoubleDelay      = 500 * time.Millisecond // max gap between double-tap
)

Tap handling constants shared by mobile and embedded drivers.

Variables

View Source
var DonePool = async.Pool[chan struct{}]{
	New: func() chan struct{} {
		return make(chan struct{})
	},
}

Functions

func BuiltinKeyboardShortcut

func BuiltinKeyboardShortcut(key event.KeyName, clip bellui.Clipboard) core.Shortcut

BuiltinKeyboardShortcut returns the standard editing shortcut bound to a key pressed with the platform shortcut modifier held (Control, or Super on macOS), or nil when the key is not one of the built-ins. Clipboard shortcuts (Copy/Cut/Paste) are given clip. Shared by the desktop (glfw) and mobile drivers so both map the same keys to the same shortcuts (pre-rebrand tracker #1077).

func CanvasForObject

func CanvasForObject(obj core.CanvasObject) core.Canvas

CanvasForObject returns the canvas for the specified object.

func ClampRegionToCanvas added in v1.2.0

func ClampRegionToCanvas(pos geo.Position, sz geo.Size, size geo.Size) (geo.Position, geo.Size)

ClampRegionToCanvas intersects a dirty region with the canvas [0,0]-(size) box, returning a zero-size region when it falls entirely outside.

func CullOffClip added in v1.2.0

func CullOffClip(obj core.CanvasObject, pos, clipPos geo.Position, clipSize geo.Size) bool

CullOffClip is the paint walk's CullFunc: it culls a clip-owner (a scroll, a ClipToBounds container, a rounded clip such as a Card) whose bounds, widened by cullMargin and by its own shadow, miss the clip. A clip-owner's descendants draw inside its bounds, so nothing of the subtree can show. An object that owns no clip may draw outside its bounds, and is never culled.

func DragDecay

func DragDecay(delta geo.Delta) geo.Delta

DragDecay implements momentum-based scroll decay after a drag ends. Call this from a ticker/animation callback, passing the last drag delta. Returns the decayed delta, or zero if below threshold.

func InDirtyRegion added in v1.2.0

func InDirtyRegion(pos geo.Position, size geo.Size, rPos geo.Position, rSize geo.Size) bool

InDirtyRegion reports whether the rect (pos, size) needs repainting under a partial repaint of the region (rPos, rSize). An empty region, a frame with nothing dirty, holds nothing. By overlap alone, a rect reaching across the empty region at (0, 0) would count as inside it and be painted unclipped, over pixels nothing else repainted (#605).

func PaintBounds added in v1.3.0

func PaintBounds(node *RenderCacheNode) (geo.Position, geo.Size)

PaintBounds returns the world-space box node's object paints in: its painter.PaintExtent, through its world transform.

func PaintBoundsAt added in v1.3.0

func PaintBoundsAt(obj core.CanvasObject, m geo.Matrix) (geo.Position, geo.Size)

PaintBoundsAt is PaintBounds for obj with world transform m.

func PaintClips added in v1.2.0

func PaintClips(node *RenderCacheNode) driver.Clips

PaintClips is the clips a paint walk sets up for node's object: none for a clip-owner whose children the walk culled, as they would constrain nothing (#481). Each one costs the painter a stencil or scissor change.

A rectangle clip that its world transform turns or skews is also a stencil clip with no corner radius, stamped with that transform: the scissor can only hold the box around the turned rectangle, so alone it would let the children show in that box's corners (#1003). The scissor stays, as the bound of the stencil's area. A scale or a move keeps the rectangle upright, and the scissor alone is exact.

func RectsOverlap

func RectsOverlap(aPos geo.Position, aSize geo.Size, bPos geo.Position, bSize geo.Size) bool

RectsOverlap reports whether two axis-aligned rectangles intersect. Used by the drivers to cull objects that fall outside the partial-repaint region.

func RegionCoversCanvas

func RegionCoversCanvas(region, canvas geo.Size) bool

RegionCoversCanvas reports whether a dirty region is large enough that a partial repaint saves little, so a plain full clear is preferable.

func WorldBox added in v1.3.0

func WorldBox(m geo.Matrix, size geo.Size) (geo.Position, geo.Size)

WorldBox is the canvas box an object of size size with world transform m covers: its own box moved, or under a rotation or skew the bounding box of where m puts it (#997). A clipping object clips its children to it.

Types

type BoundaryGeometry added in v1.2.0

type BoundaryGeometry struct {
	// Origin is the texture's top-left corner, where it is blitted: the
	// boundary's position snapped down to a device pixel, less the margin.
	Origin geo.Position
	// PixW and PixH are the texture's size in device pixels, covering the
	// boundary and the margin around it.
	PixW, PixH int
	// Size is the texture's size in canvas units.
	Size geo.Size
	// Phase is how far the boundary's content sits from the pixel grid.
	Phase BoundaryPhase
}

BoundaryGeometry is where a RepaintBoundary is rendered and drawn.

func BoundaryGeometryFor added in v1.2.0

func BoundaryGeometryFor(pos geo.Position, size geo.Size, pxPerUnit float32) BoundaryGeometry

BoundaryGeometryFor places a RepaintBoundary at pos with size, on a canvas of pxPerUnit device pixels per unit. Rendering its content at pos - Origin keeps the sub-pixel offset it would have drawn directly, and blitting the texture at Origin is a copy, pixel for pixel. A texture placed at pos instead drew its content on another sub-pixel grid and resampled it, so edges came out differently from drawing in place (#570).

type BoundaryPhase added in v1.2.0

type BoundaryPhase struct{ X, Y int32 }

BoundaryPhase is the sub-pixel offset, in 1/boundaryPhaseSteps of a device pixel, of a RepaintBoundary's content from the pixel grid.

type Canvas

type Canvas struct {
	OnFocus   func(obj event.Focusable)
	OnUnfocus func()

	// FixedSize is set by drivers whose window cannot grow to fit its content
	// (the browser, where the window is the page's viewport). Content larger
	// than the canvas is then clipped instead of the canvas growing past the
	// window: a canvas laid out wider than the viewport was drawn squeezed
	// into it until the next window resize (#387).
	FixedSize bool
	// contains filtered or unexported fields
}

Canvas defines common canvas implementation.

func (*Canvas) AddShortcut

func (c *Canvas) AddShortcut(shortcut core.Shortcut, handler func(shortcut core.Shortcut))

AddShortcut adds a shortcut to the canvas.

func (*Canvas) CheckDirtyAndClear

func (c *Canvas) CheckDirtyAndClear() bool

CheckDirtyAndClear returns true if the canvas is dirty and clears the dirty state. Call it on the main goroutine only: the flag has no lock.

func (*Canvas) CullOffClip added in v1.2.0

func (c *Canvas) CullOffClip(obj core.CanvasObject, pos, clipPos geo.Position, clipSize geo.Size) bool

CullOffClip is the package's CullOffClip for a walk's CullFunc. For the object the walk is about to visit it answers from that object's node, which remembers its clip and shadow reach (#599); for any other object it asks the renderer, as CullOffClip does.

func (*Canvas) Direction

func (c *Canvas) Direction() bellui.Direction

Direction returns the per-canvas user-interface direction set by Canvas.SetDirection. The default github.com/belluikit/bellui.DirectionAuto defers to the process-global github.com/belluikit/bellui.SetLayoutDirection.

func (*Canvas) DirtyRegion

func (c *Canvas) DirtyRegion() (pos geo.Position, size geo.Size, set bool)

DirtyRegion returns the accumulated dirty region from the last FreeDirtyTextures call. If set is false, the region is undefined and a full repaint is needed.

func (*Canvas) DrawDebugOverlay

func (c *Canvas) DrawDebugOverlay(obj core.CanvasObject, pos geo.Position, size geo.Size)

func (*Canvas) EnsureMinSize

func (c *Canvas) EnsureMinSize() bool

EnsureMinSize ensure canvas min size.

This function uses lock.

func (*Canvas) Focus

func (c *Canvas) Focus(obj event.Focusable)

Focus makes the provided item focused.

func (*Canvas) FocusGained

func (c *Canvas) FocusGained()

FocusGained signals to the manager that its content got focus. Valid only on Desktop.

func (*Canvas) FocusLost

func (c *Canvas) FocusLost()

FocusLost signals to the manager that its content lost focus. Valid only on Desktop.

func (*Canvas) FocusNext

func (c *Canvas) FocusNext()

FocusNext focuses the next focusable item.

func (*Canvas) FocusPrevious

func (c *Canvas) FocusPrevious()

FocusPrevious focuses the previous focusable item.

func (*Canvas) Focused

func (c *Canvas) Focused() event.Focusable

Focused returns the current focused object.

func (*Canvas) FreeDirtyTextures

func (c *Canvas) FreeDirtyTextures() uint64

FreeDirtyTextures frees the textures of the objects refreshed since it last ran, and returns how many of them are in sight: those under a hidden object need no frame (#1061).

func (*Canvas) InSight added in v1.3.0

func (c *Canvas) InSight(obj core.CanvasObject) bool

InSight reports whether obj is in sight in this canvas' trees: the last walk placed it, and it and every object above it are still visible. One hidden since, by Hide or a tab switch, is out of sight at once, without waiting for the next walk (bellui.IsOnScreen). So is one shown again at once, before the walk that places it (#1069): see shownAgain. Call it on the main goroutine, which walks the trees.

func (*Canvas) Initialize

func (c *Canvas) Initialize(impl SizeableCanvas, onOverlayChanged func())

Initialize initializes the canvas.

func (*Canvas) IsDirty

func (c *Canvas) IsDirty() bool

IsDirty reports whether the canvas has changes that have not been painted yet, without clearing the flag. Call it on the main goroutine only. While it is true the spatial index has not been rebuilt since the last change, so hit testing must not rely on it.

func (*Canvas) MarkDirtyRect added in v1.2.0

func (c *Canvas) MarkDirtyRect(pos geo.Position, size geo.Size)

MarkDirtyRect adds a rect to the next PartialDirtyRegion. A driver that paints something no canvas object stands for, such as the mobile screen-reader focus ring, marks where it was and where it will be, so the region clears the one and redraws the content under the other (#551).

func (*Canvas) MarkFullRepaint added in v1.2.0

func (c *Canvas) MarkFullRepaint()

MarkFullRepaint tells PartialDirtyRegion that the frame being painted is a full repaint that did not ask it for a region, so the bounds it recorded are no longer those on screen.

It also takes the nodes queued for a region walk, since this frame repaints everything they could have reported. Only PartialDirtyRegion took them, and after a mobile background→resume no frame asks it for a region again (the mobile driver's surfaceShown, pre-rebrand tracker #342), so every node added from then on stayed queued, with its object, for the life of the canvas: an app rebuilding a tab bar ten times a second kept 26 MB of nodes in 26 minutes (daysong#365).

func (*Canvas) MarkMinSizeDirty added in v1.2.0

func (c *Canvas) MarkMinSizeDirty(obj core.CanvasObject)

MarkMinSizeDirty records that obj may report a different min size, so the next EnsureMinSize asks it again (#464). Refresh calls it; BaseWidget.Refresh calls it for the widget itself, whose renderer may refresh only its parts. Safe from any goroutine.

func (*Canvas) MarkPlacementDirty added in v1.2.0

func (c *Canvas) MarkPlacementDirty(obj core.CanvasObject)

MarkPlacementDirty records that obj may have moved, been resized or been hidden, so the next partial-repaint region walks from its node. An object with no node is not drawn, or is under one a walk reaches anyway: a new object is added through a container or widget that reports, and a shown one through paintgen. Safe from any goroutine.

func (*Canvas) MinSizeVisits added in v1.2.0

func (c *Canvas) MinSizeVisits() int

MinSizeVisits reports how many nodes the last EnsureMinSize visited.

func (*Canvas) NodeFor

func (c *Canvas) NodeFor(obj core.CanvasObject) (*RenderCacheNode, bool)

NodeFor returns the RenderCacheNode for the given object, if it exists.

func (*Canvas) ObjectTrees

func (c *Canvas) ObjectTrees() []core.CanvasObject

ObjectTrees return canvas object trees.

This function uses lock.

func (*Canvas) Overlays

func (c *Canvas) Overlays() core.OverlayStack

Overlays returns the overlay stack.

func (*Canvas) Painter

func (c *Canvas) Painter() gpu.Painter

Painter returns the canvas painter.

func (*Canvas) PartialDirtyRegion

func (c *Canvas) PartialDirtyRegion() (pos geo.Position, size geo.Size, set bool)

PartialDirtyRegion runs a draw-free walk that recomputes world transforms and returns the region of the canvas that must be cleared and redrawn this frame: the union, over every object that was refreshed or has moved/resized since the previous paint, of both its previous and its current world-space bounds (so a move clears where it left as well as where it lands), padded for anti-aliased edges. Refreshed objects additionally contribute their whole subtree so overflow children (shadows, ripples, focus rings) are covered. Each node's recorded bounds are advanced to the current frame. set is false when nothing changed, in which case the caller can skip the redraw entirely.

When the refreshed objects' previous bounds alone cover most of the canvas, the region would too, so it returns the whole canvas without walking; the first later call that cannot skip walks to record the bounds again, and also returns the whole canvas (#496). So does the call after a full repaint the caller did without asking for a region (MarkFullRepaint).

It walks from the nodes reported moved, resized, hidden or refreshed since the last call, not from the roots, unless something no node can report changed (region.go, #599).

Only meaningful under the partialrepaint build tag; the per-node bookkeeping it relies on is otherwise never populated.

func (*Canvas) RebuildSpatialIndex

func (c *Canvas) RebuildSpatialIndex()

RebuildSpatialIndex walks the render cache trees and populates a new SpatialIndex from the cached world transforms and clip bounds.

func (*Canvas) Refresh

func (c *Canvas) Refresh(obj core.CanvasObject)

Refresh refreshes a canvas object.

func (*Canvas) RegionVisits added in v1.2.0

func (c *Canvas) RegionVisits() int

RegionVisits reports how many nodes the last PartialDirtyRegion visited.

func (*Canvas) ReleaseDropped added in v1.3.0

func (c *Canvas) ReleaseDropped()

ReleaseDropped asks the next frame's walk to release what the caches and the painter hold for content the app took out of the canvas, as it does for replaced content (bellui.Release, #1083). It marks the canvas dirty so that frame comes. Call it on the main goroutine.

func (*Canvas) RemoveShortcut

func (c *Canvas) RemoveShortcut(shortcut core.Shortcut)

RemoveShortcut removes a shortcut from the canvas.

func (*Canvas) SetContentTreeAndFocusMgr

func (c *Canvas) SetContentTreeAndFocusMgr(content core.CanvasObject)

SetContentTreeAndFocusMgr sets content tree and focus manager.

This function does not use the canvas lock.

func (*Canvas) SetDirection

func (c *Canvas) SetDirection(d bellui.Direction)

SetDirection overrides the user-interface direction for this canvas' whole content, regardless of the process-global setting, so one window can flow left-to-right inside a right-to-left application (or vice versa). Passing github.com/belluikit/bellui.DirectionAuto restores the global setting. The content is re-laid-out and repainted to apply the change.

func (*Canvas) SetDirty

func (c *Canvas) SetDirty()

SetDirty marks the canvas as needing a paint. Call it on the main goroutine only: the flag has no lock.

func (*Canvas) SetMenuTreeAndFocusMgr

func (c *Canvas) SetMenuTreeAndFocusMgr(menu core.CanvasObject)

SetMenuTreeAndFocusMgr sets menu tree and focus manager.

This function does not use the canvas lock.

func (*Canvas) SetMobileWindowHeadTree

func (c *Canvas) SetMobileWindowHeadTree(head core.CanvasObject)

SetMobileWindowHeadTree sets window head tree.

This function does not use the canvas lock.

func (*Canvas) SetPainter

func (c *Canvas) SetPainter(p gpu.Painter)

SetPainter sets the canvas painter.

func (*Canvas) SpatialIndex

func (c *Canvas) SpatialIndex() *SpatialIndex

SpatialIndex returns the current spatial index for broadphase hit testing. May return nil if the index has not been built yet.

func (*Canvas) TypedShortcut

func (c *Canvas) TypedShortcut(shortcut core.Shortcut)

TypedShortcut handle the registered shortcut.

func (*Canvas) Unfocus

func (c *Canvas) Unfocus()

Unfocus unfocuses all the objects in the canvas.

func (*Canvas) WalkContentTrees

func (c *Canvas) WalkContentTrees(
	beforeChildren func(*RenderCacheNode, geo.Position),
	afterChildren func(*RenderCacheNode, geo.Position),
)

WalkContentTrees walks content, window head, and menu trees (not overlays).

func (*Canvas) WalkContentTreesCulled added in v1.2.0

func (c *Canvas) WalkContentTreesCulled(
	cull driver.CullFunc,
	beforeChildren func(*RenderCacheNode, geo.Position),
	afterChildren func(*RenderCacheNode, geo.Position),
)

WalkContentTreesCulled walks the content trees as WalkContentTrees does, visiting an object cull reports as drawing nothing visible without its children (driver.WalkVisibleObjectTreeCulled). The paint walk passes CullOffClip, so content scrolled out of view costs one visit per clip-owner instead of its whole subtree (#464). Walks that must reach every object (layout, hit testing, accessibility) pass nil.

func (*Canvas) WalkOverlayTrees

func (c *Canvas) WalkOverlayTrees(
	beforeChildren func(*RenderCacheNode, geo.Position),
	afterChildren func(*RenderCacheNode, geo.Position),
)

WalkOverlayTrees walks overlay trees only.

func (*Canvas) WalkTrees

func (c *Canvas) WalkTrees(
	beforeChildren func(*RenderCacheNode, geo.Position),
	afterChildren func(*RenderCacheNode, geo.Position),
)

WalkTrees walks over all trees (content, menu, overlays) and rebuilds the spatial index.

type DragCoast added in v1.3.0

type DragCoast struct {
	// contains filtered or unexported fields
}

DragCoast carries a released touch drag on with decaying deltas (DragDecay, about 60 steps a second) and then ends it, for the drivers that give touch drags momentum (mobile, embedded) — only for Draggables that ask for it (event.MomentumDraggable, #751). A driver keeps one and calls Stop before it delivers any new touch, so a touch during a coast stops it dead (#751).

Release and Stop run on the main goroutine. The coast's own goroutine only sleeps and queues steps: each step, and the final DragEnd, runs on the main goroutine through the driver's queue and checks there that its coast is still the current one. Since Stop runs on the main goroutine too, a step queued before a Stop but run after it finds its coast replaced and does nothing, so no step and no DragEnd from a stopped coast reaches the Draggable after the new touch went down.

func (*DragCoast) Release added in v1.3.0

func (c *DragCoast) Release(wid event.Draggable, ev *event.DragEvent, do func(func()))

Release ends a touch drag released with ev on wid, whose Dragged is the momentum seed (TouchHandler.TapUp sets it from the finger's speed at release). Only a Draggable that opts in through event.MomentumDraggable coasts (#751); any other, and a slow release, ends the drag at once. A coasting one queues each step and the final DragEnd with do, which must run its function on the main goroutine.

func (*DragCoast) Stop added in v1.3.0

func (c *DragCoast) Stop() bool

Stop ends a running coast now: its Draggable gets DragEnd before Stop returns, so before whatever the caller dispatches next, and nothing the coast already queued reaches it afterwards. Without a coast it does nothing. It reports whether it stopped one, so the touch that did can be kept from also tapping (TouchHandler.CatchCoast, #792).

type ObjectFinder

type ObjectFinder interface {
	FindObjectAtPositionMatching(pos geo.Position, test func(core.CanvasObject) bool) (core.CanvasObject, geo.Position, int)
	// FindEnabledObjectAtPositionMatching is FindObjectAtPositionMatching
	// that also reports whether the object found lies inside a disabled
	// widget (driver.InertUnder, #1378).
	FindEnabledObjectAtPositionMatching(pos geo.Position, test func(core.CanvasObject) bool) (core.CanvasObject, geo.Position, int, bool)
	CanvasForTouch() core.Canvas
}

ObjectFinder locates objects at a position on a canvas. This abstracts the difference between mobile (uses overlay stack) and embedded (uses FindObjectAtPositionMatching directly).

type RenderCacheNode

type RenderCacheNode struct {
	// contains filtered or unexported fields
}

RenderCacheNode represents a node in a render cache tree.

func (*RenderCacheNode) BoundaryRenderedAt added in v1.2.0

func (r *RenderCacheNode) BoundaryRenderedAt(phase BoundaryPhase) bool

BoundaryRenderedAt reports whether node's RepaintBoundary texture was rendered at phase. A clean texture rendered at another phase holds its content on another sub-pixel grid, so it must be rendered again.

func (*RenderCacheNode) CachesAsBoundary added in v1.3.0

func (r *RenderCacheNode) CachesAsBoundary() bool

CachesAsBoundary reports whether the paint walks draw this node through its RepaintBoundary texture: it is a boundary, and its world transform at most moves it. The texture is blitted axis-aligned and unscaled, so under a rotation, a scale or a skew, on the boundary or above it, the walks draw the subtree directly instead, and use the texture again once the transform is back to a move (#1003).

func (*RenderCacheNode) IsBoundary

func (r *RenderCacheNode) IsBoundary() bool

IsBoundary returns true if this node is a RepaintBoundary.

func (*RenderCacheNode) Obj

Obj returns the node object.

func (*RenderCacheNode) PaintOrigin added in v1.3.0

func (r *RenderCacheNode) PaintOrigin() geo.Position

PaintOrigin is where the node's object is drawn from: its world transform's image of the object's origin, (0, 0) in its own coordinates (#997). With no transform above or on it, that is the walk position. A transform's translation, a pivot's and a transformed ancestor's all move it; a painter applies the transform's linear part about it.

func (*RenderCacheNode) Parent

func (r *RenderCacheNode) Parent() *RenderCacheNode

Parent returns the parent node, or nil for root nodes.

func (*RenderCacheNode) SetBoundaryRenderedAt added in v1.2.0

func (r *RenderCacheNode) SetBoundaryRenderedAt(phase BoundaryPhase)

SetBoundaryRenderedAt records the phase node's RepaintBoundary texture was rendered at.

func (*RenderCacheNode) WorldTransform

func (r *RenderCacheNode) WorldTransform() geo.Matrix

WorldTransform returns the composed affine transform from root to this node. It incorporates all ancestor transforms plus this node's local transform.

type SizeableCanvas

type SizeableCanvas interface {
	core.Canvas
	Resize(geo.Size)
	MinSize() geo.Size
}

SizeableCanvas defines a canvas with size related functions.

type SpatialIndex

type SpatialIndex struct {
	// contains filtered or unexported fields
}

SpatialIndex provides O(1) broadphase hit testing via a uniform grid.

The canvas is divided into cells of fixed size. Each cell lists the [spatialEntry] values whose screen-space AABB overlaps that cell. Entries are inserted in DFS order during the tree walk so that within each cell the last matching entry is the deepest (innermost) object — matching the existing "last match wins" semantics.

Each entry is stored once, in entries; a cell holds int32 indices into it, all cells packed into one items slice (cell i is items[cellStart[i]: cellStart[i+1]]). Copying the entry into every cell it overlapped made a full-window background ~510 entry copies, and with the slices regrown from zero each paint the rebuild was 81% of a static frame's allocation (#435). The slices are reused by reset, so a canvas rebuilding every paint allocates only when the scene outgrows them.

The index is immutable once built and safe for concurrent reads.

func (*SpatialIndex) FindAllObjectsAtPositionMatching

func (idx *SpatialIndex) FindAllObjectsAtPositionMatching(
	mouse geo.Position,
	matches func(core.CanvasObject) bool,
) []driver.ObjectAtPosition

FindAllObjectsAtPositionMatching returns all matching objects at mouse, ordered from deepest (innermost) to shallowest (outermost). This is used for scroll event propagation.

func (*SpatialIndex) FindEnabledObjectAtPositionMatching added in v1.3.0

func (idx *SpatialIndex) FindEnabledObjectAtPositionMatching(
	mouse geo.Position,
	matches func(core.CanvasObject) bool,
) (core.CanvasObject, geo.Position, bool, bool)

FindEnabledObjectAtPositionMatching is FindObjectAtPositionMatching that also reports whether the object found lies inside a disabled widget (driver.InertUnder, #1378).

func (*SpatialIndex) FindObjectAtPositionMatching

func (idx *SpatialIndex) FindObjectAtPositionMatching(
	mouse geo.Position,
	matches func(core.CanvasObject) bool,
) (core.CanvasObject, geo.Position, bool)

FindObjectAtPositionMatching finds the deepest object at mouse whose screen-space AABB and clip bounds contain the point, that passes the narrowphase inverse-transform test, and for which matches returns true.

The return values mirror driver.FindObjectAtPositionMatching: the matched object, the mouse position in object-local coordinates, and a boolean indicating whether a match was found.

type TouchHandler

type TouchHandler struct {
	Finder ObjectFinder

	LastTapDown    map[int]time.Time
	LastTapDownPos map[int]geo.Position
	LastTapDelta   map[int]geo.Delta

	DragOffset geo.Position
	DragStart  geo.Position
	Dragging   event.Draggable

	Touched         map[int]mobile.Touchable
	TouchCancelFunc context.CancelFunc
	TouchCancelLock sync.Mutex
	TouchLastTapped core.CanvasObject
	TouchTapCount   int

	// OnTapFocused, when set, is called for a tap on the widget that already
	// has the focus, before the tap is delivered. The mobile driver uses it to
	// bring back an on-screen keyboard the system hid while the widget kept
	// the focus: its Done key, Back, or the keyboard's own hide key (#822,
	// #806). A drag or scroll is not a tap and does not call it.
	OnTapFocused func(event.Focusable)

	// OnTapUp is an optional hook called at the start of TapUp, before
	// tap/drag processing. If it returns true, tap processing is skipped
	// (the hook handled the event). Used by mobile for menu dismissal.
	OnTapUp func(pos geo.Position) bool

	// ScrollCallback, when set by the driver, enables touch flick-scrolling of
	// scrollable content (#291): a move past the tap slop that latches no
	// Draggable but began over an event.Scrollable becomes a scroll gesture —
	// every move calls this with the gesture origin and the move's delta, and
	// the driver turns it into a touch-sourced ScrollEvent (which buys nested
	// propagation from its scroll dispatch). It also carries two-finger pans
	// (pinch.go, #398). Where the Scroll is itself Draggable (the mobile
	// driver, #402) a one-finger drag latches the Scroll first, so setting this
	// there only adds the two-finger pan. A driver that leaves it nil gets
	// neither, and two fingers over a Pinchable always pinch.
	ScrollCallback func(origin geo.Position, delta geo.Delta)
	// ScrollEndCallback is called when a scroll gesture's contact lifts, with
	// the momentum seed: the distance the finger was covering per momentum
	// step when it let go, from its recent moves (velocity.go), and nothing
	// when it was held still before lifting (#751). A system cancel ends the
	// gesture without it — momentum from a contact the system took over would
	// keep content moving after a palm rejection.
	ScrollEndCallback func(origin geo.Position, delta geo.Delta)

	// LongPressCallback, when set by the driver, enables hold-fire long-press
	// (pre-rebrand tracker #758): a stationary touch dispatches LongPressed at TapSecondaryDelay
	// while the finger is still down — native mobile behavior — instead of on
	// release. The release of a hold-fired touch then dispatches
	// SecondaryTappable, so a widget implementing both gets "select on hold,
	// menu on lift". Targets that are not LongPressable keep the release-time
	// handling in TapUp unchanged.
	LongPressCallback func(event.LongPressable, *event.PointEvent)
	// contains filtered or unexported fields
}

TouchHandler implements tap, drag, and double-tap event handling logic shared between mobile and embedded drivers. Embed this struct and provide an ObjectFinder.

func (*TouchHandler) CancelPendingTap added in v1.1.0

func (h *TouchHandler) CancelPendingTap()

CancelPendingTap abandons a double-tap wait that has not fired yet. Call it when the canvas those taps were dispatched against goes away — a window closing, a driver shutting down.

Cancelling the context alone is not enough and never was: that is how a SECOND tap tells the waiter to fire early as a double tap, so it makes the dispatch happen rather than preventing it. The generation bump is what distinguishes "fire now" from "do not fire at all".

func (*TouchHandler) CatchCoast added in v1.3.0

func (h *TouchHandler) CatchCoast(tapID int)

CatchCoast marks the contact about to go down (TapDown with tapID) as the one that stopped moving content: a drag's coast or a scroll's momentum. As on Android and iOS, a touch that catches a fling only stops it. It taps, double-taps and long-presses nothing, so stopping a list to read it does not select a row (#792). It can still drag or scroll from there. The driver calls it just before TapDown.

func (*TouchHandler) InitTouchHandler

func (h *TouchHandler) InitTouchHandler(finder ObjectFinder)

InitTouchHandler initializes the maps. Call from the canvas constructor.

func (*TouchHandler) SetClock added in v1.3.0

func (h *TouchHandler) SetClock(now func() time.Time)

SetClock sets the clock the velocity samples are stamped with; nil is time.Now. A driver's tests step it, so whether a release coasts does not depend on how fast the test machine hands the driver its events (#786).

func (*TouchHandler) TapCancel

func (h *TouchHandler) TapCancel(pos geo.Position, tapID int)

TapCancel handles a system-cancelled touch sequence (the desktop driver's glfw TouchCancel, #266): the system took the contact over — e.g. a palm rejection or an edge gesture — so the gesture must end without dispatching any tap. A pending hold-fire and tooltip are cancelled, a Touchable gets TouchCancel, and a drag this contact latched gets DragEnd (the drag's effect so far stands; there is no undo protocol for Draggable) — a drag some other contact owns is left alone, which is the point of a palm rejection arriving mid-drag. pos is the last known contact position — it may be zero where the platform does not report one, so it is used for the cancel event only, never for hit testing.

func (*TouchHandler) TapDown

func (h *TouchHandler) TapDown(pos geo.Position, tapID int)

TapDown handles a pointer-down event.

func (*TouchHandler) TapMove

func (h *TouchHandler) TapMove(pos geo.Position, tapID int,
	dragCallback func(event.Draggable, *event.DragEvent),
)

TapMove handles a pointer-move event (potential drag).

func (*TouchHandler) TapUp

func (h *TouchHandler) TapUp(pos geo.Position, tapID int,
	tapCallback func(event.Tappable, *event.PointEvent),
	tapAltCallback func(event.SecondaryTappable, *event.PointEvent),
	longPressCallback func(event.LongPressable, *event.PointEvent),
	doubleTapCallback func(event.DoubleTappable, *event.PointEvent),
	dragCallback func(event.Draggable, *event.DragEvent),
)

TapUp handles a pointer-up event (tap, secondary tap, long-press, or drag end).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL