widget

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2024 License: MIT, Unlicense Imports: 35 Imported by: 4

Documentation

Overview

Package widget implements state tracking and event handling of common user interface controls. To draw widgets, use a theme packages such as package github.com/utopiagio/gio/widget/material.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bool

type Bool struct {
	Value bool
	// contains filtered or unexported fields
}

func (*Bool) History

func (b *Bool) History() []Press

func (*Bool) Hovered

func (b *Bool) Hovered() bool

Hovered reports whether pointer is over the element.

func (*Bool) Layout

func (b *Bool) Layout(gtx layout.Context, w layout.Widget) layout.Dimensions

func (*Bool) Pressed

func (b *Bool) Pressed() bool

Pressed reports whether pointer is pressing the element.

func (*Bool) Update

func (b *Bool) Update(gtx layout.Context) bool

Update the widget state and report whether Value was changed.

type Border

type Border struct {
	Color        color.NRGBA
	CornerRadius unit.Dp
	Width        unit.Dp
}

Border lays out a widget and draws a border inside it.

func (Border) Layout

func (b Border) Layout(gtx layout.Context, w layout.Widget) layout.Dimensions

type ChangeEvent

type ChangeEvent struct{}

A ChangeEvent is generated for every user change to the text.

type Click

type Click struct {
	Modifiers key.Modifiers
	NumClicks int
}

Click represents a click.

type Clickable

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

Clickable represents a clickable area.

Example (Passthrough)
package main

import (
	"fmt"
	"image"

	"github.com/utopiagio/gio/f32"
	"github.com/utopiagio/gio/io/input"
	"github.com/utopiagio/gio/io/pointer"
	"github.com/utopiagio/gio/layout"
	"github.com/utopiagio/gio/op"
	"github.com/utopiagio/gio/widget"
)

func main() {
	// When laying out clickable widgets on top of each other,
	// pointer events can be passed down for the underlying
	// widgets to pick them up.
	var button1, button2 widget.Clickable
	var r input.Router
	gtx := layout.Context{
		Ops:         new(op.Ops),
		Constraints: layout.Exact(image.Pt(100, 100)),
		Source:      r.Source(),
	}

	// widget lays out two buttons on top of each other.
	widget := func() {
		content := func(gtx layout.Context) layout.Dimensions { return layout.Dimensions{Size: gtx.Constraints.Min} }
		button1.Layout(gtx, content)
		// button2 completely covers button1, but pass-through allows pointer
		// events to pass through to button1.
		defer pointer.PassOp{}.Push(gtx.Ops).Pop()
		button2.Layout(gtx, content)
	}

	// The first layout and call to Frame declare the Clickable handlers
	// to the input router, so the following pointer events are propagated.
	widget()
	r.Frame(gtx.Ops)
	// Simulate one click on the buttons by sending a Press and Release event.
	r.Queue(
		pointer.Event{
			Source:   pointer.Mouse,
			Buttons:  pointer.ButtonPrimary,
			Kind:     pointer.Press,
			Position: f32.Pt(50, 50),
		},
		pointer.Event{
			Source:   pointer.Mouse,
			Buttons:  pointer.ButtonPrimary,
			Kind:     pointer.Release,
			Position: f32.Pt(50, 50),
		},
	)

	if button1.Clicked(gtx) {
		fmt.Println("button1 clicked!")
	}
	if button2.Clicked(gtx) {
		fmt.Println("button2 clicked!")
	}

}
Output:

button1 clicked!
button2 clicked!

func (*Clickable) Click

func (b *Clickable) Click()

Click executes a simple programmatic click.

func (*Clickable) Clicked

func (b *Clickable) Clicked(gtx layout.Context) bool

Clicked calls Update and reports whether a click was registered.

func (*Clickable) History

func (b *Clickable) History() []Press

History is the past pointer presses useful for drawing markers. History is retained for a short duration (about a second).

func (*Clickable) Hovered

func (b *Clickable) Hovered() bool

Hovered reports whether a pointer is over the element.

func (*Clickable) Layout

Layout and update the button state.

func (*Clickable) Pressed

func (b *Clickable) Pressed() bool

Pressed reports whether a pointer is pressing the element.

