ui: git.kirsle.net/go/ui Index | Examples | Files | Directories

package ui

import "git.kirsle.net/go/ui"

Package ui provides a user interface toolkit for Go.

The UI toolkit targets SDL2 applications on desktop (Linux, Mac and Windows) or an HTML Canvas render engine for web browsers.

It provides various widgets such as Frame, Label, Button, Checkbox, Radiobox and Tooltip and an event supervisor to monitor the state of the widgets.

Index

Examples

Package Files

button.go check_button.go checkbox.go debug.go docs.go dragdrop.go enums.go frame.go frame_pack.go frame_place.go functions.go image.go label.go main_window.go menu.go menu_bar.go menu_button.go supervisor.go tooltip.go version.go widget.go window.go window_manager.go

Constants

const (
    SideMin = Center
    SideMax = NW
)

Range of Side values.

const (
    BMP  ImageType = "bmp"
    PNG            = "png"
    JPEG           = "jpg"
)

Supported image formats.

const (
    BorderNone   BorderStyle = ""
    BorderSolid  BorderStyle = "solid"
    BorderRaised             = "raised"
    BorderSunken             = "sunken"
)

Styles for a widget border.

const (
    CloseButton = 0x01

    // NOTICE: MaximizeButton behavior is currently buggy, window doesn't
    // redraw itself at the new size properly.
    MaximizeButton = 0x02

    // Minimize button has no default behavior attached; you can bind it with
    // window.Handle(MinimizeWindow) to set your own event handler.
    MinimizeButton = 0x04
)

Window button options. OR these together in a call to Window.SetButtons().

const Version = "0.1.0"

Version of the UI toolkit.

Variables

var (
    DefaultWidth  = 640
    DefaultHeight = 480
)

Default width and height for MainWindow.

var (
    // The caller should STOP forwarding any mouse or keyboard events to any
    // other handles for the remainder of this tick.
    ErrStopPropagation = errors.New("stop all event propagation")
    ErrNoEventHandler  = errors.New("no event handler")
)

Error messages that may be returned by Supervisor.Loop()

var DefaultFont = render.Text{
    Size:  12,
    Color: render.Black,
}

DefaultFont is the default font settings used for a Label.

var (
    FPS = 60
)

Target frames per second for the MainWindow to render at.

var MenuFont = render.Text{
    Size:  12,
    Color: render.Black,
    PadX:  4,
    PadY:  2,
}

MenuFont is the default font settings for MenuBar buttons.

var MenuWidth = 180

MenuWidth sets the width of all popup menus. TODO, widths should be automatic.

func AbsolutePosition Uses

func AbsolutePosition(w Widget) render.Point

AbsolutePosition computes a widget's absolute X,Y position on the window on screen by crawling its parent widget tree.

func AbsoluteRect Uses

func AbsoluteRect(w Widget) render.Rect

AbsoluteRect returns a Rect() offset with the absolute position. X and Y are the AbsolutePosition of the widget. W and H are the widget's width and height. (X,Y not added to them)

func HasParent Uses

func HasParent(w Widget, parent Widget) bool

HasParent returns whether the target widget is a descendant of the parent. This scans the parents of the widget recursively until it finds a match.

func PrintWidgetTree Uses

func PrintWidgetTree(root Widget)

PrintWidgetTree prints a widget tree to console.

func WidgetTree Uses

func WidgetTree(root Widget) []string

WidgetTree returns a string representing the tree of widgets starting at a given widget.

type BaseWidget Uses

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

BaseWidget holds common functionality for all widgets, such as managing their widths and heights.

func (*BaseWidget) Background Uses

func (w *BaseWidget) Background() render.Color

Background returns the background color.

func (*BaseWidget) BorderColor Uses

func (w *BaseWidget) BorderColor() render.Color

BorderColor returns the border color, or defaults to the background color.

func (*BaseWidget) BorderSize Uses

func (w *BaseWidget) BorderSize() int

BorderSize returns the border thickness.

func (*BaseWidget) BorderStyle Uses

func (w *BaseWidget) BorderStyle() BorderStyle

BorderStyle returns the border style.

func (*BaseWidget) BoxSize Uses

func (w *BaseWidget) BoxSize() render.Rect

BoxSize returns the full rendered size of the widget including its box thickness (border, padding and outline).

func (*BaseWidget) BoxThickness Uses

func (w *BaseWidget) BoxThickness(m int) int

BoxThickness returns the full sum of the padding, border and outline. m = multiplier, i.e., 1 or 2. If m=1 this returns the box thickness of one edge of the widget, if m=2 it would account for both edges of the widget.

func (*BaseWidget) Children Uses

func (w *BaseWidget) Children() []Widget

Children returns the widget's children, to be implemented by containers. The default implementation returns an empty slice.

func (*BaseWidget) Compute Uses

func (w *BaseWidget) Compute(e render.Engine)

Compute calls the base widget's Compute function, which just triggers events on widgets that want to be notified when the widget computes.

func (*BaseWidget) Configure Uses

func (w *BaseWidget) Configure(c Config)

Configure the base widget with all the common properties at once. Any property left as the zero value will not update the widget.

func (*BaseWidget) DrawBox Uses

func (w *BaseWidget) DrawBox(e render.Engine, P render.Point)

DrawBox draws the border and outline.

func (*BaseWidget) Event Uses

func (w *BaseWidget) Event(event Event, e EventData) error

