Input events
Bellui delivers input to an object by checking which interfaces it
implements. There is no event registration: if the object under the pointer
has a Tapped method with the right signature, a click calls it. The
interfaces are in the event
package.
Ready-made widgets already implement the interfaces they need; a button is
Tappable, an entry is Focusable. You implement them yourself when you
build a widget. The canvas primitives implement
none of them, by design.
A widget that receives everything
This widget implements every pointer interface except DoubleTappable (see
the warning below) and reports what it gets:
// pad is a widget that implements several event interfaces. The toolkit
// checks which interfaces an object has and delivers matching events.
type pad struct {
widget.BaseWidget
bg *canvas.Rectangle
log func(string)
}
func newPad(log func(string)) *pad {
p := &pad{bg: canvas.NewRectangle(color.NRGBA{R: 0x3b, G: 0x6e, B: 0xc8, A: 0xff}), log: log}
p.ExtendBaseWidget(p)
return p
}
func (p *pad) CreateRenderer() core.WidgetRenderer {
return widget.NewSimpleRenderer(p.bg)
}
// event.Tappable: a click or a tap.
func (p *pad) Tapped(e *event.PointEvent) { p.log(fmt.Sprintf("Tapped at %v", e.Position)) }
// event.SecondaryTappable: a right-click on desktop.
func (p *pad) TappedSecondary(*event.PointEvent) { p.log("TappedSecondary") }
// event.LongPressable: press and hold.
func (p *pad) LongPressed(*event.PointEvent) { p.log("LongPressed") }
// event.Hoverable: the pointer enters, moves over and leaves (desktop and web).
func (p *pad) HoverIn(*event.HoverEvent) { p.log("HoverIn") }
func (p *pad) HoverMoved(*event.HoverEvent) {}
func (p *pad) HoverOut() { p.log("HoverOut") }
// event.Draggable: the pointer moves while pressed.
func (p *pad) Dragged(e *event.DragEvent) { p.log(fmt.Sprintf("Dragged by %v", e.Dragged)) }
func (p *pad) DragEnd() { p.log("DragEnd") }
// event.Scrollable: a mouse wheel or touchpad scroll.
func (p *pad) Scrolled(e *event.ScrollEvent) { p.log(fmt.Sprintf("Scrolled %v", e.Scrolled)) }widget.BaseWidget, ExtendBaseWidget and CreateRenderer are explained
in Custom widgets. Every event method runs on the
main goroutine.
Pointer interfaces
| Interface | Methods | Delivered when |
|---|---|---|
Tappable | Tapped(*PointEvent) | A click or tap is pressed and released on the object |
DoubleTappable | DoubleTapped(*PointEvent) | Two taps in quick succession |
SecondaryTappable | TappedSecondary(*PointEvent) | A right-click on desktop; on touch, see below |
LongPressable | LongPressed(*PointEvent) | The pointer is held down without moving |
Hoverable | HoverIn, HoverMoved, HoverOut | A mouse pointer enters, moves over, or leaves the object |
Draggable | Dragged(*DragEvent), DragEnd() | The pointer moves while pressed, and then is released |
Scrollable | Scrolled(*ScrollEvent) | A mouse wheel or touchpad scrolls over the object |
Pinchable | Pinched(*PinchEvent), PinchEnded() | Two fingers on the object move apart or together; PinchEnded once when either lifts |
A PointEvent
has Position, relative to the object’s top-left corner, and
AbsolutePosition, relative to the window. DragEvent.Dragged and
ScrollEvent.Scrolled are a geo.Delta:
how far the pointer moved since the last event. ScrollEvent.Source says
whether a scroll came from a mouse wheel, a touchpad or a touch gesture.
A PinchEvent
is a PointEvent at the point between the fingers, plus Scale: the change
since the previous event, above 1 when the fingers moved apart. Multiply
successive values for the total zoom.
DoubleTappable, a single tap is not delivered
straight away. The toolkit waits to see whether a second tap follows, and
calls Tapped only after that delay has passed. Implement DoubleTappable
only when you need it.Desktop and touch
The same interfaces work on every platform, but some gestures map differently:
| Gesture | Desktop and web | Touch |
|---|---|---|
| Tap | Primary button click | Finger tap |
| Secondary tap | Right-click | Lifting the finger after a press and hold |
| Long press | Holding the primary button down; it fires while the button is still down, and the release does not also deliver Tapped | Holding a finger still; it fires while the finger is still down |
| Hover | Mouse movement | Not delivered: there is no pointer between touches |
| Scroll | Mouse wheel or touchpad | Dragging a finger over scrollable content, such as a scroll container, or two fingers moving together anywhere |
| Pinch | Not delivered from a trackpad yet | Two fingers moving apart or together, when both are on a Pinchable |
On touch, a widget that implements both LongPressable and
SecondaryTappable gets LongPressed while the finger is held, and then
TappedSecondary when it lifts.
A pinch starts only when both fingers land on the same Pinchable. Two
fingers on widgets either side of it, such as a slider and a button, keep
their own drag and tap. Neither finger of a pinch or a two-finger scroll
produces a tap or a drag. Two fingers moving together scroll the content
under them, so a page of charts or 3D views, which keep one-finger drags for
themselves, still scrolls.
Drags on touch screens
Two optional interfaces refine how a Draggable behaves under a finger. They
change nothing for a mouse drag.
// strip pans its content left and right when dragged.
type strip struct {
widget.BaseWidget
offset float32
text *canvas.Text
}
func newStrip() *strip {
s := &strip{text: canvas.NewText("", color.NRGBA{R: 0x3b, G: 0x6e, B: 0xc8, A: 0xff})}
s.ExtendBaseWidget(s)
return s
}
// event.Draggable: move the content with the pointer.
func (s *strip) Dragged(e *event.DragEvent) {
s.offset += e.Dragged.DX
s.Refresh()
}
func (s *strip) DragEnd() {}
// event.DragClaimer: on touch, take a drag only when it starts sideways.
// An upward or downward drag goes on to the scroll around the strip.
func (s *strip) ClaimsDrag(d geo.Delta) bool {
return abs(d.DX) > abs(d.DY)
}
// event.MomentumDraggable: on touch, keep moving after a fast release,
// because the strip pans content rather than being moved itself.
func (s *strip) DragMomentum() bool { return true }event.DragClaimerlets a widget take a touch drag in some directions only. When a finger starts to drag, Bellui asks theDraggablewidgets under it, innermost first, withClaimsDrag(delta), wheredeltais the first movement. The first one that returns true gets the drag until the finger lifts. A drag that nobody claims scrolls whatever can scroll there. ADraggablewithoutClaimsDragtakes every drag that starts on it.ClaimsDragmust not change any state, because it is asked while the target is still being chosen. A drag that follows a long press is not offered: it goes to the innermostDraggable.event.MomentumDraggablelets a drag keep moving after a fast release, on Android, iOS and embedded devices. IfDragMomentum()returns true, the widget gets moreDraggedevents that slow down, thenDragEnd. Every otherDraggablegetsDragEndwhere the finger lifted. Use it for widgets that pan content, such as a map or a canvas. Do not use it for something the user moves directly, such as a slider thumb or a divider: what the user let go of has to stay there. Scroll containers already use it.
In the example, an upward swipe that starts on the strip scrolls the page, and a sideways one pans the strip:
// A strip that pans sideways inside a page that scrolls up and down. On a
// touch screen it takes only sideways drags, so an upward swipe that starts on
// it still scrolls the page, and it keeps moving after a fling.
package main
import (
"fmt"
"image/color"
"github.com/belluikit/bellui"
"github.com/belluikit/bellui/app"
"github.com/belluikit/bellui/canvas"
"github.com/belluikit/bellui/container"
"github.com/belluikit/bellui/core"
"github.com/belluikit/bellui/event"
"github.com/belluikit/bellui/geo"
"github.com/belluikit/bellui/widget"
)
// strip pans its content left and right when dragged.
type strip struct {
widget.BaseWidget
offset float32
text *canvas.Text
}
func newStrip() *strip {
s := &strip{text: canvas.NewText("", color.NRGBA{R: 0x3b, G: 0x6e, B: 0xc8, A: 0xff})}
s.ExtendBaseWidget(s)
return s
}
// event.Draggable: move the content with the pointer.
func (s *strip) Dragged(e *event.DragEvent) {
s.offset += e.Dragged.DX
s.Refresh()
}
func (s *strip) DragEnd() {}
// event.DragClaimer: on touch, take a drag only when it starts sideways.
// An upward or downward drag goes on to the scroll around the strip.
func (s *strip) ClaimsDrag(d geo.Delta) bool {
return abs(d.DX) > abs(d.DY)
}
// event.MomentumDraggable: on touch, keep moving after a fast release,
// because the strip pans content rather than being moved itself.
func (s *strip) DragMomentum() bool { return true }
func abs(v float32) float32 {
if v < 0 {
return -v
}
return v
}
func (s *strip) CreateRenderer() core.WidgetRenderer {
bg := canvas.NewRectangle(color.NRGBA{R: 0x80, G: 0x80, B: 0x80, A: 0x30})
bg.SetMinSize(geo.NewSize(200, 80))
r := &stripRenderer{s: s, bg: bg}
r.Refresh()
return r
}
type stripRenderer struct {
s *strip
bg *canvas.Rectangle
}
func (r *stripRenderer) Layout(size geo.Size) {
r.bg.Resize(size)
r.s.text.Move(geo.NewPos(r.s.offset, (size.Height-r.s.text.MinSize().Height)/2))
}
func (r *stripRenderer) MinSize() geo.Size { return r.bg.MinSize() }
func (r *stripRenderer) Refresh() {
r.s.text.Text = fmt.Sprintf("Offset %.0f", r.s.offset)
r.s.text.Refresh()
r.Layout(r.s.Size())
}
func (r *stripRenderer) Objects() []core.CanvasObject { return []core.CanvasObject{r.bg, r.s.text} }
func (r *stripRenderer) Destroy() {}
func main() {
a := app.NewWithID("com.example.drag")
w := a.NewWindow("Drag directions")
page := container.NewVBox()
for i := 1; i <= 20; i++ {
page.Add(widget.NewLabel(fmt.Sprintf("Row %d", i)))
if i == 3 {
page.Add(newStrip())
}
}
w.SetContent(container.NewVScroll(page))
w.Resize(geo.NewSize(320, 480))
bellui.ShowAndRun(w)
}Platform-specific interfaces
For desktop-only details there are extra interfaces in
driver/desktop:
Mouseable (MouseDown and MouseUp, with the button and modifier keys),
Keyable (KeyDown and KeyUp) and Cursorable (the mouse cursor to show
over the object). The driver/mobile
package has Touchable (TouchDown, TouchUp, TouchCancel) for raw touch
events.
Keyboard input
Key events go to the focused object. An object can take focus if it
implements Focusable:
| Method | Called when |
|---|---|
FocusGained(), FocusLost() | The object gains or loses focus |
TypedRune(rune) | A character is typed |
TypedKey(*KeyEvent) | A key without a character is pressed, such as an arrow key or Return |
KeyEvent.Name is a KeyName
such as event.KeyReturn or event.KeyEscape. KeyEvent.Modifier holds the
modifier keys that were down. On desktop, Tab moves focus to the next
focusable object. Your code can move focus with w.Canvas().Focus(obj).
Some widgets keep Tab for themselves: a multi-line Entry types a tab
character, and the DAG canvas moves between nodes. A custom widget does the
same by implementing
event.Tabbable
with AcceptsTab returning true. So that keyboard users are never stuck in
such a widget, two key sequences still move focus out of it:
- Escape, then Tab (or Shift+Tab to go back). This works everywhere, including the web. An Escape that closes a pop-up or dialog does not count; press Escape once more.
- Ctrl+Tab (or Ctrl+Shift+Tab), on desktop and mobile. Browsers keep Ctrl+Tab for switching their own tabs, so it does not work on the web.
On desktop, a key pressed with Control, Alt or Super (Command on macOS) goes
to the shortcut system, not to TypedKey. Only unmodified and
Shift-modified keys reach TypedKey.
When no object has focus, key events go to the window’s canvas instead.
Handle them there with SetOnTypedKey and SetOnTypedRune, as the example
below does.
Shortcuts
A shortcut is a key combination with a name. The
bellui package defines
the standard ones (ShortcutCopy, ShortcutPaste, ShortcutCut,
ShortcutSelectAll, ShortcutUndo, ShortcutRedo and more). For any other
combination, use
desktop.CustomShortcut.
Add a window-wide shortcut on the window’s canvas:
// A shortcut for the whole window: Ctrl+S, or Cmd+S on macOS.
save := &desktop.CustomShortcut{KeyName: event.KeyS, Modifier: event.KeyModifierShortcutDefault}
w.Canvas().AddShortcut(save, func(core.Shortcut) {
show("Save shortcut")
})
// Keys that no focused widget consumed.
w.Canvas().SetOnTypedKey(func(e *event.KeyEvent) {
show(fmt.Sprintf("Key %s", e.Name))
})event.KeyModifierShortcutDefault is Command in an app built for macOS or
iOS, and Control in every other build, so one shortcut follows each
platform’s convention. It is fixed when you compile: a web build uses
Control, even in a browser on a Mac.
When a shortcut is pressed, the toolkit tries, in order:
- a matching shortcut in the window’s main menu;
- the focused object, if it implements
bellui.Shortcutable(TypedShortcut); - the shortcuts added to the canvas with
AddShortcut.
So a focused text entry receives Ctrl+C before a canvas shortcut for the same
keys would. To give your own widget shortcuts, embed a
bellui.ShortcutHandler,
which provides TypedShortcut, AddShortcut and RemoveShortcut.
The complete example:
// A pad that reports every pointer event it receives, plus a window-wide
// keyboard shortcut and key handler.
package main
import (
"fmt"
"image/color"
"github.com/belluikit/bellui"
"github.com/belluikit/bellui/app"
"github.com/belluikit/bellui/canvas"
"github.com/belluikit/bellui/container"
"github.com/belluikit/bellui/core"
"github.com/belluikit/bellui/driver/desktop"
"github.com/belluikit/bellui/event"
"github.com/belluikit/bellui/widget"
)
// pad is a widget that implements several event interfaces. The toolkit
// checks which interfaces an object has and delivers matching events.
type pad struct {
widget.BaseWidget
bg *canvas.Rectangle
log func(string)
}
func newPad(log func(string)) *pad {
p := &pad{bg: canvas.NewRectangle(color.NRGBA{R: 0x3b, G: 0x6e, B: 0xc8, A: 0xff}), log: log}
p.ExtendBaseWidget(p)
return p
}
func (p *pad) CreateRenderer() core.WidgetRenderer {
return widget.NewSimpleRenderer(p.bg)
}
// event.Tappable: a click or a tap.
func (p *pad) Tapped(e *event.PointEvent) { p.log(fmt.Sprintf("Tapped at %v", e.Position)) }
// event.SecondaryTappable: a right-click on desktop.
func (p *pad) TappedSecondary(*event.PointEvent) { p.log("TappedSecondary") }
// event.LongPressable: press and hold.
func (p *pad) LongPressed(*event.PointEvent) { p.log("LongPressed") }
// event.Hoverable: the pointer enters, moves over and leaves (desktop and web).
func (p *pad) HoverIn(*event.HoverEvent) { p.log("HoverIn") }
func (p *pad) HoverMoved(*event.HoverEvent) {}
func (p *pad) HoverOut() { p.log("HoverOut") }
// event.Draggable: the pointer moves while pressed.
func (p *pad) Dragged(e *event.DragEvent) { p.log(fmt.Sprintf("Dragged by %v", e.Dragged)) }
func (p *pad) DragEnd() { p.log("DragEnd") }
// event.Scrollable: a mouse wheel or touchpad scroll.
func (p *pad) Scrolled(e *event.ScrollEvent) { p.log(fmt.Sprintf("Scrolled %v", e.Scrolled)) }
func main() {
a := app.NewWithID("com.example.events")
w := a.NewWindow("Input events")
last := widget.NewLabel("Interact with the blue pad")
show := func(s string) { last.SetText(s) }
// A shortcut for the whole window: Ctrl+S, or Cmd+S on macOS.
save := &desktop.CustomShortcut{KeyName: event.KeyS, Modifier: event.KeyModifierShortcutDefault}
w.Canvas().AddShortcut(save, func(core.Shortcut) {
show("Save shortcut")
})
// Keys that no focused widget consumed.
w.Canvas().SetOnTypedKey(func(e *event.KeyEvent) {
show(fmt.Sprintf("Key %s", e.Name))
})
w.SetContent(container.NewBorder(nil, last, nil, nil, newPad(show)))
bellui.ShowAndRun(w)
}Detecting an idle user
bellui.LastUserActivity()
returns when the user last gave the app input, in any of its windows. Use it
for an idle timer: go back to a home screen, dim, or lock after a while
without input. A timer reads it and compares it with time.Now:
const idleAfter = 10 * time.Second
started := time.Now()
go func() {
for range time.Tick(time.Second) {
bellui.Do(func() {
// LastUserActivity is the zero time until the first input,
// so count from the start of the app until then.
last := bellui.LastUserActivity()
if last.Before(started) {
last = started
}
away := time.Since(last) > idleAfter
if away && content.Visible() {
content.Hide()
idle.Show()
} else if !away && !content.Visible() {
idle.Hide()
content.Show()
}
})
}
}()It counts input as it arrives, before any widget sees it, so a scroll inside a list counts even though the list reports nothing. What counts:
- a mouse button pressed or released, and the mouse moved while a button is held;
- a touch going down, moving or lifting;
- a scroll from a wheel or a trackpad;
- a key pressed or released, typed text, and input from an on-screen keyboard;
- files dropped into a window.
Moving the mouse with no button held does not count. Neither does anything the app does itself: an animation, a timer, content that keeps scrolling after the finger lifts, or a value set from code. Actions a screen reader performs through the accessibility API, such as activating a button, are not counted yet. Before the first input it returns the zero time. You can call it from any goroutine.
The whole program:
// An idle timer: after ten seconds without input the window shows a notice,
// and the next input brings the content back.
package main
import (
"time"
"github.com/belluikit/bellui"
"github.com/belluikit/bellui/app"
"github.com/belluikit/bellui/container"
"github.com/belluikit/bellui/geo"
"github.com/belluikit/bellui/widget"
)
func main() {
a := app.NewWithID("com.example.idle")
w := a.NewWindow("Idle timer")
content := container.NewVBox(widget.NewLabel("Type, click or scroll."), widget.NewEntry())
idle := widget.NewLabel("Nobody here? Touch anything to come back.")
idle.Hide()
const idleAfter = 10 * time.Second
started := time.Now()
go func() {
for range time.Tick(time.Second) {
bellui.Do(func() {
// LastUserActivity is the zero time until the first input,
// so count from the start of the app until then.
last := bellui.LastUserActivity()
if last.Before(started) {
last = started
}
away := time.Since(last) > idleAfter
if away && content.Visible() {
content.Hide()
idle.Show()
} else if !away && !content.Visible() {
idle.Hide()
content.Show()
}
})
}
}()
w.SetContent(container.NewStack(content, container.NewCenter(idle)))
w.Resize(geo.NewSize(360, 200))
bellui.ShowAndRun(w)
}