func (*Clickable) Update

func (b *Clickable) Update(gtx layout.Context) (Click, bool)

Update the button state by processing events, and return the next click, if any.

type Decorations

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

Decorations handles the states of window decorations.

func (*Decorations) Clickable

func (d *Decorations) Clickable(action system.Action) *Clickable

Clickable returns the clickable for the given single action.

func (*Decorations) LayoutMove

func (d *Decorations) LayoutMove(gtx layout.Context, w layout.Widget) layout.Dimensions

LayoutMove lays out the widget that makes a window movable.

func (*Decorations) Maximized

func (d *Decorations) Maximized() bool

Maximized returns whether the window is maximized.

func (*Decorations) Perform

func (d *Decorations) Perform(actions system.Action)

Perform updates the decorations as if the specified actions were performed by the user.

func (*Decorations) Update

func (d *Decorations) Update(gtx layout.Context) system.Action

Update the state and return the set of actions activated by the user.

type Draggable

type Draggable struct {
	// Type contains the MIME type and matches transfer.SourceOp.
	Type string
	// contains filtered or unexported fields
}

Draggable makes a widget draggable.

func (*Draggable) Dragging

func (d *Draggable) Dragging() bool

Dragging returns whether d is being dragged.

func (*Draggable) Layout

func (d *Draggable) Layout(gtx layout.Context, w, drag layout.Widget) layout.Dimensions
Example
package main

import (
	"fmt"
	"image"
	"io"
	"strings"

	"github.com/utopiagio/gio/f32"
	"github.com/utopiagio/gio/io/event"
	"github.com/utopiagio/gio/io/input"
	"github.com/utopiagio/gio/io/pointer"
	"github.com/utopiagio/gio/io/transfer"
	"github.com/utopiagio/gio/layout"
	"github.com/utopiagio/gio/op"
	"github.com/utopiagio/gio/op/clip"
	"github.com/utopiagio/gio/widget"
)

func main() {
	var r input.Router
	gtx := layout.Context{
		Ops:         new(op.Ops),
		Constraints: layout.Exact(image.Pt(100, 100)),
		Source:      r.Source(),
	}
	// mime is the type used to match drag and drop operations.
	// It could be left empty in this example.
	const mime = "MyMime"
	drag := &widget.Draggable{Type: mime}
	var drop int
	// widget lays out the drag and drop handlers and processes
	// the transfer events.
	widget := func() {
		// Setup the draggable widget.
		w := func(gtx layout.Context) layout.Dimensions {
			sz := image.Pt(10, 10) // drag area
			return layout.Dimensions{Size: sz}
		}
		drag.Layout(gtx, w, w)
		// drag must respond with an Offer event when requested.
		// Use the drag method for this.
		if m, ok := drag.Update(gtx); ok {
			drag.Offer(gtx, m, io.NopCloser(strings.NewReader("hello world")))
		}

		// Setup the area for drops.
		ds := clip.Rect{
			Min: image.Pt(20, 20),
			Max: image.Pt(40, 40),
		}.Push(gtx.Ops)
		event.Op(gtx.Ops, &drop)
		ds.Pop()

		// Check for the received data.
		for {
			ev, ok := gtx.Event(transfer.TargetFilter{Target: &drop, Type: mime})
			if !ok {
				break
			}
			switch e := ev.(type) {
			case transfer.DataEvent:
				data := e.Open()
				defer data.Close()
				content, _ := io.ReadAll(data)
				fmt.Println(string(content))
			}
		}
	}
	// Register and lay out the widget.
	widget()
	r.Frame(gtx.Ops)

	// Send drag and drop gesture events.
	r.Queue(
		pointer.Event{
			Kind:     pointer.Press,
			Position: f32.Pt(5, 5), // in the drag area
		},
		pointer.Event{
			Kind:     pointer.Move,
			Position: f32.Pt(5, 5), // in the drop area
		},
		pointer.Event{
			Kind:     pointer.Release,
			Position: f32.Pt(30, 30), // in the drop area
		},
	)
	// Let the widget process the events.
	widget()
	r.Frame(gtx.Ops)

	// Process the transfer.DataEvent.
	widget()

}
Output:

hello world