Event is called internally by Doodle to trigger an event. Handlers can return ErrStopPropagation to prevent further widgets being notified of events.

func (*BaseWidget) FixedSize Uses

func (w *BaseWidget) FixedSize() bool

FixedSize returns whether the widget's size has been hard-coded by the user (true) or if it automatically resizes based on its contents (false).

func (*BaseWidget) Foreground Uses

func (w *BaseWidget) Foreground() render.Color

Foreground returns the foreground color.

func (*BaseWidget) Handle Uses

func (w *BaseWidget) Handle(event Event, fn func(EventData) error)

Handle an event in the widget.

func (*BaseWidget) Hidden Uses

func (w *BaseWidget) Hidden() bool

Hidden returns whether the widget is hidden. If this widget is not hidden, but it has a parent, this will recursively crawl the parents to see if any of them are hidden.

func (*BaseWidget) Hide Uses

func (w *BaseWidget) Hide()

Hide the widget from being rendered.

func (*BaseWidget) ID Uses

func (w *BaseWidget) ID() string

ID returns the ID that the widget calls itself by.

func (*BaseWidget) IDFunc Uses

func (w *BaseWidget) IDFunc(fn func() string)

IDFunc sets an ID function.

func (*BaseWidget) Margin Uses

func (w *BaseWidget) Margin() int

Margin returns the margin width.

func (*BaseWidget) MoveBy Uses

func (w *BaseWidget) MoveBy(v render.Point)

MoveBy adds the X,Y values to the widget's current position.

func (*BaseWidget) MoveTo Uses

func (w *BaseWidget) MoveTo(v render.Point)

MoveTo updates the X,Y position to the new point.

func (*BaseWidget) OnMouseOut Uses

func (w *BaseWidget) OnMouseOut(render.Point)

OnMouseOut should be overridden on widgets who want this event.

func (*BaseWidget) OutlineColor Uses

func (w *BaseWidget) OutlineColor() render.Color

OutlineColor returns the background color.

func (*BaseWidget) OutlineSize Uses

func (w *BaseWidget) OutlineSize() int

OutlineSize returns the outline thickness.

func (*BaseWidget) Parent Uses

func (w *BaseWidget) Parent() (Widget, bool)

Parent returns the parent widget, like a Frame, and a boolean indicating whether the widget had a parent.

func (*BaseWidget) Point Uses

func (w *BaseWidget) Point() render.Point

Point returns the X,Y position of the widget on the window.

func (*BaseWidget) Present Uses

func (w *BaseWidget) Present(e render.Engine, p render.Point)

Present calls the base widget's Present function, which just triggers events on widgets that want to be notified when the widget presents.

func (*BaseWidget) Rect Uses

func (w *BaseWidget) Rect() render.Rect

Rect returns the widget's absolute rectangle, the combined Size and Point.

func (*BaseWidget) Resize Uses

func (w *BaseWidget) Resize(v render.Rect)

Resize sets the size of the widget to the .W and .H attributes of a rect.

func (*BaseWidget) ResizeAuto Uses

func (w *BaseWidget) ResizeAuto(v render.Rect)

ResizeAuto sets the size of the widget but doesn't set the fixedSize flag.

func (*BaseWidget) ResizeBy Uses

func (w *BaseWidget) ResizeBy(v render.Rect)

ResizeBy resizes by a relative amount.

func (*BaseWidget) SetBackground Uses

func (w *BaseWidget) SetBackground(c render.Color)

SetBackground sets the color.

func (*BaseWidget) SetBorderColor Uses

func (w *BaseWidget) SetBorderColor(c render.Color)

SetBorderColor sets the border color.

func (*BaseWidget) SetBorderSize Uses

func (w *BaseWidget) SetBorderSize(v int)

SetBorderSize sets the border thickness.

func (*BaseWidget) SetBorderStyle Uses

func (w *BaseWidget) SetBorderStyle(v BorderStyle)

SetBorderStyle sets the border style.

func (*BaseWidget) SetForeground Uses

func (w *BaseWidget) SetForeground(c render.Color)

SetForeground sets the color.

func (*BaseWidget) SetID Uses

func (w *BaseWidget) SetID(id string)

SetID sets a string name for your widget, helpful for debugging purposes.

func (*BaseWidget) SetMargin Uses

func (w *BaseWidget) SetMargin(v int)

SetMargin sets the margin width.

func (*BaseWidget) SetOutlineColor Uses

func (w *BaseWidget) SetOutlineColor(c render.Color)

SetOutlineColor sets the color.

func (*BaseWidget) SetOutlineSize Uses

func (w *BaseWidget) SetOutlineSize(v int)

SetOutlineSize sets the outline thickness.

func (*BaseWidget) SetParent Uses

func (w *BaseWidget) SetParent(parent Widget)

SetParent sets the widget's parent. This function is called by container widgets like Frame when they add a child widget to their care. Pass a nil parent to unset the parent.

func (*BaseWidget) Show Uses

func (w *BaseWidget) Show()

Show the widget.

func (*BaseWidget) Size Uses

func (w *BaseWidget) Size() render.Rect

Size returns the box with W and H attributes containing the size of the widget. The X,Y attributes of the box are ignored and zero.

func (*BaseWidget) String Uses

func (w *BaseWidget) String() string

type BorderStyle Uses

type BorderStyle string

BorderStyle options for widget.SetBorderStyle()

type Button Uses

type Button struct {
    BaseWidget
    // contains filtered or unexported fields
}

Button is a clickable button.

func NewButton Uses

func NewButton(name string, child Widget) *Button

NewButton creates a new Button.

func (*Button) Children Uses

func (w *Button) Children() []Widget

Children returns the button's child widget.

func (*Button) Compute Uses

func (w *Button) Compute(e render.Engine)

Compute the size of the button.

func (*Button) Present Uses

func (w *Button) Present(e render.Engine, P render.Point)

Present the button.

func (*Button) SetText Uses

func (w *Button) SetText(text string) error

SetText conveniently sets the button text, for Label children only.

type CheckButton Uses

type CheckButton struct {
    Button
    BoolVar   *bool
    StringVar *string
    Value     string
}

CheckButton implements a checkbox and radiobox widget. It's based on a Button and holds a boolean or string pointer (boolean for checkbox, string for radio).

func NewCheckButton Uses

func NewCheckButton(name string, boolVar *bool, child Widget) *CheckButton

NewCheckButton creates a new CheckButton.

func NewRadioButton Uses

func NewRadioButton(name string, stringVar *string, value string, child Widget) *CheckButton

NewRadioButton creates a CheckButton bound to a string variable.

func (*CheckButton) Compute Uses

func (w *CheckButton) Compute(e render.Engine)

Compute to re-evaluate the button state (in the case of radio buttons where a different button will affect the state of this one when clicked).

type Checkbox Uses

type Checkbox struct {
    Frame
    // contains filtered or unexported fields
}

Checkbox combines a CheckButton with a widget like a Label.

func NewCheckbox Uses

func NewCheckbox(name string, boolVar *bool, child Widget) *Checkbox

NewCheckbox creates a new Checkbox.

func NewRadiobox Uses

func NewRadiobox(name string, stringVar *string, value string, child Widget) *Checkbox

NewRadiobox creates a new Checkbox in radio mode.

func (*Checkbox) Child Uses

func (w *Checkbox) Child() Widget

Child returns the child widget.

func (*Checkbox) Supervise Uses

func (w *Checkbox) Supervise(s *Supervisor)

Supervise the checkbutton inside the widget.

type Config Uses

type Config struct {
    // Size management. If you provide a non-zero value for Width and Height,
    // the widget will be resized and the "fixedSize" flag is set, meaning it
    // will not re-compute its size dynamically. To set the size while also
    // keeping the auto-resize property, pass AutoResize=true too. This is
    // mainly used internally when widgets are calculating their automatic sizes.
    AutoResize   bool
    Width        int
    Height       int
    Margin       int
    MarginX      int
    MarginY      int
    Background   render.Color
    Foreground   render.Color
    BorderSize   int
    BorderStyle  BorderStyle
    BorderColor  render.Color
    OutlineSize  int
    OutlineColor render.Color
}

Config holds common base widget configs for quick configuration.

type DragDrop Uses

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

DragDrop is a state machine to manage draggable UI components.

func NewDragDrop Uses

func NewDragDrop() *DragDrop

NewDragDrop initializes the DragDrop struct. Normally your Supervisor will manage the drag/drop object, but you can use your own if you don't use a Supervisor.

func (*DragDrop) IsDragging Uses

func (dd *DragDrop) IsDragging() bool

IsDragging returns whether the drag state is active.

func (*DragDrop) SetWidget Uses

func (dd *DragDrop) SetWidget(w Widget)

SetWidget attaches the widget to the drag state, but does not start the drag; you call Start() after this if the subject is a widget.

func (*DragDrop) Start Uses

func (dd *DragDrop) Start()

Start the drag state.

func (*DragDrop) Stop Uses

func (dd *DragDrop) Stop()

Stop dragging. This will also clear the stored widget, if any.

func (*DragDrop) Widget Uses

func (dd *DragDrop) Widget() Widget

Widget returns the attached widget or nil.

type Edge Uses

type Edge int

Edge name

const (
    Top Edge = iota
    Left
    Right
    Bottom
    FollowCursor
)

Edge values.

type Event Uses

type Event int

Event is a named event that the supervisor will send.

const (
    NullEvent Event = iota
    MouseOver
    MouseOut
    MouseDown
    MouseUp
    Click
    KeyDown
    KeyUp
    KeyPress

    // Drag/drop event handlers.
    DragStop // if a widget is being dragged and the drag is done
    DragMove // mouse movements sent to a widget being dragged.
    Drop     // a "drop site" widget under the cursor when a drag is done

    // Window Manager events.
    CloseWindow
    MaximizeWindow
    MinimizeWindow
    CloseModal

    // Lifecycle event handlers.
    Compute // fired whenever the widget runs Compute
    Present // fired whenever the widget runs Present
)

Events.

type EventData Uses

type EventData struct {
    // Point is usually the cursor position on click and mouse events.
    Point render.Point

    // Engine is the render engine on Compute and Present events.
    Engine render.Engine

    // Supervisor is the reference to the supervisor who sent the event.
    Supervisor *Supervisor
}

EventData carries common data to event handlers.

type FocusedWindow Uses

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

FocusedWindow is a doubly-linked list of recently focused Windows, with the current and most-recently focused on top. TODO make not exported.

func (*FocusedWindow) Print Uses

func (fw *FocusedWindow) Print()

Print the structure of the linked list from top to bottom.

func (FocusedWindow) String Uses