func (*Draggable) Offer

func (d *Draggable) Offer(gtx layout.Context, mime string, data io.ReadCloser)

Offer the data ready for a drop. Must be called after being Requested. The mime must be one in the requested list.

func (*Draggable) Pos

func (d *Draggable) Pos() f32.Point

Pos returns the drag position relative to its initial click position.

func (*Draggable) Update

func (d *Draggable) Update(gtx layout.Context) (mime string, requested bool)

Update the draggable and returns the MIME type for which the Draggable was requested to offer data, if any

type Editor

type Editor struct {

	// Alignment controls the alignment of text within the editor.
	Alignment text.Alignment
	// LineHeight determines the gap between baselines of text. If zero, a sensible
	// default will be used.
	LineHeight unit.Sp
	// LineHeightScale is multiplied by LineHeight to determine the final gap
	// between baselines. If zero, a sensible default will be used.
	LineHeightScale float32
	// SingleLine force the text to stay on a single line.
	// SingleLine also sets the scrolling direction to
	// horizontal.
	SingleLine bool
	// ReadOnly controls whether the contents of the editor can be altered by
	// user interaction. If set to true, the editor will allow selecting text
	// and copying it interactively, but not modifying it.
	ReadOnly bool
	// Submit enabled translation of carriage return keys to SubmitEvents.
	// If not enabled, carriage returns are inserted as newlines in the text.
	Submit bool
	// Mask replaces the visual display of each rune in the contents with the given rune.
	// Newline characters are not masked. When non-zero, the unmasked contents
	// are accessed by Len, Text, and SetText.
	Mask rune
	// InputHint specifies the type of on-screen keyboard to be displayed.
	InputHint key.InputHint
	// MaxLen limits the editor content to a maximum length. Zero means no limit.
	MaxLen int
	// Filter is the list of characters allowed in the Editor. If Filter is empty,
	// all characters are allowed.
	Filter string
	// WrapPolicy configures how displayed text will be broken into lines.
	WrapPolicy text.WrapPolicy
	// contains filtered or unexported fields
}

Editor implements an editable and scrollable text area.

func (*Editor) CaretCoords

func (e *Editor) CaretCoords() f32.Point

CaretCoords returns the coordinates of the caret, relative to the editor itself.

func (*Editor) CaretPos

func (e *Editor) CaretPos() (line, col int)

CaretPos returns the line & column numbers of the caret.

func (*Editor) ClearSelection

func (e *Editor) ClearSelection()

ClearSelection clears the selection, by setting the selection end equal to the selection start.

func (*Editor) Delete

func (e *Editor) Delete(graphemeClusters int) (deletedRunes int)

Delete runes from the caret position. The sign of the argument specifies the direction to delete: positive is forward, negative is backward.

If there is a selection, it is deleted and counts as a single grapheme cluster.

func (*Editor) Insert

func (e *Editor) Insert(s string) (insertedRunes int)

func (*Editor) Layout

func (e *Editor) Layout(gtx layout.Context, lt *text.Shaper, font font.Font, size unit.Sp, textMaterial, selectMaterial op.CallOp) layout.Dimensions

Layout lays out the editor using the provided textMaterial as the paint material for the text glyphs+caret and the selectMaterial as the paint material for the selection rectangle.

func (*Editor) Len

func (e *Editor) Len() int

Len is the length of the editor contents, in runes.

func (*Editor) MoveCaret

func (e *Editor) MoveCaret(startDelta, endDelta int)

MoveCaret moves the caret (aka selection start) and the selection end relative to their current positions. Positive distances moves forward, negative distances moves backward. Distances are in grapheme clusters, which closely match what users perceive as "characters" even when the characters are multiple code points long.

func (*Editor) Read

func (e *Editor) Read(p []byte) (int, error)

Read implements io.Reader.

func (*Editor) Regions

func (e *Editor) Regions(start, end int, regions []Region) []Region

Regions returns visible regions covering the rune range [start,end).

func (*Editor) Seek

func (e *Editor) Seek(offset int64, whence int) (int64, error)

Seek implements io.Seeker.

func (*Editor) SelectedText

func (e *Editor) SelectedText() string

SelectedText returns the currently selected text (if any) from the editor.