func (fw FocusedWindow) String() string

String of the FocusedWindow returns the underlying Window's String().

type Frame Uses

type Frame struct {
    Name string
    BaseWidget
    // contains filtered or unexported fields
}

Frame is a widget that contains other widgets.

func NewFrame Uses

func NewFrame(name string) *Frame

NewFrame creates a new Frame.

func (*Frame) Add Uses

func (w *Frame) Add(child Widget) error

Add a child widget to the frame. When the frame Presents itself, it also presents child widgets. This method is safe to call multiple times: it ensures the widget is not already a child of the Frame before adding it.

func (*Frame) Children Uses

func (w *Frame) Children() []Widget

Children returns all of the child widgets.

func (*Frame) Compute Uses

func (w *Frame) Compute(e render.Engine)

Compute the size of the Frame.

func (*Frame) Pack Uses

func (w *Frame) Pack(child Widget, config ...Pack)

Pack a widget along a side of the frame.

func (*Frame) Place Uses

func (w *Frame) Place(child Widget, config Place)

Place a widget into the frame.

func (*Frame) Present Uses

func (w *Frame) Present(e render.Engine, P render.Point)

Present the Frame.

func (*Frame) Setup Uses

func (w *Frame) Setup()

Setup ensures all the Frame's data is initialized and not null.

type Image Uses

type Image struct {
    BaseWidget

    // Configurable fields for the constructor.
    Type  ImageType
    Image image.Image
    // contains filtered or unexported fields
}

Image is a widget that is backed by an image file.

func ImageFromFile Uses

func ImageFromFile(e render.Engine, filename string) (*Image, error)

ImageFromFile creates an Image by opening a file from disk.

func ImageFromTexture Uses

func ImageFromTexture(tex render.Texturer) *Image

ImageFromTexture creates an Image from a texture.

func NewImage Uses

func NewImage(c Image) *Image

NewImage creates a new Image.

func OpenImage Uses

func OpenImage(e render.Engine, filename string) (*Image, error)

OpenImage initializes an Image with a given file name.

The file extension is important and should be a supported ImageType.

func (*Image) Compute Uses

func (w *Image) Compute(e render.Engine)

Compute the widget.

func (*Image) GetRGBA Uses

func (w *Image) GetRGBA() *image.RGBA

GetRGBA returns an image.RGBA from the image data.

func (*Image) Present Uses

func (w *Image) Present(e render.Engine, p render.Point)

Present the widget.

type ImageType Uses

type ImageType string

ImageType for supported image formats.

type Label Uses

type Label struct {
    BaseWidget

    // Configurable fields for the constructor.
    Text         string
    TextVariable *string
    IntVariable  *int
    Font         render.Text
    // contains filtered or unexported fields
}

Label is a simple text label widget.

func NewLabel Uses

func NewLabel(c Label) *Label

NewLabel creates a new label.

func (*Label) Compute Uses

func (w *Label) Compute(e render.Engine)

Compute the size of the label widget.

func (*Label) Present Uses

func (w *Label) Present(e render.Engine, P render.Point)

Present the label widget.

func (*Label) Value Uses

func (w *Label) Value() string

Value returns the current text value displayed in the widget, whether it was the hardcoded value or a TextVariable.

type MainWindow Uses

type MainWindow struct {
    Engine render.Engine
    // contains filtered or unexported fields
}

MainWindow is the parent window of a UI application.

func NewMainWindow Uses

func NewMainWindow(title string, dimensions ...int) (*MainWindow, error)

NewMainWindow initializes the MainWindow. You should probably only have one of these per application. Dimensions are the width and height of the window.

Example: NewMainWindow("Title Bar") // default 640x480 window NewMainWindow("Title", 800, 600) // both required

func (*MainWindow) Add Uses

func (mw *MainWindow) Add(w Widget)

Add a child widget to the window's supervisor. This alone does not make the child widget render each frame; use Pack, Place or Attach for that.

func (*MainWindow) Attach Uses

func (mw *MainWindow) Attach(w Widget)

Attach a child widget to the window without its position managed. The widget's Present() method will be called each time the window Presents, but the positioning of the child widget must be handled manually by the caller.

Pack and Place are usually the methods you want to use to put a child widget into the window. One example use case for Attach is when you want to create child Window widgets which can be dragged by their title bars; their dynamic drag-drop positioning is best managed manually, and Pack or Place would interfere with their positioning otherwise.

This also calls .Add() to add the widget to the MainWindow's Supervisor.

Implementation details: - Adds the widget to the MainWindow's Supervisor. - Calls Frame.Add(w) so it will Present each time the main frame Presents. - Calls w.Compute() on your widget so it can calculate its initial size.

func (*MainWindow) Frame Uses

func (mw *MainWindow) Frame() *Frame

Frame returns the window's main frame, if needed.

func (*MainWindow) Loop Uses

func (mw *MainWindow) Loop() error

Loop does one loop of the UI.

func (*MainWindow) MainLoop Uses

func (mw *MainWindow) MainLoop() error

MainLoop starts the main event loop and blocks until there's an error.

func (*MainWindow) OnLoop Uses

func (mw *MainWindow) OnLoop(callback func(*event.State))

OnLoop registers a function to be called on every loop of the main window. This enables your application to register global event handlers or whatnot. The function is called between the event polling and the updating of any UI elements.

func (*MainWindow) Pack Uses