func (*Editor) Selection

func (e *Editor) Selection() (start, end int)

Selection returns the start and end of the selection, as rune offsets. start can be > end.

func (*Editor) SelectionLen

func (e *Editor) SelectionLen() int

SelectionLen returns the length of the selection, in runes; it is equivalent to utf8.RuneCountInString(e.SelectedText()).

func (*Editor) SetCaret

func (e *Editor) SetCaret(start, end int)

SetCaret moves the caret to start, and sets the selection end to end. start and end are in runes, and represent offsets into the editor text.

func (*Editor) SetText

func (e *Editor) SetText(s string)

func (*Editor) Text

func (e *Editor) Text() string

Text returns the contents of the editor.

func (*Editor) Update

func (e *Editor) Update(gtx layout.Context) (EditorEvent, bool)

Update the state of the editor in response to input events. Update consumes editor input events until there are no remaining events or an editor event is generated. To fully update the state of the editor, callers should call Update until it returns false.

func (*Editor) WriteTo

func (e *Editor) WriteTo(w io.Writer) (int64, error)

WriteTo implements io.WriterTo.

type EditorEvent

type EditorEvent interface {
	// contains filtered or unexported methods
}

type Enum

type Enum struct {
	Value string
	// contains filtered or unexported fields
}

func (*Enum) Focused

func (e *Enum) Focused() (string, bool)

Focused reports the focused key, or false if no key is focused.

func (*Enum) Hovered

func (e *Enum) Hovered() (string, bool)

Hovered returns the key that is highlighted, or false if none are.

func (*Enum) Layout

func (e *Enum) Layout(gtx layout.Context, k string, content layout.Widget) layout.Dimensions

Layout adds the event handler for the key k.

func (*Enum) Update

func (e *Enum) Update(gtx layout.Context) bool

Update the state and report whether Value has changed by user interaction.

type Fit

type Fit uint8

Fit scales a widget to fit and clip to the constraints.

const (
	// Unscaled does not alter the scale of a widget.
	Unscaled Fit = iota
	// Contain scales widget as large as possible without cropping
	// and it preserves aspect-ratio.
	Contain
	// Cover scales the widget to cover the constraint area and
	// preserves aspect-ratio.
	Cover
	// ScaleDown scales the widget smaller without cropping,
	// when it exceeds the constraint area.
	// It preserves aspect-ratio.
	ScaleDown
	// Fill stretches the widget to the constraints and does not
	// preserve aspect-ratio.
	Fill
)

type Float

type Float struct {
	// Value is the value of the Float, in the [0; 1] range.
	Value float32
	// contains filtered or unexported fields
}

Float is for selecting a value in a range.

func (*Float) Dragging

func (f *Float) Dragging() bool

Dragging returns whether the value is being interacted with.

func (*Float) Layout

func (f *Float) Layout(gtx layout.Context, axis layout.Axis, pointerMargin unit.Dp) layout.Dimensions

func (*Float) Update

func (f *Float) Update(gtx layout.Context) bool

Update the Value according to drag events along the f's main axis. The return value reports whether the value was changed.

The range of f is set by the minimum constraints main axis value.

type Icon

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

func NewIcon

func NewIcon(data []byte) (*Icon, error)

NewIcon returns a new Icon from IconVG data.

func (*Icon) Layout

func (ic *Icon) Layout(gtx layout.Context, color color.NRGBA) layout.Dimensions

Layout displays the icon with its size set to the X minimum constraint.

type Image

type Image struct {
	// Src is the image to display.
	Src paint.ImageOp
	// Fit specifies how to scale the image to the constraints.
	// By default it does not do any scaling.
	Fit Fit
	// Position specifies where to position the image within
	// the constraints.
	Position layout.Direction
	// Scale is the factor used for converting image pixels to dp.
	// If Scale is zero it defaults to 1.
	//
	// To map one image pixel to one output pixel, set Scale to 1.0 / gtx.Metric.PxPerDp.
	Scale float32
}

Image is a widget that displays an image.

func (Image) Layout

func (im Image) Layout(gtx layout.Context) layout.Dimensions

type Label