func (mw *MainWindow) Pack(w Widget, pack Pack)

Pack a child widget into the window's default frame.

func (*MainWindow) Place Uses

func (mw *MainWindow) Place(w Widget, config Place)

Place a child widget into the window's default frame.

func (*MainWindow) SetBackground Uses

func (mw *MainWindow) SetBackground(color render.Color)

SetBackground changes the window's frame's background color.

func (*MainWindow) SetTitle Uses

func (mw *MainWindow) SetTitle(title string)

SetTitle changes the title of the window.

func (*MainWindow) Supervisor Uses

func (mw *MainWindow) Supervisor() *Supervisor

Supervisor returns the window's Supervisor instance.

type Menu struct {
    BaseWidget
    Name string
    // contains filtered or unexported fields
}

Menu is a frame that holds menu items. It is the

Example of using the menu widgets.

Code:

mw, err := ui.NewMainWindow("Menu Bar Example", 800, 600)
if err != nil {
    panic(err)
}

// Create a main menu for your window.
menu := ui.NewMenuBar("Main Menu")

// File menu. Some items with accelerators, some without.
// NOTE: key bindings are up to you, the accelerators are
// purely decorative.
file := menu.AddMenu("File")
file.AddItemAccel("New", "Ctrl-N", func() {})
file.AddItemAccel("Open", "Ctrl-O", func() {})
file.AddItemAccel("Save", "Ctrl-S", func() {})
file.AddItem("Save as...", func() {})
file.AddSeparator()
file.AddItem("Close window", func() {})
file.AddItemAccel("Exit", "Alt-F4", func() {})

// Help menu.
help := menu.AddMenu("Help")
help.AddItemAccel("Contents", "F1", func() {})
help.AddItem("About", func() {})

// Give the menu bar your Supervisor so it can wire all
// events up and make the menus work.
menu.Supervise(mw.Supervisor())

// Compute and pack the menu bar against the top of
// the main window (or other parent container)
menu.Compute(mw.Engine)
mw.Pack(menu, menu.PackTop()) // Side: N, FillX: true

// Each loop you must then:
// - Call Supervisor.Loop() as normal to handle events.
// - Call Supervisor.Present() to draw the modal popup menus.
// MainLoop() of the MainWindow does this for you.
mw.MainLoop()

func NewMenu Uses

func NewMenu(name string) *Menu

NewMenu creates a new Menu. It is hidden by default. Usually you'll use it with a MenuButton or in a right-click handler.

func (w *Menu) AddItem(label string, command func()) *MenuItem

AddItem quickly adds an item to a menu.

func (w *Menu) AddItemAccel(label string, accelerator string, command func()) *MenuItem

AddItemAccel quickly adds an item to a menu with a shortcut key label.

func (w *Menu) AddSeparator() *MenuItem

AddSeparator adds a separator bar to the menu to delineate items.

func (w *Menu) Children() []Widget

Children returns the child frame of the menu.

func (w *Menu) Compute(e render.Engine)

Compute the menu

func (w *Menu) Pack(item *MenuItem)

Pack a menu item onto the menu.

func (w *Menu) Present(e render.Engine, p render.Point)

Present the menu

func (w *Menu) Rect() render.Rect

Rect returns the rect of the menu's body.

func (w *Menu) Size() render.Rect

Size returns the size of the menu's body.

func (w *Menu) Supervise(s *Supervisor)

Supervise the Menu. This will add all current and future MenuItem widgets to the supervisor.

type MenuBar struct {
    Frame
    // contains filtered or unexported fields
}

MenuBar is a frame that holds several MenuButtons, such as for the main menu at the top of a window.

func NewMenuBar Uses

func NewMenuBar(name string) *MenuBar

NewMenuBar creates a new menu bar frame.

func (w *MenuBar) AddMenu(label string) *MenuButton

AddMenu adds a new menu button to the bar. Returns the MenuButton object so that you can add items to it.

func (w *MenuBar) PackTop() Pack

PackTop returns the default Frame Pack settings to place the menu at the top of the parent widget.

func (w *MenuBar) Supervise(s *Supervisor)

Supervise the menu bar, making its child menu buttons work correctly.

type MenuButton struct {
    Button
    // contains filtered or unexported fields
}

MenuButton is a button that opens a menu when clicked.

After creating a MenuButton, call AddItem() to add options and callback functions to fill out the menu. When the MenuButton is clicked, its menu will be drawn and take modal priority in the Supervisor.

Example of using the MenuButton.

Code:

mw, err := ui.NewMainWindow("Menu Button", 800, 600)
if err != nil {
    panic(err)
}

// Create a MenuButton much as you would a normal Button.
btn := ui.NewMenuButton("Button1", ui.NewLabel(ui.Label{
    Text: "File",
}))
mw.Place(btn, ui.Place{ // place it in the center
    Center: true,
    Middle: true,
})

// Add menu items to it.
btn.AddItemAccel("New", "Ctrl-N", func() {})
btn.AddItemAccel("Open", "Ctrl-O", func() {})
btn.AddItemAccel("Save", "Ctrl-S", func() {})
btn.AddItem("Save as...", func() {})
btn.AddSeparator()
btn.AddItem("Close window", func() {})
btn.AddItemAccel("Exit", "Alt-F4", func() {})

// Add the button to Supervisor for events to work.
btn.Supervise(mw.Supervisor())

// Each loop you must then:
// - Call Supervisor.Loop() as normal to handle events.
// - Call Supervisor.Present() to draw the modal popup menus.
// MainLoop() of the MainWindow does this for you.
mw.MainLoop()

func NewMenuButton Uses

func NewMenuButton(name string, child Widget) *MenuButton

NewMenuButton creates a new MenuButton (labels recommended).

If the child is a Label, this function will set some sensible padding on its font if the Label does not already have non-zero padding set.

func (w *MenuButton) AddItem(label string, f func())

AddItem adds a new option to the MenuButton's menu.

func (w *MenuButton) AddItemAccel(label string, accelerator string, f func()) *MenuItem

AddItemAccel adds a new menu option with hotkey text.

func (w *MenuButton) AddSeparator()

AddSeparator adds a separator to the menu.

func (w *MenuButton) Compute(e render.Engine)

Compute to re-evaluate the button state (in the case of radio buttons where a different button will affect the state of this one when clicked).

func (w *MenuButton) Supervise(s *Supervisor)

Supervise the MenuButton. This is necessary for the pop-up menu to work when the button is clicked.

type MenuItem struct {
    Button
    Label       string
    Accelerator string
    Command     func()
    // contains filtered or unexported fields
}

MenuItem is an item in a Menu.

func NewMenuItem Uses

func NewMenuItem(label, accelerator string, command func()) *MenuItem

NewMenuItem creates a new menu item.

func NewMenuSeparator Uses

func NewMenuSeparator() *MenuItem

NewMenuSeparator creates a separator menu item.

type Pack Uses

type Pack struct {
    // Side of the parent to anchor the position to, like N, SE, W. Default
    // is Center.
    Side Side

    // If the widget is smaller than its allocated space, grow the widget
    // to fill its space in the Frame.
    Fill  bool
    FillX bool
    FillY bool

    Padding int // Equal padding on X and Y.
    PadX    int
    PadY    int
    Expand  bool // Widget should grow its allocated space to better fill the parent.
}

Pack provides configuration fields for Frame.Pack().

type Place Uses

type Place struct {
    // X and Y coordinates for explicit location of widget within its parent.
    // This placement option trumps all others.
    Point render.Point

    // Place relative to an edge of the window. The widget will stick to the
    // edge of the window even as it resizes. Options are ignored if Point
    // is set.
    Top    int
    Left   int
    Right  int
    Bottom int
    Center bool
    Middle bool
}

Place provides configuration fields for Frame.Place().

func (Place) Strategy Uses

func (p Place) Strategy() string

Strategy returns the placement strategy for a Place config struct. Returns 'Point' if a render.Point is used (even if zero, zero) Returns 'Side' if the side values are set.

type Side Uses

type Side uint8

Side is a cardinal direction.

const (
    Center Side = iota
    N
    NE
    E
    SE
    S
    SW
    W
    NW
)

Side values.

func (Side) IsCenter Uses

func (a Side) IsCenter() bool

IsCenter returns if the side is Center, N or S, to determine whether to align text as centered for North/South sides.

func (Side) IsEast Uses

func (a Side) IsEast() bool

IsEast returns if the side is E, NE or SE.

func (Side) IsMiddle Uses

func (a Side) IsMiddle() bool

IsMiddle returns if the side is Center, E or W, to determine whether to align text as middled for East/West sides.

func (Side) IsNorth Uses

func (a Side) IsNorth() bool

IsNorth returns if the side is N, NE or NW.

func (Side) IsSouth Uses

func (a Side) IsSouth() bool

IsSouth returns if the side is S, SE or SW.

func (Side) IsWest Uses

func (a Side) IsWest() bool

IsWest returns if the side is W, NW or SW.

type Supervisor Uses

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

Supervisor keeps track of widgets of interest to notify them about interaction events such as mouse hovers and clicks in their general vicinity.

func NewSupervisor Uses

func NewSupervisor() *Supervisor

NewSupervisor creates a supervisor.

func (*Supervisor) Add Uses

func (s *Supervisor) Add(w Widget)

Add a widget to be supervised. Has no effect if the widget is already under the supervisor's care.

func (*Supervisor) CloseAllWindows Uses

func (s *Supervisor) CloseAllWindows() int

CloseAllWindows closes all open windows being managed by supervisor. Returns the number of windows closed.

func (*Supervisor) DragStart Uses

func (s *Supervisor) DragStart()

DragStart sets the drag state without a widget.

An example where you'd use this is if you want a widget to respond to a Drop event (mouse released over a drop-site widget) but the 'thing' being dragged is not a ui.Widget, i.e., for custom app specific logic.

func (*Supervisor) DragStartWidget Uses

func (s *Supervisor) DragStartWidget(w Widget)

DragStartWidget sets the drag state to true with a target widget attached.

The widget being dragged is given DragMove events while the drag is underway. When the mouse button is released, the widget is given a DragStop event and the widget below the cursor is given a Drop event.

func (*Supervisor) DragStop Uses

func (s *Supervisor) DragStop()

DragStop stops the drag state.

func (*Supervisor) FocusWindow Uses

func (s *Supervisor) FocusWindow(win *Window) error

FocusWindow brings the given window to the top of the supervisor's focus.

The window must have previously been added to the supervisor's Window Manager by calling the Supervise() method of the window.

func (*Supervisor) GetModal Uses

func (s *Supervisor) GetModal() Widget