type Label struct {
	// Alignment specifies the text alignment.
	Alignment text.Alignment
	// MaxLines limits the number of lines. Zero means no limit.
	MaxLines int
	// Truncator is the text that will be shown at the end of the final
	// line if MaxLines is exceeded. Defaults to "…" if empty.
	Truncator string
	// WrapPolicy configures how displayed text will be broken into lines.
	WrapPolicy text.WrapPolicy
	// LineHeight controls the distance between the baselines of lines of text.
	// If zero, a sensible default will be used.
	LineHeight unit.Sp
	// LineHeightScale applies a scaling factor to the LineHeight. If zero, a
	// sensible default will be used.
	LineHeightScale float32
}

Label is a widget for laying out and drawing text. Labels are always non-interactive text. They cannot be selected or copied.

func (Label) Layout

func (l Label) Layout(gtx layout.Context, lt *text.Shaper, font font.Font, size unit.Sp, txt string, textMaterial op.CallOp) layout.Dimensions

Layout the label with the given shaper, font, size, text, and material.

func (Label) LayoutDetailed

func (l Label) LayoutDetailed(gtx layout.Context, lt *text.Shaper, font font.Font, size unit.Sp, txt string, textMaterial op.CallOp) (layout.Dimensions, TextInfo)

Layout the label with the given shaper, font, size, text, and material, returning metadata about the shaped text.

type List

type List struct {
	Scrollbar
	layout.List
}

List holds the persistent state for a layout.List that has a scrollbar attached.

type Press

type Press struct {
	// Position of the press.
	Position image.Point
	// Start is when the press began.
	Start time.Time
	// End is when the press was ended by a release or cancel.
	// A zero End means it hasn't ended yet.
	End time.Time
	// Cancelled is true for cancelled presses.
	Cancelled bool
}

Press represents a past pointer press.

type Region

type Region struct {
	// Bounds is the coordinates of the bounding box relative to the containing
	// widget.
	Bounds image.Rectangle
	// Baseline is the quantity of vertical pixels between the baseline and
	// the bottom of bounds.
	Baseline int
}

Region describes the position and baseline of an area of interest within shaped text.

type Scrollbar

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

Scrollbar holds the persistent state for an area that can display a scrollbar. In particular, it tracks the position of a viewport along a one-dimensional region of content. The viewport's position can be adjusted by drag operations along the display area, or by clicks within the display area.

Scrollbar additionally detects when a scroll indicator region is hovered.

func (*Scrollbar) AddDrag

func (s *Scrollbar) AddDrag(ops *op.Ops)

AddDrag configures the drag listener for the scrollbar to use the current clip area.

func (*Scrollbar) AddIndicator

func (s *Scrollbar) AddIndicator(ops *op.Ops)

AddIndicator configures the indicator click listener for the scrollbar to use the current clip area.

func (*Scrollbar) AddTrack

func (s *Scrollbar) AddTrack(ops *op.Ops)

AddTrack configures the track click listener for the scrollbar to use the current clip area.

func (*Scrollbar) Dragging

func (s *Scrollbar) Dragging() bool

Dragging reports whether the user is currently performing a drag gesture on the indicator. Note that this can return false while ScrollDistance is nonzero if the user scrolls using a different control than the scrollbar (like a mouse wheel).

func (*Scrollbar) IndicatorHovered

func (s *Scrollbar) IndicatorHovered() bool

IndicatorHovered reports whether the scroll indicator is currently being hovered by the pointer.

func (*Scrollbar) ScrollDistance

func (s *Scrollbar) ScrollDistance() float32

ScrollDistance returns the normalized distance that the scrollbar moved during the last call to Layout as a value in the range [-1,1].

func (*Scrollbar) TrackHovered

func (s *Scrollbar) TrackHovered() bool

TrackHovered reports whether the scroll track is being hovered by the pointer.

func (*Scrollbar) Update

func (s *Scrollbar) Update(gtx layout.Context, axis layout.Axis, viewportStart, viewportEnd float32)

Update updates the internal state of the scrollbar based on events since the previous call to Update. The provided axis will be used to normalize input event coordinates and constraints into an axis- independent format. viewportStart is the position of the beginning of the scrollable viewport relative to the underlying content expressed as a value in the range [0,1]. viewportEnd is the position of the end of the viewport relative to the underlying content, also expressed as a value in the range [0,1]. For example, if viewportStart is 0.25 and viewportEnd is .5, the viewport described by the scrollbar is currently showing the second quarter of the underlying content.