GetModal returns the modal on the top of the stack, or nil if there is no modal on top.

func (*Supervisor) Hovering Uses

func (s *Supervisor) Hovering(cursor render.Point) (hovering, outside []WidgetSlot)

Hovering returns all of the widgets managed by Supervisor that are under the mouse cursor. Returns the set of widgets below the cursor and the set of widgets not below the cursor.

func (*Supervisor) IsDragging Uses

func (s *Supervisor) IsDragging() bool

IsDragging returns whether the drag state is enabled.

func (*Supervisor) IsPointInWindow Uses

func (s *Supervisor) IsPointInWindow(point render.Point) bool

IsPointInWindow returns whether the given Point overlaps with a window managed by the Supervisor.

func (*Supervisor) Loop Uses

func (s *Supervisor) Loop(ev *event.State) error

Loop to check events and pass them to managed widgets.

Useful errors returned by this may be: - ErrStopPropagation

func (*Supervisor) PopModal Uses

func (s *Supervisor) PopModal(w Widget) bool

PopModal attempts to pop the modal from the stack, but only if the modal is at the top of the stack.

A widget may safely attempt to PopModal itself on a CloseModal event to close themselves when the user clicks outside their box. If there were a newer modal on the stack, this PopModal action would do nothing.

func (*Supervisor) Present Uses

func (s *Supervisor) Present(e render.Engine)

Present all widgets managed by the supervisor.

NOTE: only the Window Manager feature uses this method, and this method will render the windows from bottom to top with the focused window on top. For other widgets, they should be added to a parent Frame that will call Present on them each time the parent Presents, or otherwise you need to manage the presentation of widgets outside the Supervisor.

func (*Supervisor) PushModal Uses

func (s *Supervisor) PushModal(w Widget) int

PushModal sets the widget to be a "modal" for the Supervisor.

Modal widgets have top-most event priority: mouse and click events go ONLY to the modal and its descendants. Modals work as a stack: the most recently pushed widget is the active modal, and popping the modal will make the next most-recent widget be the active modal.

If a Click event registers OUTSIDE the bounds of the modal widget, the widget receives a CloseModal event.

Returns the length of the modal stack.

func (*Supervisor) Widgets Uses

func (s *Supervisor) Widgets() <-chan WidgetSlot

Widgets returns a channel of widgets managed by the supervisor in the order they were added.

type Tooltip Uses

type Tooltip struct {
    BaseWidget

    // Configurable attributes.
    Text         string  // Text to show in the tooltip.
    TextVariable *string // String pointer instead of text.
    Edge         Edge    // side to display tooltip on
    // contains filtered or unexported fields
}

Tooltip attaches a mouse-over popup to another widget.

Tooltip usage example.

Code:

mw, err := ui.NewMainWindow("Tooltip Example", 800, 600)
if err != nil {
    panic(err)
}

// Add a widget that will have a tooltip attached, i.e. a button.
btn := ui.NewButton("My Button", ui.NewLabel(ui.Label{
    Text: "Hello world!",
}))
mw.Place(btn, ui.Place{
    Center: true,
    Middle: true,
})

// Add a tooltip to it. The tooltip attaches itself to the button's
// MouseOver, MouseOut, Compute and Present handlers -- you don't need to
// place the tooltip inside the window or parent frame.
ui.NewTooltip(btn, ui.Tooltip{
    Text: "This is a tooltip that pops up\non mouse hover!",
    Edge: ui.Right,
})

mw.MainLoop()

func NewTooltip Uses

func NewTooltip(target Widget, tt Tooltip) *Tooltip

NewTooltip creates a new tooltip attached to a widget.

func (*Tooltip) Compute Uses

func (w *Tooltip) Compute(e render.Engine)

Compute the size of the tooltip.

func (*Tooltip) Present Uses

func (w *Tooltip) Present(e render.Engine, P render.Point)

Present the tooltip.

func (*Tooltip) Value Uses

func (w *Tooltip) Value() string

Value returns the current text displayed in the tooltop, whether from the configured Text or the TextVariable pointer.

type Widget Uses

type Widget interface {
    ID() string           // Get the widget's string ID.
    IDFunc(func() string) // Set a function that returns the widget's ID.
    String() string
    Point() render.Point
    MoveTo(render.Point)
    MoveBy(render.Point)
    Size() render.Rect    // Return the Width and Height of the widget.
    FixedSize() bool      // Return whether the size is fixed (true) or automatic (false)
    BoxSize() render.Rect // Return the full size including the border and outline.
    Resize(render.Rect)
    ResizeBy(render.Rect)
    ResizeAuto(render.Rect)
    Rect() render.Rect // Return the full absolute rect combining the Size() and Point()

    Handle(Event, func(EventData) error)
    Event(Event, EventData) error // called internally to trigger an event

    // Thickness of the padding + border + outline.
    BoxThickness(multiplier int) int
    DrawBox(render.Engine, render.Point)

    // Widget configuration getters.
    Margin() int                  // Margin away from other widgets
    SetMargin(int)                //
    Background() render.Color     // Background color
    SetBackground(render.Color)   //
    Foreground() render.Color     // Foreground color
    SetForeground(render.Color)   //
    BorderStyle() BorderStyle     // Border style: none, raised, sunken
    SetBorderStyle(BorderStyle)   //
    BorderColor() render.Color    // Border color (default is Background)
    SetBorderColor(render.Color)  //
    BorderSize() int              // Border size (default 0)
    SetBorderSize(int)            //
    OutlineColor() render.Color   // Outline color (default Invisible)
    SetOutlineColor(render.Color) //
    OutlineSize() int             // Outline size (default 0)
    SetOutlineSize(int)           //

    // Visibility
    Hide()
    Show()
    Hidden() bool

    // Container widgets like Frames can wire up associations between the
    // child widgets and the parent.
    Parent() (parent Widget, ok bool)
    SetParent(parent Widget) // for the container to assign itself the parent
    Children() []Widget      // for containers to return their children

    // Run any render computations; by the end the widget must know its
    // Width and Height. For example the Label widget will render itself onto
    // an SDL Surface and then it will know its bounding box, but not before.
    Compute(render.Engine)

    // Render the final widget onto the drawing engine.
    Present(render.Engine, render.Point)
}

Widget is a user interface element.

type WidgetSlot Uses

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

WidgetSlot holds a widget with a unique ID number in a sorted list.

type Window Uses

type Window struct {
    BaseWidget
    Title string

    // Title bar colors. Sensible defaults are chosen in NewWindow but you
    // may customize after the fact.
    ActiveTitleBackground   render.Color
    ActiveTitleForeground   render.Color
    InactiveTitleBackground render.Color
    InactiveTitleForeground render.Color
    // contains filtered or unexported fields
}

Window is a frame with a title bar.

Example of using the Supervisor Window Manager.

Code:

mw, err := ui.NewMainWindow("Window Manager Example", 800, 600)
if err != nil {
    panic(err)
}

// Create a window as normal.
window := ui.NewWindow("Hello world!")
window.Configure(ui.Config{
    Width:  320,
    Height: 240,
})

// Configure its title bar colors (optional; these are the defaults)
window.ActiveTitleBackground = render.Blue
window.ActiveTitleForeground = render.White
window.InactiveTitleBackground = render.DarkGrey
window.InactiveTitleForeground = render.Grey

// Configure its window buttons (optional); default has no window buttons.
// Window buttons are only functional in managed windows.
window.SetButtons(ui.CloseButton | ui.MaximizeButton | ui.MinimizeButton)

// Add some widgets to the window.
btn := ui.NewButton("My Button", ui.NewLabel(ui.Label{
    Text: "Hello world!",
}))
window.Place(btn, ui.Place{
    Center: true,
    Middle: true,
})

// To enable the window manager controls, the key step is to give it
// the Supervisor so it can be managed:
window.Compute(mw.Engine)
window.Supervise(mw.Supervisor())

// Each loop you must then:
// - Call Supervisor.Loop() as normal to handle events.
// - Call Supervisor.Present() to draw the managed windows.
// MainLoop() of the MainWindow does this for you.
mw.MainLoop()

func NewWindow Uses

func NewWindow(title string) *Window

NewWindow creates a new window.

func (*Window) Children Uses

func (w *Window) Children() []Widget

Children returns the window's child widgets.

func (*Window) Close Uses

func (w *Window) Close()

Close the window, hiding it from display and calling its CloseWindow handler.

func (*Window) Compute Uses

func (w *Window) Compute(e render.Engine)

Compute the window.

func (*Window) Configure Uses

func (w *Window) Configure(C Config)

Configure the widget. Color and style changes are passed down to the inner content frame of the window.

func (*Window) ConfigureTitle Uses

func (w *Window) ConfigureTitle(C Config)

ConfigureTitle configures the title bar widget.

func (*Window) Focused Uses

func (w *Window) Focused() bool

Focused returns whether the window is focused.

func (*Window) Maximized Uses

func (w *Window) Maximized() bool

Maximized returns whether the window is maximized.

func (*Window) Pack Uses

func (w *Window) Pack(child Widget, config ...Pack)

Pack a child widget into the window's main frame.

func (*Window) Place Uses

func (w *Window) Place(child Widget, config Place)

Place a child widget into the window's main frame.

func (*Window) Present Uses

func (w *Window) Present(e render.Engine, P render.Point)

Present the window.

func (*Window) SetButtons Uses

func (w *Window) SetButtons(buttons int)

SetButtons sets the title bar buttons to show in the window.

The value should be the OR of CloseButton, MaximizeButton and MinimizeButton that you want to be enabled.

Window buttons only work if the window is managed by Supervisor and you have called the Supervise() method of the window.

func (*Window) SetFocus Uses

func (w *Window) SetFocus(v bool)

SetFocus sets the window's focus value. Note: if you're using the Supervisor to manage the windows, do NOT call this method -- window focus is managed by the Supervisor.

func (*Window) SetMaximized Uses

func (w *Window) SetMaximized(v bool)

SetMaximized sets the state of the maximized window. Must have called Compute() once before so the window can hang on to the render.Engine, to calculate the size of the parent window.

func (*Window) Supervise Uses

func (w *Window) Supervise(s *Supervisor)

Supervise enables the window to be dragged around by its title bar by adding its relevant event hooks to your Supervisor.

func (*Window) TitleBar Uses

func (w *Window) TitleBar() *Frame

TitleBar returns the title bar widget.

Directories

PathSynopsis
eg
eg/frame-placeExample script for using the Place strategy of ui.Frame.
eg/hello-world
eg/tooltip
theme

Package ui imports 14 packages (graph) and is imported by 4 packages. Updated 2020-08-12. Refresh now. Tools for package owners.