type SelectEvent

type SelectEvent struct{}

A SelectEvent is generated when the user selects some text, or changes the selection (e.g. with a shift-click), including if they remove the selection. The selected text is not part of the event, on the theory that it could be a relatively expensive operation (for a large editor), most applications won't actually care about it, and those that do can call Editor.SelectedText() (which can be empty).

type Selectable

type Selectable struct {
	// Alignment controls the alignment of the text.
	Alignment text.Alignment
	// MaxLines is the maximum number of lines of text to be displayed.
	MaxLines int
	// Truncator is the symbol to use at the end of the final line of text
	// if text was cut off. Defaults to "…" if left empty.
	Truncator string
	// WrapPolicy configures how displayed text will be broken into lines.
	WrapPolicy text.WrapPolicy
	// LineHeight controls the distance between the baselines of lines of text.
	// If zero, a sensible default will be used.
	LineHeight unit.Sp
	// LineHeightScale applies a scaling factor to the LineHeight. If zero, a
	// sensible default will be used.
	LineHeightScale float32
	// contains filtered or unexported fields
}

Selectable displays selectable text.

func (*Selectable) ClearSelection

func (l *Selectable) ClearSelection()

ClearSelection clears the selection, by setting the selection end equal to the selection start.

func (*Selectable) Focused

func (l *Selectable) Focused() bool

Focused returns whether the label is focused or not.

func (*Selectable) Layout

func (l *Selectable) Layout(gtx layout.Context, lt *text.Shaper, font font.Font, size unit.Sp, textMaterial, selectionMaterial op.CallOp) layout.Dimensions

Layout clips to the dimensions of the selectable, updates the shaped text, configures input handling, and paints the text and selection rectangles. The provided textMaterial and selectionMaterial ops are used to set the paint material for the text and selection rectangles, respectively.

func (*Selectable) Regions

func (l *Selectable) Regions(start, end int, regions []Region) []Region

Regions returns visible regions covering the rune range [start,end).

func (*Selectable) SelectedText

func (l *Selectable) SelectedText() string

SelectedText returns the currently selected text (if any) from the editor.

func (*Selectable) Selection

func (l *Selectable) Selection() (start, end int)

Selection returns the start and end of the selection, as rune offsets. start can be > end.

func (*Selectable) SelectionLen

func (l *Selectable) SelectionLen() int

SelectionLen returns the length of the selection, in runes; it is equivalent to utf8.RuneCountInString(e.SelectedText()).

func (*Selectable) SetCaret

func (l *Selectable) SetCaret(start, end int)

SetCaret moves the caret to start, and sets the selection end to end. start and end are in runes, and represent offsets into the editor text.

func (*Selectable) SetText

func (l *Selectable) SetText(s string)

SetText updates the text to s if it does not already contain s. Updating the text will clear the selection unless the selectable already contains s.

func (*Selectable) Text

func (l *Selectable) Text() string

Text returns the contents of the label.

func (*Selectable) Truncated

func (l *Selectable) Truncated() bool

Truncated returns whether the text has been truncated by the text shaper to fit within available constraints.

func (*Selectable) Update

func (l *Selectable) Update(gtx layout.Context) bool

Update the state of the selectable in response to input events. It returns whether the text selection changed during event processing.

type SubmitEvent

type SubmitEvent struct {
	Text string
}

A SubmitEvent is generated when Submit is set and a carriage return key is pressed.

type TextInfo

type TextInfo struct {
	// Truncated contains the number of runes of text that are represented by a truncator
	// symbol in the text. If zero, there is no truncator symbol.
	Truncated int
}

TextInfo provides metadata about shaped text.

Notes

Bugs

  • this method's definition of a "word" is currently whitespace-delimited. Languages that do not use whitespace to delimit words will experience counter-intuitive behavior when navigating by word.

Directories

Path Synopsis
Package material implements the Material design.
Package material implements the Material design.

Jump to

Keyboard shortcuts

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